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
687
Hello Hi Guys How Are You I Hope All You Are Doing Good Welcome To The Land Cords Lee Today Will Do The Longest Union Value Path Withdrawal Question So Let's Video Give Inside And Outside Returns The Length Of The Longest Pass Thursday And Not Passed Through The length of the match between to note servi now in which will not the length of the number of subscribe now to the part of the little bit pieky birth but not s hard s you know a little bit vacation you can solve between there sorrow And its improvement award function is veervar [praise] [praise] [praise] a soap [praise] [praise] [praise] and safed meaning of 108 laung ispat and this root is so I make that a function and a game for storing the maximum volume maximum length hai ki maang hai all the meaning of Length Swasthya to maintain Vaikuntha variable max variable in this annual is so first ayurveda call fruit a [ so first ayurveda call fruit a [ so first ayurveda call fruit a [ pramshan] pramshan] pramshan] kar dena hai maintaining Tubelight is left and right and left will call for the left [ pramshan] pramshan] pramshan] hai Android m calling from the right toe [ [Praise] [ [Praise] [ [Praise] That boat gift Abhay Root [Praise] That depth of I 10 Not fixed to none and that rudded well [Praise rudded well [Praise rudded well [Praise ] ] ] That it is equal to the 9th to the left I left side is 0 [Praise] The [Praise] The [Praise] The right side of Zero [praise] have done all right [ right [ right [ praise] have done praise] have done 102 Not have left or right Significance of Bus Calculator will calculate the match The maximum disturbance till nine som On A&B Happy Return I Maths Of I Sleep On The Right Side Inside Left Side You Return Hair Maximum Morning Hour M Calling Alarms Calling Loot Show Fear Of Mysticism Moment Person Then Implementing A Cliff Route Byte Route Off List Were Route of leaders not equal 19 feet in this how can compare can see the laptop fit and this is name five years by check Delhi 100 feet is prescription hai sanwarlu subah us check the route beet route start top ten sport and route of laptop and mid -day-mile now school and route of laptop and mid -day-mile now school and route of laptop and mid -day-mile now school increment left side one should you know it is the meaning of the same 2009 right side subscribe button from left side to right side this is becoming too length of shame vaginal value talk but happy return of the match Jor right side hai tomorrow morning aap return gift uddh axis in this will return here one happened 102 that this to 9 elite and even when the welcome one should be felt in the middle of the night sweet will happen in the same manner Sukhbir and Maximum Volume Maximum Difficulty Is Add All The Maximum Is Illness Serious And Holding Every Time The Maximum Is Univalent Pat A Select Committee NC Hard Working 108 Has Been Done Limited 998 Submitted Her Home In The State Were Traveling Every Time You Were Not The Only One So It's Very Slow Very Little Bit Unit Tool Practice How To Do The Question Is No How To Years When You Can Do It Is Lee Sanseri Hai Way Do I Will Meet In X Video MP Samvida Next Video Bye-Bye Take Care And Please Like Bye-Bye Take Care And Please Like Bye-Bye Take Care And Please Like Subscribe And Comment And Don't FORGET TO SUBSCRIBE GUYS TAKE CARE A ON THIS VIDEO
Longest Univalue Path
longest-univalue-path
Given the `root` of a binary tree, return _the length of the longest path, where each node in the path has the same value_. This path may or may not pass through the root. **The length of the path** between two nodes is represented by the number of edges between them. **Example 1:** **Input:** root = \[5,4,5,1,1,null,5\] **Output:** 2 **Explanation:** The shown image shows that the longest path of the same value (i.e. 5). **Example 2:** **Input:** root = \[1,4,5,4,4,null,5\] **Output:** 2 **Explanation:** The shown image shows that the longest path of the same value (i.e. 4). **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-1000 <= Node.val <= 1000` * The depth of the tree will not exceed `1000`.
null
Tree,Depth-First Search,Binary Tree
Medium
124,250,437
344
Ki Welcome Back Everyone in this Video Bihar Ko * Solid Code Easy Level Question and the Ko * Solid Code Easy Level Question and the Ko * Solid Code Easy Level Question and the Question is Reverse Swing in this question will be given and head of characters and what we have two years were written directed by reversing the no1 extra memory ok soft Video Subscribe Element Villain - - Unmarried Subscribe Element Villain - - Unmarried Subscribe Element Villain - - Unmarried Is The Mean Of The Day That So And Flowers Only And i20 Phone Online There Is Five Okay Length Is 500 To That They 125 - E - 150 - 150th Comments Roy And The 125 - E - 150 - 150th Comments Roy And The 125 - E - 150 - 150th Comments Roy And The Elements And Coasts 21 Dead - Verb - Elements And Coasts 21 Dead - Verb - Elements And Coasts 21 Dead - Verb - Wonderland - 25 - 235 They Saw A Pretty Simple The Wonderland - 25 - 235 They Saw A Pretty Simple The Wonderland - 25 - 235 They Saw A Pretty Simple The Code And Soft And Dates To Length Of That Sn Hai Lunch Ok 204 That In Tie Cost Him Zor Loop By Two Yes Brother Plus A Friend Rail Ticket That TDS Charge Anil Store Apps Of This Is in it's okay now it's clear I will be requested to have so half learned - I - one okay and that's half learned - I - one okay and that's half learned - I - one okay and that's such a plan - 22 - One will be reached to such a plan - 22 - One will be reached to such a plan - 22 - One will be reached to tier e and e don't have written a thing The Amazing with oo I am in your show Bigg Boss Reverse String Easy Level Questions IF Everyone Gets Injured Video Thank You So Much and Bye-Bye
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. **Example 1:** **Input:** s = \["h","e","l","l","o"\] **Output:** \["o","l","l","e","h"\] **Example 2:** **Input:** s = \["H","a","n","n","a","h"\] **Output:** \["h","a","n","n","a","H"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
Two Pointers,String,Recursion
Easy
345,541
5
how's it going everyone today we're gonna try to solve one of the really popular questions on li code this is gonna be the something called the longest palindromic substring now if we look at this question majority of the people would solve it in various ways that it's kind of brute force e but actually in this episode I'm gonna try to go through something that is a little bit more on the advanced topic we're still gonna try to go through to solve this in the traditional way but I thought I throw a little bit of nice little tricks in there to make you have an ability to saw this in a web and time okay cool so let's first try to understand the question okay longest palindromic substring let's read the question given a string s find the longest palindromic substring in s you may use you may assume that the maximum length of s is 1,000 cool so for maximum length of s is 1,000 cool so for maximum length of s is 1,000 cool so for those who don't know what a palindrome in is it's pretty much something where if you take the midpoint if you look to your left you look to your right everything beside you going out is the same for example a word like race car would be a palindrome something like a b a that's a palindrome because in the middle between the two a's you basically see a mirror image of one another right cool so let's look at a quick example this is really self-explanatory you know the palindrome self-explanatory you know the palindrome self-explanatory you know the palindrome the biggest pile of German here is something in the middle you know is three of size three right and the next palindrome on this one is of size two cool now I wanted to actually dive deeper into this question because one way to solve these type of questions what we could do is iterate through each element and then as you are in a specific element you can start expanding outwards to see if it's a palindrome or not although that can solve the problem for example you go here and you expend left and you spend right can expand go here expand left right you can't go here you can spend right and left you go be excited cetera that you can solve it that's like a brute-force away and your that's like a brute-force away and your that's like a brute-force away and your time complexity is quite high effectively you're forcing your algorithm to go through the question like twice or and square it in a sense so we're gonna try to go and review a really cool more advanced algorithm to solve this question this algorithm is actually called the manager or manager I'm probably pronouncing really horribly but it that's what it's called and we're gonna actually go through it right now so let me explain it I'm gonna try a new different topic I'll try to bring it up as a you know a presentation to see if you guys like this format more okay so let's begin to look at this algorithm let's use an example because examples are always great to explain a difficult concept so the example I'm giving here is you know and B are right by the looks of it just by eyeballing we know the highest the longest palindrome contained here is gonna be of size four right but in monikers or manicure I on you know what is called manicures algorithm what we need to do first is to address the question of whether the string is even or odd so one of the very first things we would want to do is try to manipulate this string such that you know regardless if it's even or odd we're still gonna get the same results right so the next step we want to do is you know adjust the string boom alright let's focus on the thing I've highlighted here first we'll talk about the bottom elements and top later on but I just basically manipulated the previous string and inserted money signs in between each of the characters this ensures that you know regardless if it's an even or odd string effectively I can still solve this problem right it doesn't matter cool so once we have that what we also need to do is create an array that basically tracks what are the longest powered rims as we go along on this adjusted string right cool the next thing in this algorithm that we need to really focus on is the concept of mirroring I'll dive deeper as we go along this example and you'll probably get the reference of what I'm talking about but that's something that you have to think where you know as an example if I take a random figure like n the mirror value for this would be something like this will be there n prime I won't dive into until we get to that point but let's continue with this example so one of the requirements we need to do is iterate through this string and do a series of checks right our first check to see is that okay at arch and I equal to 0 at the beginning point let's set our center point which is the center of our longest palindrome and to 0 and also let's move Valar i to its beginning position right so our first task is to check ok well how many times can I expand right and left and such times still a palindrome in this case it's 0 right so that's fine that's simple you basically update this to 0 cool now the next step new we need to do is move the I to the next level right in here we're going to look at ok well is this is my longest palindrome 0 mmm not really because my left and right I could still expand right so once I find a palindrome that is of size that's greater than my previous one well let's set the center to equal to this end and update this value to 1 now one of the things that we need to keep track of in the in this algorithm is an idea of our rightmost boundary right or what is your boundary on your most thinking ahead of you what I mean by that is that we may need to create a flag are on top of this particular index I'll dive deeper into that later but well we'll just go into that so cool we set a flag here because once you have this right flag that's one indicator when we can check okay well if we should repeat something or not right I'll go through an example what I mean so well this is this power drill is satisfied so what we're gonna do next right we're gonna go in here and check okay well is this gonna be a palindrome well not really because you're sitting on top of our your rightmost battery and there's no really thing very cold over here although you could look at this one that looks the same but you know that doesn't tell you much so I'm just gonna go okay well this is not a boundary so I'm gonna keep it as like the zero it doesn't do anything to me right so I'm gonna go move my thing keep going along keep expanding so I'm hearing now right on B so what happens here so on B I'm already above my R which is gonna be like okay well if we look at if we expand left and right our longest palindrome in this case is gonna be one two three right this is our longest palindrome we're gonna change it to three but we're gonna also move where I said before this to the rightmost flag right and then I'm gonna set this particular I love my Center into my longest segment cool so that's relatively simple right nothing difficult here but this is where the power begins when we move on to the next step so when we go in here move along the I again if I check what if my I is less than my right boundary right what can I do here in a sense so we know that the power drum on I if this was my Center the maximum this can be would either equal to the minimum of what my counterpart would be which is this one which is zero or the boundary of what my right would be right because that's like the attribute of a palindrome right your left will equal to your right so therefore your little brother or little partner here should be equal to what you have as at them at the very least right so what we can do right now is see like okay can I expand in this case if it's zero or are - my position - if it's zero or are - my position - if it's zero or are - my position - if it's zero to the minimum of those two elements well I'm gonna take the zero as my position cool and then I'm gonna go check you know if my left and right would actually do anything well in this case zero is probably my right solution great let's move on along okay cool so in this case same thing less than our checking here your counterpart over here is this one and we know that okay it can be a 1 we can insert that either our - I be a 1 we can insert that either our - I be a 1 we can insert that either our - I or n they're both equal to 1 so we're gonna actually say alright let's keep this as one great alright so the next step is gonna move on to hear more on top of our right once we're here we're gonna go check out okay well I can't check even my up my right bounding anymore because I'm on top of it so what do I need to do well we're gonna start checking left and right and start expanding beyond that so I could expand it seems like okay well I could spent all the way down to 4 right so we're gonna update this number to 4 and put this on the right boundary to this particular element and ensure that this comes in here great now we can continue along and move along in this element again and effectively go and check if my I is less than R it is less than R I'm gonna go check over here of less it's gonna be one or two the less of those two I'm going to take this as 1 oops not that value oops change that to one great and then I'm gonna effectively see if it is the case which is the case great because I could start from these two variables that's great and expand doesn't make sense and move along cool now I am going to ensure that check on this particular value so it's going to be zero or two take the zero and I check left and right of course it's zero go on to be B over here it's gonna be either three or one this is an interesting one so it could be three or one so I'm gonna make sure that I gotta go okay I'm gonna change it to one because I'm taking the less of the two which is the case in here great we going to hear boom same case I'm on top of it I can check left and right I can't go anywhere that's fine so my boundary just stays the same doesn't do anything my new Center is not the same and then BOOM keep going along am i right cool and then update this particular value to here move this to the center and boom this is gonna be my value of one right so by doing this we keep track of our maximum palindrome on this way and from this we can actually solve the problem really quickly just read the longest one and then there's your palindrome so let's go to some code and what we will but understanding a little bit more all right we're back at the code all right let's try to solve this so one of the first things remember our reference before what we need to do is to adjust the string to accommodate for the edge cases of even and odd numbers so let's do that I'm gonna go Const equals to a I'm gonna call this like new string will equal to I'm gonna grow a helper function because here's a actually pro tip if you were to go through an interview and if you won't know you need to do something but you don't have time to do it you could explain to the interviewer what you're trying to do and use a helper function to return the result that you want so for example in here I'm gonna get something called get if I'd string and passing the s and you got let the interview know that okay what this really does is just add money signs to the string that you're interested and so on and so forth cool this will save a lot of time for you and if you have time at the end of the interview you can actually write this equation out but for now we're just gonna go and create this helper function I will write down that segment later on but for now we understand that okay this basically creates those hashes there the next thing we want to do is to create that p function you could be an p array which I'm gonna call P is a new array of size a new string dot length right and then I'm gonna fill it with zeros so what this really does is like creating the saw equal size of that particular string filling it with zeros great now my next step remember what I said before in my presentation that we need to keep track of a few things we need to keep track of where our Center is and we also need to keep track of where the right boundary would be right so let's do that let's send Center B 0 and let right bow equal to 0 for now because we start from 0 great cool now here's the fun part now we're gonna actually start iterating through the character so we're gonna do that for let I equal to 0 and it's gonna be less than the new string length and i's gonna plus right cool ok so what are we gonna do here so one of the things that we need to keep track of is the center of where you know where we have to mirror okay where's our index the mirrored index so remember when i was looking back earlier talking about okay well let me go back to an example so when we're looking at this the mirror value is here well we if we have the center point here we want to find the index of its mirror it's basically the same thing as Center you know it's basically Center - the I you know it's basically Center - the I you know it's basically Center - the I mean sorry this - the center you'll get mean sorry this - the center you'll get mean sorry this - the center you'll get a value and then you don't bring it back in here so let's get back in here so the equation is relatively simple it's gonna be let the index mirror equal to center - the index she's it's might be ya index - index she's it's might be ya index - index she's it's might be ya index - Center cool so that will basically tell me where my mirror index would be okay so in here it's gonna be zero that's do anything that's great so one of the things we need to do now is to check well is my eye less is it basically on my right boundary right so we're gonna have to do a check is like if my eye is less than my right boundary if it is the case I'm going to update my P of I P of i2 equal to my minimum math.min of basically what to my minimum math.min of basically what to my minimum math.min of basically what we were saying before which is the right boundary - the eye or the P at the boundary - the eye or the P at the boundary - the eye or the P at the mirror value index no score mirror well I can use camel case that's probably better JavaScript e cool great so let's shrink this over here great cool what does this da do it's basically what we were mentioning earlier we're gonna check if the value is less than the right boundary and then take the less of those two great now this is where we start doing the expansion the expanding game okay so let's go and try to expand left and right let's define that first let's let left equals to I plus I'm gonna go and say like eight where I'm at right now G's plus okay I'm gonna go and save my P of I position right plus one right because I want to go oh not if I go one is right I'm gonna go one ahead of me and one behind me right so I'll do that and let's go look at that let's go here go on left the left is like the opposite a minus that value alright great so I know my left and right boundaries right so my next thing to do is well let's go and I'll go this spacing is horrible sorry excuse my things okay cool the next thing to do here is basically check annex start expanding my left and right so I'm gonna go and write a quick while loop Wow my right is less than the length new string length so basically I won't expand beyond my right boundary and my left is greater than or equal to zero and also my new string at the left position is equal to my new string on my right position basically if there's like if those position are equal to the same what I'm gonna do I'm just gonna increase the value over here by one and I'm also gonna expand more on the right and left so I'm gonna go right plus left - - great okay cool so now we have left - - great okay cool so now we have left - - great okay cool so now we have this thing let's go and try to look at okay let's go and try to explain this a little bit okay so we've already expanded that's great now what do we do when we hit the boundaries what we're gonna do in here is gonna go like basically check if my eye position plus my p @ @ i right is gonna be plus my p @ @ i right is gonna be plus my p @ @ i right is gonna be greater than right boundary is it gonna be greater than that if it is well I'm gonna go and readjust my Center will equal to my eye position right so I'm saying that if where I'm at in my time I'll overlapping the right boundary or being a little bit more I'm gonna adjust my new Center and also set the right boundary to equal to my I plus plea and I great cool so this pretty much covers majority of the algorithm I'm gonna paste in some code that I've written before to do it you know to deal with this string here which I'm gonna give me a second I'm gonna paste it in here so I don't waste anyone's time cool I could just go constant that equals to the word cool so what this pretty much does is that you know adds hashes to the word and it returns instead of money I'm gonna use hashes that's what it does right it returns that but we're not quite done yet right because right now all we have done is construct a P of I that tells me where is the longest palindrome right we still have to return the actual palindrome itself right so one of the things we need to do is start doing that so last bits of stuff is gonna go and see like what is the maximum length I'm gonna call length well math max I'm gonna spread what spread LV element on P to identify what the maximum length is and let the index of well that will be Pete index of length cool now we help the backs of leg that when you know when the index of that would be I'm gonna start returning the new string dot substring stop string and I'm gonna go and define it as my index minus length plus 1 and length sorry I'm I need some water here index plus length cool once we have that substring of that total substring from the beginning to end for the longest air segment I'm gonna make sure I get rid of those hash tags so I'm gonna go split hash tag great geez come on cooperate okay I get rid of those hash tags and I'm gonna join the string again cool by doing this effectively I have I should have solved the problem there is an edge case that you know I wanted to deal with not edge case but I wanted to you know not have to deal with all this stuff with my sight string a size one so I'm gonna do anything here if my s all like this is gonna be less than one which is you know it can be an edge case I'm just gonna return s which is fine cool so I think this is uh this will solve a problem so let's see how it actually works great accept it and it's a hundred percent beating everybody else so I hope everybody understands this I know there's a little bit more complicated algorithm to think about however I know the results are here it's fast I beat everybody and I just did a life that's pretty cool and yeah so that's it hope you guys hit that subscribe hit that give me a like give me a comment let me know if you like this new format of me explaining things on the PowerPoint I know I'm just trying to do it as one take as much as I can I'm trying to not edit as much as possible so you get the raw deal or you see the struggle I experienced because no not everyone's perfect I know videos you can make sometimes make it perfect however I want to give you the real deal so stay tuned for the next episode thanks for attending bye
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
1,047
hi everyone it's Soren today we have a problem when we are given a string s and we need to repeatedly make a duplicate removals from s until we no longer can so what's a duplicate is if the two adjacent characters are equal so for example in this case we have a b a c a so these two characters are equal right so we are removing them now we have a c a and again these two characters are also adjacent two characters are equal right so we are removing also these two now we have CA and we are returning CA as a result we are going to solve this problem using a stack data structure so what we are going to do to our stack so let's take this example a B A CA the example that we have seen earlier so what we do starting from the first character we are adding that to our stack so for example in this case first we are adding a the next one so as we are adding the character so we are checking that is the previous character in a stack is that equals to our current character so for example we are adding a because there is no character in the stack so the next one we are adding what we are adding B so again we are we want to add the next pep but we are checking okay if the top character is equals to our this character B right yes it equals so we are removing the this character also from the stack right so we are removing this character from the stack and now we are adding the next one is a right we are adding a we are trying to add a is the a is it equals to A yes it equals to A so we are also removing from the stack this character so the next one we are adding C and we are checking that is the next one is a equals to C no so we are adding a here and the last one is that we are going over our stack and adding that to the so we are forming a new string and returning that as a result so what's the time and space complexity in this case the time complexity is we are going over our string only once so it's of n and the space complexity is we are using stack and for the stack in the worst case scenario our space complexity is also going to be off n okay first thing that we do here we are creating a stack with the type is being the character so we are going over our string and for each character we are checking if our stack is not empty and if our the element that is on the top of the stack if that equals to our current character so what we do we are taking that character from the stack because they are adjacent to adjacent uh characters that are equal if not then we are adding that character to our stack and once we exit this Loop we have we don't have no longer two adjacent characters that are equal so we are building up our result so for that we are using a string Builder and we are going over our stack until it's empty and we are adding inserting the to the zero character why because for example in the stack uh in our previous example right so the characters are first is a and the next one is C but the correct result should be the correct result that we should return should be ca right CA so that's for that reason we are adding the character to the zero index making sure that uh we have the correct order so should be in reverse order and at the end we are just returning a result okay that's it uh that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
Remove All Adjacent Duplicates In String
maximize-sum-of-array-after-k-negations
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them. We repeatedly make **duplicate removals** on `s` until we no longer can. Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**. **Example 1:** **Input:** s = "abbaca " **Output:** "ca " **Explanation:** For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ". **Example 2:** **Input:** s = "azxxzy " **Output:** "ay " **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters.
null
Array,Greedy,Sorting
Easy
2204
1,611
as most of you know every day we try to pick one the code one interview experience from read code and try to solve all the interesting question of the interview experience not only that we also try to solve all the possible follow-ups of solve all the possible follow-ups of solve all the possible follow-ups of that particular question that can be asked during an interview so we have already solved a lot of interview experiences from microsoft facebook amazon and others i will link them in the description below do check them out you will be amazed to see how a very easy problem turns into a very hard problem of lead code so do check them out in this particular video we will be looking at this linkedin interview experiences of january the first question we will be not we will not be discussing because we have already discussed this kind of question several times in our channel i will link some of these some of the questions that are of similar type in the description below i will strongly encourage you to solve it on your own and if you have any doubts you can link it you can comment down below and i will answer them or if you want me to create a separate video for this particular question uh do mention it below i will create that as well let's discuss the second problem so the second problem is basically we are given an integer n and we have to transform this integer n to zero by performing some operations we have to we can perform two type of operation the first operation is change the right most bit to zero if it is like change the right most bit basically if it is zero change it to one if it is one change it to zero similarly the second operation is we can change the if bit if i minus 1 bit is 1 and all the bits after i minus 1 which is i minus 2 to 0 all are 0 so we have to find the minimum number of operations that will be required to make this n to zero so let's understand this is an example so let's say the number is one zero then we can apply the second kind of operation so first operation is i think very straight forward just change the right most bit so second operation like if this is the number we can change this to this because this is the 8th bit let's assume so i minus 1 8th bit is 1 that's correct and all the bits after i minus 1 is 0 so that's where we can apply second kind second operation second type of operation here to convert this to this but notice that we can't uh if the number is this we can't convert it to uh this because if the bit is like if this is it bit then this is one that's fine but after this not all of them are 0 like this is not 0 right so that's where we can't perform this operation so hope the question is now clear now let's just look at an example let's say we have to convert this convert 6 to 0 and you have to find the minimum number of operations to do that so 6 is represented as 1 0 in binary so here what we have done is we have first performed the second kind of operation so this is the ith bit and we can see i minus one bit is one and all the bits after this is zero so that's where we can we have performed second kind of operation to come to this stage from here we perform the first kind of operation to change the right most bit from here we again perform the second kind of operation so basically this is the 8th bit in this case so i minus 1 bit is 1 and all the bit after this is zero so there is nothing after this so we can assume that everything is zero so that's where we have performed uh this two and change this one to zero after this we are going to perform the first kind of operation to change this rightmost bit to zero so in total we have performed four operations to make this six to zero right so that's the answer now as i keep on saying in every video if the question is difficult try to solve a simpler version of the question so in this case one simpler version could be let's try to solve the case where there is only one bit set so let's say this is the question and we have to convert this to 0 by applying these two set of operations only so now how to do that first of all let's think of what all operations we can actually apply so this operation we can apply every time because this is just the setting the right like changing the right most bit but the second operation is quite interesting notice that we have to change this particular bit to zero right so we can do this only with second operation so first operation only allow you to change the rightmost bit but if you want to change any other bit you have to use second operation so here we have to change this bit to zero right our final goal so we have to use second kind of operation now once we are sure that we are using second kind of operation it indirectly means that we have to convert this to this somehow like somehow uh first this will be made and from here we will then convert this we will then apply the second kind of operation to convert this to this basically to make the first bit as zero so like now if this part is clear then what is left is we have to convert this 0 to 1 0 somehow so our question now becomes that we have to convert this 0 to 1 0 by applying the same kind of operations so this is equivalent to saying that we have to convert 1 0 to 0 okay so these two are the same thing now let's assume that total x number of steps are required to do so okay so we have performed x number of steps to convert this to this then we have performed one more step to convert this to this and then we have to perform again x number of steps to convert this to zero because as we have discussed like converting zero to one zero required x step so converting one zero to zero g zero will also require x step so that's why we are doing like but that's what we are doing here like converting this one zero to zero will require x steps so in total we require 2x plus one number of steps to convert this one zero to zero where x is the number of steps required to convert one zero to zero or zero two one zero now let's name this uh one zero thing so let's say uh if ith bit or let's name it j so if jth bit is set like but as you have discussed we have solved we are solving the case where there is only one bit set so let's assume that if jth bit is set the answer is denoted by f of j okay so f of j comes out to be 2 into x so what is x is nothing but f of j minus 1 right so basically x denotes the number of steps required to convert one zero to zero so if here if uh j is you can see j is zero one two three third position so and one zero here j is second position right so that if f of j denotes the number of uh steps required to convert an integer with jth bit set 2 0 then this is nothing but f of j minus 1 right so what we have found is f of j is nothing but 2 into f of j minus 1 plus 1 okay so if you don't understand this equation i will strongly encourage you to rewind the past five minutes of the video and rewatch it to understand this because this is the core of the solution now it like what does it mean it means like let's say like we know f of one right f of one is nothing but uh the number of steps required to convert the uh or basically we know f of zero like zero is the number of steps required to convert the zero with uh to convert the number with zero with bit set so basically if the number is one which is and we have to convert this to zero then this is f of zero so what is the number of steps required here so one is the last bit right so we can apply simply apply the first kind of operation and to convert and convert this to 0. so f of 0 is 1 now with this equation f of 1 would be 3 basically 1 into 2 plus 1 similarly f of 2 uh would be 7 3 into 2 plus 1 and so on and so forth so now hope this part is clear now if you remember we had solved this part as a easier version of the original question we haven't solved the original question yet so now let's look at how to solve the original question wherein we might have more than one bit set so till now we have solved uh we have solved one question wherein we are saying only the jth bit is if only the iii set the number of steps or j if only jth bit is set then the number of steps required is f of j minus 1 cross 2 plus 1 so we already know all the answers for converting 1 to 0 for converting 2 to 0 for converting 4 to 0 for converting it to 0 and so on and so forth basically all the numbers which have only one bit set we already know the answer for all of them with this equation okay now let's add one more bit to our uh question so let's say we want to convert this to zero okay now think about it so if you remember from one zero from basically one zero we have converted this to this and in between we saw that this number was coming right because what we have said is we convert this to this and then from here to there right so this one the converting this 1 0 to 0 has this part plus this part right and what we require actually is this part so what is this part is nothing but uh if we just want to find this part is nothing but the number of steps required to convert this to this like this total path and minus number of steps required to convert this to this right so let's formalize it so basically we are trying to find or this time let's not denote it by f that's denoted by uh f dash okay so we are finding 1 0 answer number of steps required to convert this to 0. so what we have said is this is nothing but the number of steps required to convert this to this minus number of steps required to convert this to 0 000 why basically we already seen that this path this entire this integer comes in between this conversion so this is like this entire conversion consists of the steps required to convert this from this and then from here to here so if we want the number of steps to convert from here to there we only require this part uh like this entire path minus this path so this path is nothing but to convert 0 to 1 0 right so that's what this path is so we have just found we have just come up with this solution okay now this like if you look at this it is now clear that what we are actually doing so now let's say let's talk about the three uh the case where there are three bit set so let's say this is the case that we are looking at or let me just change the color so let's say this is the case that we are looking at and you have to convert this to this so what we can say is the value of like the answer for this is nothing but uh the value of this f of 1 0 minus f of 0 1 0 okay that's the answer now how to find this is again the same like we have if we want to find this is again the same kind of equation like if we let's break this as well so what we'll say is the steps required here is this minus f of 0 1 0 okay so that's what the number of steps is so now you can see uh this is zero so now you can see what we are doing is the first bit for the first bit we are adding this to our answer then for the second bit we are subtracting like if we just uh like this entire thing will be in braces right so if we just open up the brace this will be minus and this will be plus so for the second thing for the second bit we are subtracting it then for the third bit we are again adding it similarly if there are other bits we will again subtract it and add it so what we are doing on every like we will start with the first bit we will add that to our answer then for the second bit we will subtract that to our answer then for the third bit we will again add that to our answer so what intuitively what is happening is we are saying that to go from here to there like from this particular thing to zero we will encounter like we first go we will first think of going from this uh this entire like this the set where only one bit is set and which is the largest bit now in the path of going from here to here we will encounter this particular thing so let's subtract that path from here and we will get the answer so now when we subtract the path from here this is again the same problem where we are trying to say what is the number of steps required to go from here to zero so you again for again do the same thing we will again know that to go from here to there we if we start from uh this particular step we will encounter this in between so let's just do this and then subtract the remaining part so that's what we are doing so the solution is very simple for the first bit add f of that to the answer for the second bit my subtract f of that to the answer for the third bit again add f of that bit to the answer so let's try to look at the code quickly the code is very simple we just find f initially f of 0 has discussed it's one and all the other f we have just found with this simple equation f of j minus 1 cross 2 plus 1 now uh we will check all the set bits so let's say this uh this j bit is set so for the first j like if it is the first bit we will add that if it is the second bit we will subtract that if the third bit will add that and so on so what we have done is initially we will add this f of j to the answer then as soon as we add something we will like uh revert this one to zero so if we like we are just drawing it because drawing one with zero will give us one uh enjoying one with one will give us one zero so that's where we are just drawing this so after this if value of plus is zero then it will become one and if value of one was a value of plus was one it will become zero so that's basically after uh whatever we have done in done with the jth bit for the next bit we will do the opposite so if we have added this before we will just subtract this afterwards so add first then subtract then again add then for subtract so on and so forth until we have exhausted all the set bits of this n and finally written the answer so hope you understand the solution i will link this problem and the interview experience in the description below in the next video we will be covering uh the next set of question which is this and this so stay tuned for the next video if you like the video give the video a thumbs up and do subscribe the channel as i told i am regularly publishing the video every day for different interview experiences so until then see you
Minimum One Bit Operations to Make Integers Zero
making-file-names-unique
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`. Return _the minimum number of operations to transform_ `n` _into_ `0`_._ **Example 1:** **Input:** n = 3 **Output:** 2 **Explanation:** The binary representation of 3 is "11 ". "11 " -> "01 " with the 2nd operation since the 0th bit is 1. "01 " -> "00 " with the 1st operation. **Example 2:** **Input:** n = 6 **Output:** 4 **Explanation:** The binary representation of 6 is "110 ". "110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. "010 " -> "011 " with the 1st operation. "011 " -> "001 " with the 2nd operation since the 0th bit is 1. "001 " -> "000 " with the 1st operation. **Constraints:** * `0 <= n <= 109`
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
Array,Hash Table,String
Medium
null
128
Rico's question is called longest consecutive sequence this has given an unsorted array of integers find the length of the longest consecutive element sequence so for this question a sequence could be something like 0 1 2 or 10 11 12 13 14 things like that then it says your algorithm should run an O of n complexity so for the example they give us there's the array 100 for 200 1 3 &amp; 2 there's the array 100 for 200 1 3 &amp; 2 there's the array 100 for 200 1 3 &amp; 2 and in that array is the sequence 1 2 3 &amp; 4 so how many numbers are in the &amp; 4 so how many numbers are in the &amp; 4 so how many numbers are in the sequence 1 2 3 &amp; 4 that would be four sequence 1 2 3 &amp; 4 that would be four sequence 1 2 3 &amp; 4 that would be four numbers so the length is four and as a side note a sequence is also considered a streak so I'll be going back and forth between sequence and streak during my explanation all right I've purposely slightly modified the example in the question so we can see how to deal with duplicates let's think about what our end goal is at the end of this we have to determine what the longest streak is so we're going to look at each number and determine the length of the streak that it's involved in so a length from 1 to n so in the first case let's say the first number is 100 we're gonna somehow determine how long the streak it's included in is but let's say then we go to the next number is also 100 but we've already determined the streak that the number 100 was involved in because we've seen it before now let's think about by the time we get to this over here that's also the number 100 if we kept the duplicates in we will have checked three times the length of the street that the number 100 is in do we really need to do this multiple times no we really only need to check it once so really the first thing we should do is remove any duplicates and we'll do that using a set and that's because a set by definition doesn't contain any duplicates so we'll add everything to a set and then we'll loop over only the numbers in the set because we know at that point that every number in the set is unique so after we add to the set our dataset would look more like this okay so now that every number in our dataset is unique what happens now let's start again with the number 100 to increase the streak we need to look at whether the number 101 is in the set is it no it's not so the current streak for the number 100 is 1 and since we can't extend that streak we can also say at this point that the global streak is also 1 because we've only looked at one number so far and it has a streak of 1 let's move on to the next number we need to reset the current streak to 1 but it's already 1 so you can't really tell in this case can we extend the streak for the number of 4 well we do know because of the example provided in the question that the number 4 is involved in a streak it's involved in the streak 1 2 3 4 so we shouldn't just consider the number that's one more than the number we're on we also have to consider the number that's one less than it but how do we actually go about doing that do we do something like we arrive at the number and we check if the number that's one number below it is in the set and if it is then we try to continue that streak and then also see if the number that's one number above that numbers in the set and try to continue that streak that would be unnecessarily complicated ideally we would find the lowest number in a streak let's say 1 and then only start counting the numbers in the from there so it's to do something like that we really do only have to consider if the number that's one greater than the number on is in the set but checking if the number that's one less than the number we're on does actually play a really important role let's consider the number we're on which is the number four we get to the number four and we check to see if the number that's one greater than it is in the set it's not now let's skip ahead a couple steps so let's say we're at the number one we check to see if the number that's one greater than it is in the set and we tried to create a streak that way so as the number that's one greater than one in the set which is the number two yes it is so we would have the number two can we keep that streak alive is the number that's one greater than the number two in the set which is the number three yes it is the number that's one greater than the number three in the set which is the number four yes it is now is the number that's one greater than the number four which is the number five is that in the set no it's not so that streak is done but we know that eventually we'll get to the number three using the number three that streak we know will be three and four and then we'd get to the number two and we know that streak would be two three four notice how much duplication there is we've checked the number four one two three four times we've checked the number three times and we've checked the number two twice this is not very efficient so what we can do instead is anytime we arrive at a number we can check whether the number that's one less than it is in the set if it is we know that the number were we'll already naturally be included in another streak and since it will be captured in another streak we can skip over it now and let the other Street captain so with that rule in mind we're gonna move on to the next number at this point the global streak is still 1 and the current streak is still 1 so let's move over to the number 200 first we check to see if the number that's one less than 200 is in the set because if it is we know that it will already be captured in a different streak so we don't have to worry about it now is 199 in the set No so now we can consider if the number 200 starts a new streak so is the number 201 in the set no it's not so the current streak is still 1 and the global streak is also still 1 now we move on to the number 1 is the number that's one less than 1 meaning the number 0 and the data set no it's not so now we can check to see whether the number 1 starts a streak so is the number that's 1 greater than 1 in the set well yes it is it's the number 2 so we know that this streak is at least 2 is the number that's 1 greater than 2 in the set yes it is so we add 1 to the current streak is the number that's 1 greater than 3 in the set yes it is the number 4 is in the set so we add another one to the streak and is the number that's 1 greater than 4 in the set no the number 5 is not in the set so our current streak ends at 4 so now that the current streak is done we can check is the current streak greater than the global streak well yes it is so now the global streak has to get updated to match the current streak all right so we're moving on to the next number which means we have to reset the current streak back to 1 because now we're going to be at the number 3 so is the number that's one less than the number 3 in the set yes it is the number 2 is in the set so we can ignore the number 3 because we know that the number 3 is already going to be captured or has already been captured in a different streak so the global streak remains 4 and the current streak remains at 1 all right so finally we're at the number 2 is the number that's one less than the number 2 in the set yes it is so we know that the number 2 is already going to be captured or has already been captured in another streak so we can skip over the number 2 and now we're at the end of the set so we know that the final answer is that the longest streak is 4 all right let's get to the code what lead code has given us is a function called longest consecutive which accepts an argument named gnomes and nums is just an array of integers so remember the first thing we have to do is create a new set so we'll say let's set equal a new set so now we add every number to the set so for let num of gnomes set dot add no so every number is added to the set at this point that would look like this original data set will become this so it'll only have unique values all right so then we need to also keep track of the longest streak so we'll say let longest streak equal zero you can say over here longest equals zero all right so now we have to loop over every number in the set so that's four let numb offset and this point would be here at the number 100 so for every number we land on we have to first check whether the number that's one less than it is in the set because if it is we know that the number that we're on either has already been captured or will be captured in another streak and in that case we can just ignore it so we'll say if the set doesn't have the number that's one less than we're on then we can continue all right and the set does not have the number 99 so now we can create a temporary variable that says let current num equal the number we're on and let the current streak equal one so that it look like this current equals one all right so since the number that's one less than it is not in the set we can check to see whether or not the number we're on starts a new streak so we'll say while set has current num plus 1 so we check to see if the number that's one greater than it is in the set and if it is then we'll just see how many times that happens so we'll say current streak plus equals one and current num plus equals one so increment the count of the streak and increment the number by one until we no longer have a streak going all right then after we do that we just need to see which one is greater the current streak or the global streak so we'll say longest streak equals the maximum of either the longest streak or the current streak all right so now we go back to the diagram on the left the number 101 does not exist in the set so that streak is done so now we update the longest streak to equal the current streak because the longest streak so far only had the number 100 in it all right so now we move on to the next number which is the number four is the number that's one less than the number four in the set yes the number three is in the set so we know that the number four is going to be captured or has already been captured in a different streak so we can just move on to the next number is the number that's one less than the number 200 in the set no it's not so we can check to see if the number 200 starts a new streak is the number 201 the set no it's not so we just move on to the next number so remember that at this point the current streak is still 1 and the longest streak is still 1 also all right so we're at the number 1 is the number that's one less than the number one in the set no it's not so now we can see if the number one starts a new streak is the number that's 1 greater than 1 in the set yes it is that's the number 2 so our current streak is going to be updated to 2 so now we see how long this streak goes on is the number 3 in the set yes it is the number 4 in the set yes it is the number 5 in the set no it's not so our current streak ends at 4 so now that we're done with our current streak the longest streak now has to be updated to match the current streak since the current streak is greater than it so longest will be 4 we move on to the next number which means we reset the current streak to 1 we check if the number that's one less than the number 3 is in the set yes it is so we move on because we know that 3 is being captured somewhere else filing at the number 2 is the number that's one less than it in the set yes it is so we move on and now we're done so now we know that the only thing left to do is to return the longest streak all right let's run the code make sure it works yes it does let's submit all right so our solution was faster than about 98% of other JavaScript than about 98% of other JavaScript than about 98% of other JavaScript submissions and it takes up less space than 100% of them so as usual you can than 100% of them so as usual you can than 100% of them so as usual you can find the code and written explanation down below and also in the description our other algorithm resources similar to this see you next time
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ You must write an algorithm that runs in `O(n)` time. **Example 1:** **Input:** nums = \[100,4,200,1,3,2\] **Output:** 4 **Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4. **Example 2:** **Input:** nums = \[0,3,7,2,5,8,4,6,0,1\] **Output:** 9 **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Hash Table,Union Find
Medium
298,2278
31
hey guys welcome back to another video and today we're going to be solving the lead code question next permutation all right so in this question we need to implement next permutation which rearranges the number into lexicographically next greater permutation of numbers if such arrangement is not possible it must rearrange it as the least possible order so what that means is basically if you reach the last arrangement we go back all the way to the beginning okay so the replacement must be in place so it happens in constant memory and here are some examples inputs are on the left and the corresponding outputs are on the right all right so real quickly um in simple words what this question is asking is we're going to be given some sort of order of numbers right and we need to find out what is the next permutation going to be and if you don't know what a permutation is i'll be going over it real quickly okay so over here we have one two three and then we go to one three and two since that's the next uh permutation right uh then three two one since that's the ending we're gonna go all the way back to the beginning which is one two and three and then one five is going to end up being one five and one okay so before we start off with the question let's try to understand uh what a permutation is and then we'll look into different ways we can use to solve this question all right so i'm not going to spend too much time on this but let's just go through this real quickly so let's say we have some sort of uh box right and this box has three numbers one two and three and um think of these as items and we can place these items in three different locations so each of the location is represented by an underline so think of this as location one location two location three right and our job is to find all the possible combinations or permutations they both mean the same thing right permutations can just be do think of them as different combinations to represent something so we need to find all these possible combinations or permutations of where we can put these items and we're going to follow the lexicographical order and basically what that means is we're going to start off with the smallest number possible so let's start off with our first position over here and these are the numbers we currently have we have one two and three so we'll pretty simply put we can either have the number one two or three the first position can have any of these three numbers and which one are we going to end up choosing well we want the smallest numbers so we're going to choose the smallest value right so we're going to start off with choosing the number one so now that i put the number one we need to get rid of this from our list so just to kind of show that we got rid of it i'm going to underline it okay so i'm underlining 1 there great so now let's go on to our next step over here what are the numbers we have left we've already used up 1 so the numbers we have left are 2 and 3. so what are we going to put here well again we're going to put 2 because 2 is smaller and we want to have the smallest number and finally what are we going to be having what are we going to be left with well so we used up 2 i'm going to underline it and the only number we have left is the number 3. so the only option we have is three so think of this as being our first combination one two three is the first combination we have and what is the next permutation for this sequence of numbers going to be well let's look at it step by step do we have any other number that we can put in this place over here well the answer is no we don't have any other number that we could put there because the only other option we have was the number three so let's move back one more step let's go over here so over here do we have any other numbers and the answer is yes so over here we could have either put the number two or we could have put the number three and we chose to put the number two well because well it's smaller but we've already looked at all of the combinations we've exhausted all the possible combinations for two in this place right and the only combination was well three so what we're going to do now is we're going to replace this with the other combination so let's just get rid of this over here and we also get rid of the three okay and instead of the two we're gonna do the three so i'm circling three i'm gonna put three here so now we've used up one and we've also used up three so what is the number we have left well two so the only other option we can put here is two so this is going to be our next combination one three and two so this is where things change what is going to happen over here well over here we've exhausted all the possible combinations so we're done with that in this position we've also tried both the combination we've tried the combination of two and we've tried the combination of three so what we're going to do is we're going to go back to the very beginning and over here we have three combinations so as it is we're done with all of the possible combinations of the number one right so we're done with all of the combinations for the number one so now what we're going to do is we're going to try out the next possible value which is well it's two so let's just get rid of this real quick okay so instead of one since we've tried all of its combinations we're going to have 2. well what are we going to have over here and the other two numbers we have left are 1 and 3 and we're going to end up choosing 1 since 1 is smaller and then the only other option we have is 3. so 2 1 and 3. so these are how permutations work and if you look at this at least when i saw this the first thing that i thought of was to use recursion in order to try all of the possible combinations until we find our next answer but as you think uh this would actually take up a lot of time which is very much unnecessary but instead there's actually a pattern that we can look forward to so let me just go back one step real quick so over here we have one three and two well what is the number we ended up changing is the value one and this actually comes in permutation so the thing is once we reach a number or once we find some sort of descending pattern so when you're going from one to three we're increasing what we're in ascending order right but when you go from three to two we're descending right two is less than three so what that means is that you've exhausted all of the possible combinations there are because when you're at the biggest number that means you've tried out all the combinations because look over here we first write out two and then we tried out three so once we reach 3 it means that we've already tried out the number 2 and now we're at the last combination so once you find any sort of descending pattern that means that's going to be the end of that combination so in this case we found a descending pattern over here so starting from three all the way to two there's a descending pattern so what is going to be changed well the numbers that's going to be changed is whatever is right before the descending pattern and that's the value one and this is what we actually ended up changing so after all this we actually ended up making this two and then this became one and this became three so this is the pattern that we're going to be following okay so let's say that we're given this number over here as our input and what we need to do is we need to find out the next possible permutation for it right and how could we do this well let's follow the same step we need to first look for some sort of descending pattern and we need to change the number right before the descending pattern starts so because of that i'm going to start off with putting a pointer at the last but one element and why am i doing the last but one element well the reason for that is because we actually want to find the position of the element before the descending order changes which is why i'm choosing this element okay and what are we going to compare this to we're going to compare it to its uh pre or its next element so in this case we're converting four to three so our pointers currently has four and we're going to compare it with three if four is less than three or in other words if the previous element is less than the next element then in that case that means we're in an ascending pattern but in this case this is not the case four is greater than three that means that we have a descending pattern and we're going to keep doing this until we reach a point where we find the end of this pattern so we're going to move our pointer to 9 and 9 is greater than 4 so that means we're still in a descending pattern now let's move it again so now we're at 10 is still greater than 9 so we're still not done with our descending pattern and now we're moving it again and now we have 2 and 2 is less than 10. so 2 is going to be kind of our turning point so after 2 is when the descending pattern starts and that makes sense we're going from 10 to 9 to 4 to 3 which is the downhill descending pattern and 2 is kind of our turning point so we know that 2 is the number that is going to change and what number is it going to change with so i'm kind of just going to divide this over here and what is the number that it's going to change with well the answer over here is we're going to take the next possible number to 2 and how do we know what the next possible number to two is well that's actually pretty simple to find out we're going to look for whatever possible number we have which is right after two so what comes right after two in this case well it's the number three and just to just for the sake of this example i'm going to add one more element over here which is going to be zero we need to find out what is going to be the number that replaces two and to do that we're going to start off from the ending so first we have the number zero so is the number going to be 0 well no because 2 is greater than 0 and that means that technically we've already looked at 0 so we need to look at the next possible number then we have the number 3 and 3 is greater than 2. so this is going to be the number that is going to take the place of two so what we're going to end up doing is we're going to replace these two so 2 is going to go in the place of 3 and 3 is going to go in the place of 2. so real quickly let's just do that okay so we're gonna add three over here and we're gonna put the two over here so now we've replaced their positions well but this is still not our answer yet so now what we're gonna do is since we change the value from two to three we change everything to the right as well a quick example is like when we saw one two and three and from one when we changed it to two we changed the next two positions as well the same way we're going to change everything to the right well how are we actually going to change it and the answer to that is pretty simple we need to sort this in ascending order because well we want the smallest to largest that's all we're doing right and when you sort it you're going to get 0 and this is going to become 2 this is going to become 4 this is going to become 9 it's going to be 10. and over here you can notice one thing sorting it is the same as reversing it right so this is nothing else but descending order so all we could do is we can just reverse it 10 9 4 2 0 sorted is the same as when you reverse 1094 to 0. so instead of sorting it we can just reverse it which actually takes place faster and that's what we're going to do and once you reverse it this is what you're going to get and you're going to end up replacing that the original values with these new values on top and this is going to be our answer so 0 1 3 0 2 4 9 10 is our next iteration so i think once you understand this it's the code part is actually the simple part yeah so anyways let's get right into the code okay so what i'm going to do is i'm going to start off by initializing a variable which holds the length of our numbers and the purpose that i'm doing that is because we're going to be calling the length quite a few times so we might as well call it once and just use the variable instead okay so what i'm going to start off by doing is we're going to check a base gate so if our length is less than or equal to 2 right so if our the numbers is either a length of 1 0 or 2 then in that case we can just directly return the reverse of numbers so we can just do num start reverse and we can return that value and the reason for that is when you only have two elements or even one in that case you can just reverse it and give it back because you only have two possibilities the first one is as it is given in the input and the second one as well is just going to be the reverse so that's going to take care of our base case and now what we're going to do is i'm going to assign a pointer and this is going to be the same pointer that we were talking about in our example and the pointer is going to start off at the last but 1 element so what is that's going to be length minus 2. that's the last but one element so now what i'm going to do is i'm going to try to so now we're going to move our pointer until we find the ending of some sort of descending right so how are we going to do that so first we need to check if we reach the zeroth element right so while pointer is less greater than or equal to zero so that checks for that and the second thing we need to check is whether the current element we are on is greater than or equal to the next element so what we're going to do is we're going to do nums pointer so that's going to be the current element we're on and we're going to check if that is greater than or equal to nums pointer and we want to check the next number right so nums pointer plus one sorry i cannot type okay there we go pointer plus one knobs pointer all right so now that we go inside of this while loop each time we go inside of it we're gonna decrease the value of pointer and there you have it right but there might be a point where our pointer reaches all the way to the zeroth index and at that point the pointer is going to have a value of negative one and what does that mean so let's say so we have the numbers three two and one right and in this case our pointer is going to end up having a value of negative one because we're going to start off at the first index then we're going to go to 3 and then we're going to decrease it one more time and we're going to start at leave end off with a value of negative one and when that happens that means that this is the last iteration in this case as well 3 2 1 is the last iteration and since it started we had a downward descent and what that means is that we've exhausted all of the possible combinations and now we're going to go back all the way to the very first combination and the very first combination is going to be the lowest in value and since we have the highest well the lowest is just going to be the reverse of this so in this case if nums sorry yeah if our pointer is equal to negative one and in that case we're going to return nums dot reverse since we're just going to reverse it get it in ascending order and that's what we're going to return so now over here what we want to do is we want to try to look for the number so now our pointer is at some number and we want to look at the number that comes after it and to do that we need to iterate from the ending to the until the pointer so to do that we can just go inside of a for loop so for x in range and where is it going to start from it's going to start from the last number so to do that we can just do length minus 1 that gets us the index of the last number and we're going to go all the way up to the pointer so all the way up to but not including the pointer and how are we going to iterate through this we're going to decrease each time so negative 1. okay so inside of this for loop we're going to keep iterating through it until we reach a condition and this condition is when if nums pointer so whatever our number at the pointer is less than whatever our value at this x index is and what this means is so we've currently found a number which is greater than our pointer and this is going to be whatever is the next number for our iteration so in this case uh we're going to re do that replacement right and to replace it we're going to replace num pointer and what are we going to so what are we replacing num pointer with well we're replacing that with the x value and similarly we also need to return replace the x value with the value of num's pointer so nums x is going to be equal to nums pointer nums and if you still don't what this is doing in simple words is that we found whatever is at the pointer and we found its next element and now we're just taking those two and we're replacing them right we're just switching their position that's all that's doing and after we do this we're done so we can go out of our for loop and we're going to break out of this so now we're out of our for loop and we do one last thing which is we need to take everything after our pointer and we do change that and reverse it so as it is everything after our pointer is in descending order so now we need to change it in ascending order and how can we do that well all we're going to do is we're going to first iterate through that so nums pointer plus one right we don't want to include the actual pointer but we want to include everything after that so everything first where the descending starts from and all the way to the end so the semicolon represents all the way to the end and what are we going to do to this well we're going to reverse it so we talked about this earlier all we're doing is we're reversing it and reversing it is the same as sorting it since it's already in descending order okay so real quickly how are we gonna so we're gonna do reversed and what are we gonna call the reverse function on well we're gonna call them the exact same thing which is numbs pointer uh plus one all the way to the ending and that should be it for our solution all right so now let's try submitting our solution okay and as you can see we got 83 faster than most people and uh i don't know how this actually works sometimes it says 96 sometimes 83 okay anyway so our solution was accepted and thanks a lot for watching guys do let me know if you have any questions i'll try my best to help you and don't forget to like and subscribe if this video helped you thank you
Next Permutation
next-permutation
A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order. * For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`. The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order). * For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`. * Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`. * While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement. Given an array of integers `nums`, _find the next permutation of_ `nums`. The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** nums = \[3,2,1\] **Output:** \[1,2,3\] **Example 3:** **Input:** nums = \[1,1,5\] **Output:** \[1,5,1\] **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 100`
null
Array,Two Pointers
Medium
46,47,60,267,1978
981
Question No. 981 &amp; D Question In this Question No. 981 &amp; D Question In this Question No. 981 &amp; D Question In this time based key value, what do you remember from the value of the store? If you code in Python, then you must be remembering the dictionary from the key value. Okay, if you do it in Aisi Plus, then from the key value. What will be the basis? How does Hashmat reduce? There is only one value and its corresponding values ​​are stored. values ​​are stored. values ​​are stored. Now the value can be a unique value or a wait or a similar value or it can also be a list. Okay. What type of value is there on us, we can also store the class of the club, we can store anything right, it depends on the object, basically we can store the object, so the same thing is here, right, so this is understood, its question time. It has been proved that right can store single value for that and what to do for the same, then it must be storing multiple values ​​also, storing multiple values ​​also, storing multiple values ​​also, then it is the same thing, okay brother, I have understood the thing, after that it is written that multiple values ​​for D come from Different multiple values ​​for D come from Different multiple values ​​for D come from Different This line is important Different Times Stumps Now here let's discuss a little about what are the different time stands Okay so the way it is for example man take any course of yours is ok There is a video course you have different time in it But if you want to make a note, then what will be the difference, what will happen if you take a man on time, three units are being added on time, okay, by doing this, you have your value, okay then, okay nine, let's see, if you look at me, what do you do when you make me laugh? We tell in it, brother, is it of integer type or is it of string type, for us string is right, string type is key and value, what is value, integer string, something like this, but here I don't know what is there in the whole list, one, his correspondent has made a list and do right. What is inside the list? The first value is the string. After that we are waiting for it. See, from time to time we have our wait. So what can you do in Java. What you can do is this. We can do that with one foot class. Okay, which has two methods. There are gate values ​​and one is by getting the key, it is okay, values ​​and one is by getting the key, it is okay, values ​​and one is by getting the key, it is okay, so I take it that if my value is done or my time stamp is done, then what will be the value, anything of yours is fine, the value will be done, by doing this we can do something. Or you can create a custom class yourself, it's okay for you, whatever you want is up to you, right, something like this is happening here, now look a little below it, what is written, we have to create a constructor, it's okay from time to time, the hashtag that was created. We will refine the same, then we have to create a set function, okay, which will set it. Now the point comes that what kind of input do we have, man, take it as we have added outside right bar day, we have added outside with that. The time we were in will always be in increasing order, what will happen, what will not happen, so if you are getting an interview then this is a very good question to ask, you can ask in your interview sir, I am getting the input in increasing order. Or if we get random then what will be in it? If we get random then you can make it a tree map. To shortcut it, why do we have to write short b? For the get function, we will also discuss that, so let's reduce it by one. Let's quickly go into the question and see its constunt. What is written in the constunt, we will be getting all the content from D in time only, so we do not have to take the tension of sorting at all. Okay, here one thing is sorted, brother, we do not have to take tension of sorting, if there is no tension of sorting. So what has to be done in the gate, which is the gate, it will return itself, it will return, it will retain the value which is the time stem, which is the previous time, look, it is a simple thing, D question is three, now if we call the gate, what do we do in the gate? And given by time, so what will it do, if it is sorted inside it, then sorted bomb, can it be done? Either if you do linear search, then the end will open, if you do binary, then what will be the complexity? Okay, Sin. If we do binary search in the city, then what will happen by doing binary search? I found a van, I returned it had a value of ₹ 100, it was found a van, I returned it had a value of ₹ 100, it was found a van, I returned it had a value of ₹ 100, it was fine outside, it was returned, now there is no question here, so what does it mean, for example, if I used the get function. What is the value inside then what to do in case if you did not get me then I want you written d just un mean un just lower value just lower times time is ok for example if you did not get me then I want you written d just un meaning which is less than that Yes, I will retain that, what is there in this, there is a van here, instead of you, I get 4, okay, what does it do for four, there is no pay for four here, but it is just a small catch from four, so I part for three, you return here, okay If so, this thing is written in this line, okay, I have got it and if no value is found in it, then what swing empty string do we have to retain in that case? Now which case is this? No value is found in it, Yadu's. It doesn't exist. It's okay. Instead of saying, I said food is not there, brother, what will you retain in our key, will you make a return? Or did you say that brother, it starts from my time, which is by the way, it starts from you, it is a four. If there is a five, then I have given a van, you are closest to the van, but you are not small, so I cannot return anything, in this also we will retain an empty string, so all these are a few inches, so let's reduce one, let's quickly move on to our code. On the other hand, we will code there and this is some of its importance. See, it is a construct. You have seen that set and gate have given some values. How to set is verified right and these are all gate functions. So, if the first one is doing it outside. After doing the gate van, it is returned outside, then it is not there, does the van exist inside it, then if it is returned outside in it, then what is just smaller than five, then it is okay, there is a method to it, after doing the gate floor, then just list it. Or we return equal value, okay, that is also an option, but okay, in Hashmat, operation of Van More is done in people, so there can be some issue, friend, in this also we do binary search, people in it will definitely happen. But no problem, it's fine, it's our inbuilt class, it does it, if you want, you can make it custom, you must have given in the discussion how to make it custom and I can do it directly for him. I had also told in the video that I can simply map dot is my daughter, sorry, I am just explaining myself. 45 Absent, if it does not exist, then add us now, it is passing through it, brother, what to add on it, first of all, list. Have to start right so for this I give arraylist of feet okay feet so what will I do look feet is the key value and two values ​​ both the values ​​of both are the pick of the gate which is values ​​of both are the pick of the gate which is values ​​of both are the pick of the gate which is string Store like that, if found then ok what will be there in it, what will be the first value right here, what to do here ok, it has been added, the list will be created, we have to give according to that and [ give according to that and [ give according to that and Han give the previous less equal one, so if inside our sorted, we I am looking for the time that I can do binary search inside it. Okay, so we will do binary search. You can do it by creating a function and we have to modify it a little bit. When you code the binary search, you will understand how we are modifying it. That is correct right, after that when am I getting a result, which key of the content is right if it exists right now what do we have to do after this I have you checked like now we have to apply some searching algorithm so that we get that time So what can I do inside this, I will return us a list, so first of all, let's take the list, okay, so list of players, map.get, map.get, what did I get here, if I got my list, then binary search, okay. Ok left and one right then left will start from zero and whatever is in right will start from our list which is set or right index is ok give less equal to right and after this let me check what happens Mirchi Upon You can advise what can you do, you can right left plus right - left is the plus right - left is the data type, its maximum is 100 days and my right is at 100 and my left is at 50. When I sum it and divide it, then first sum will be on the right and what will be the sum of 100 + 50 150. It has never gone above 100, so this method will also help you in the interview to find the middle, after that I have to check F gate. Made dot value becomes value then taking integer value when answer is found one is less and one is greater what is getting in the get we stored in the result what to do after that maybe possible Right this whole equal you just lower pinhocho somewhere before that so what you want you do this is what you want you increase a left you from zero you mid + 1 ok and zero you mid + 1 ok and zero you mid + 1 ok and what to do in this there is nothing to do in this brother what else It is big, it is big, so it cannot be my answer, so I will simply equalize my rights, now what do I have to do, whatever I get the latest result, you went here, what do we have to do after this, return result Very good. Like I got the answer here or else I got the equal, I have to stop after doing adrevise and it will run till the entire meaning and the entire operation is completed, then the final will give its own result, then it can be optimized here and something else. If you have an option, then tell me by commenting. I think you will understand. Have we taken the risk of creating a value based list, value is our list, why we had discussed that inside it we had to store two things, one value at a time, so for that I changed the class. That done, you can create a custom class if you want. If you want, you know how to create a custom class. What do we do in the map set? If we do not find our class, we have added it here. After that, what do we add? Par values ​​time write gate has its own values ​​time write gate has its own values ​​time write gate has its own cool, in this we have first written the basic result which can be the minimum which is an empty string, we have written that, after that we check whether it exits, if it exists then reduce it. adervise direct retain empty string, we had discussed that it is being returned in two cases, either our time stamp is smaller than the given one does not exist or our key does not exist, right then this will be returned, after that what if If it exists, then you want to do it, first of all we fetched the list and then applied binary search in it. Okay whoever our very dancer can be, okay in this case give equal to all of them, we stored them in the result now. We kept updating, if we got a valid answer, then we updated it. Well, not this, if we got another answer, then we read it and finally we have returned the result here. This one. The runtime of the part can be improved a bit, but the overall complexity is going to be different, so there is no problem about it, no, we have it is fine, so people will do it, but this one is the gate function in the particular Has Map which we have created for people to do. If the one is going to be ok then I think the dates are good, submit it and see, it will be done now, I had tried it is ok, gas, I hope you like the video, so please like, comment and subscribe, do it, and if there is any doubt, do it with me, thank you. So much
Time Based Key-Value Store
delete-columns-to-make-sorted
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp. Implement the `TimeMap` class: * `TimeMap()` Initializes the object of the data structure. * `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`. * `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`. **Example 1:** **Input** \[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\] \[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\] **Output** \[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\] **Explanation** TimeMap timeMap = new TimeMap(); timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1. timeMap.get( "foo ", 1); // return "bar " timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ". timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4. timeMap.get( "foo ", 4); // return "bar2 " timeMap.get( "foo ", 5); // return "bar2 " **Constraints:** * `1 <= key.length, value.length <= 100` * `key` and `value` consist of lowercase English letters and digits. * `1 <= timestamp <= 107` * All the timestamps `timestamp` of `set` are strictly increasing. * At most `2 * 105` calls will be made to `set` and `get`.
null
Array,String
Easy
null
1,750
hello developers let's start developing today we're going to take on The Daily pration for on lit code for the 5th of March so it's task 1750 we need to we have a string and we need to keep deleting the same parts of it until we are left within unmanageable kernel so let's start the minut it's a relatively simple setup so we are given a string and we should return a number let's see if our thingy works so it's 1750 we're going to start it and see if our test cases are running come on they should be yep they are running and basically even a sto clock is wrong is correct twice a day so for the second task we are supposed to get zero we are getting a zero we can easily change this to minus one but let's skip that part and let's see what we can actually do here so first thing is we're going to need to have a left and a right uh pointer so to say and first thing performance wise that occurs to me is that string are kind of expensive to create and do so instead of um managing it the creating new strings all the time we will just keep an index of the string where we are on the left or on the right so we're going to say that our left index initially is on the first thing the right will be on the second thing so we have two cases where we can return so yeah while left is less than the right I will delete this because I don't really need that will be my job to write so one way that we're going to finish is if this left becomes equal to right if left becomes equal to right then we just need to return zero or do we I think we will have a special case here so let's add another because if we had a not that good guess but if we just have this then the result shouldn't be zero it should be one and it should be the same if we have not this but something like a b c CA and then we have CBA the result should be one because this a should not be removed but let's see what happens so we have on it on the left we have it on the right and then so if the left and the right are different then it's easy break the cycle and then we return yeah something like that because if the left is on one and the right is on zero then we have a string of length two so we are counting both of them so that's why we need to have that plus one otherwise so if they're different no we say they are the same so let's see if we can move on the left so I will say while yeah something like this while the left is equal to the one after it move it and do the same thing with the right one so yeah this will do something now we will need to do something else as well so in this case what we're going to have a and a they are similar so now we need to move the left here and this so by the time we get here now it means that we are on this a and on this a so what we are going to do is now going to move them once more so we say we are done with the A and move them once more so increase left and in decrease right let's see what does this code do yeah so we're going all the way until we there they not the same they're not in the same chain on letters and they say okay do that and we've gotten off somewhere so the other test cases passed only the test case when we were supposed to get to this failed why so we have C we have a we have B and then we get the string a hm let's isolate that so if we have AA then the result should be actually zero we might need to repeat this code here or we might U actually give a hack or something like this that says well if you run past each other then the result is zero yep so in this case the left took this two a the right took this two a from the other side they removed them both and our right became zero our left become became two and now their difference is minus one let's see what happens if I say well if it's less than zero then it's most likely zero this is a bit of a heck we're not we did not fix our algorithm basically we just ignored any values that we didn't like so it's not always a good approach to take but in this case for these test cases it says it's okay and now comes the moment of Tru how do we submit on lit code we take this code we put it into the code tab of lit code actually we can write it right here and yeah we have the same test cases always run your code first never submit directly because you might have some forgotten console logs some uh other things that uh will basically break your code here or maybe you're using a another uh function or whatnot but anyway until you see that all your test cases that you're working with are accepted it makes no sense to submit you will just get a wrong answer or some kind of other weird error so let's see if this works and yes this time we got lucky our algorithm basically even with the hecky uh Behavior actually worked our run times are not so bad you can see that sometimes if I run it differently it I might get a different uh result because to be honest there's not too much difference between 54.4 not too much difference between 54.4 not too much difference between 54.4 megabytes and 54.5 megabytes but note that we are not 54.5 megabytes but note that we are not 54.5 megabytes but note that we are not uh allocating any strings we are not doing anything we're just managing some integers so something like that so that's all for today we have our problem of the day solved and this is marked as a medium task but to be honest I find it quite easy it is a bit of a issue until you understand what's actually needed but once you do it is kind of on the easy side so keep developing don't forget to Mouse those button except the bed button don't touch that and see you later
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
746
hi all welcome back to another video from cracking the fang interviews today i'm going to be talking about lead code 746 which is minimum cost of climbing stats this is a popular problem from amazon google microsoft and netflix interviews if you haven't already please check out the climbing stairs problem which is not the minimum cost problem so this problem is an extension to that problem i'll leave a link to the problem in the description below it builds on this problem builds on the fundamentals we have established in that problem uh yep let's look at the problem uh again here i have a snippet from lead code so what we've been given is a staircase where each step has a cost associated with it so if i were to draw this for you the way it would look like is step one has a cost of zero you can index this step 0 in programming step 1 or step 2 but let me just refer to indexes to keep it simple step 1 has a cost of 15 and step 2 has a cost of 20. two and what they're asking you to do is uh you can the constrain here is you start here or you start here and you're allowed to take uh one step or two steps at once so if you start at 10 you can directly go to 20 or you can go to 15 and then 20 essentially this is the concern of the problem what they want you to do is pick where to start first of all so start if you want to start at index 0 or 1 make that decision and once you decide that you essentially you know find the minimum cost uh sequence so if you remember in the previous problems i've mentioned whenever you hear the words like number of subsets or number of ways or minimum cost or anything with minimum or longest any superlative words right like minimum maximum longest smallest you need to be exhausted meaning to find what is the minimum you need to figure out everything else right if that makes sense logically so the only method you can use for that is usually recursion and recursion is uh is essentially exponential time algorithm so it could be u of 2 power n as previous problems that we have solved and the way you convert this into more like a polynomial runtime meaning optimize is dynamic programming and again if you haven't checked out my previous videos i highly encourage you to start with the recursion and dynamic programs programming series which this video is a part of the i have videos where i cover fundamentals with the fibonacci program then climbing stairs and then this minimum cost climbing states uh so this is a dynamic programming question and to quickly summarize the reason i um i think it is dynamic programming is i've been asked a global answer minimum right um so i have to figure out all permutations of climbing to say which one is will give me the minimum awesome so let's dive into the code um so as i've always suggested whenever you're writing code with a dynamic programming solution you always need a base case and this base case is comes from the recursion right so think about it this way you have this sequence of steps given to you and i'm going to quickly draw this again the cost for 10 15 and 20 and what you're doing is you're essentially uh this can also be represented in an array so for step one two the cost is 10 15 and 20. what you're asked to do is essentially uh find out what is the cost to get to two the final step and the constraints given were you can take one step or you can take two steps at once if that makes sense so let's try to you know since we said this is recursion and we are now directly writing optimized code for dynamic programming we need to solve some problems so what i mean is sub problem could be just you're given three steps just think of one step at a time right so for this step what is the minimum cost you are required to start either here at the zeroth step or the first step so the minimum cost here is going to be 10 because you know you don't have any other alternative if you're just looking at this sub problem but now if you are at index 15 uh what is the minimum cost of getting to index 15 so the minimum cost could be directly jumping starting from 15 itself or starting from 10 and then going to uh to 15 right so that's how i've represented this here if the cost is 10 you can either have the cost for the step one as 15 plus 10 or 15 meaning you start at 15. so you calculate that using this formulation in this case the minimum cost it will make sense to directly start from the index 15 rather than come from ah jump from 10 because it's going to add its own cost all right so we solved this um you know the sub problem till here now by solving the first sub problem for 10 then the second sub problem for 15. now let's solve the third sub problem or the problem of uh getting to 20 again for getting to 20 right the minimum uh cost uh is could be um starting at 10 and then taking two steps you can take two steps jumping to 20 or starting at 15 and then taking one step so the answer would look something like minimum 20 plus minimum of uh cost i minus 1 and cos i minus 2 if that makes sense where cos i minus 2 is the previous minus 1 and minus 2 are the previous two solutions um and that's exactly what i've written here if you see as i go through uh the array uh and what i'm essentially doing is uh in this case the what would make sense is starting at 10 and taking uh two steps and directly going to 20. so the cost will be 30 versus it could have been 35 if you had started uh picked up from 15. so essentially uh what we are doing is we are looping we set up the base cases first the base cases and then we start from index 2 so this is 0 1 2 we start from index 2 because the base cases for the previous two steps are set up and we iterate to n plus one which means uh we trade till n step n and if we are at the last index we essentially just pick uh you know uh the cost of the previous two meaning if you're jumping here which is the last index n so the question is actually asking us to go beyond these three steps um here so there's one extra step you need to make here if you just look at the example in the previous question but i've also seen a variant where they want you to get to the top step so both of these questions are valid um that's why you have an extra n plus one in the solution here itself and what you're doing is uh you know um essentially um just picking your current cost and evaluating based on previous sub problems from where should i pick or jump uh to get minimum cost so you are looking for minimum you solved all possible sub problems you are combining that to get your final result so the runtime for this is going to be time complexity is going to be o of n again here we directly wrote the optimized dynamic programming solution you could also have return recursive solution and then optimized it as we discussed with dynamic programming but the concept and the expression remains the same yeah i hope you liked the video thank you for watching cracking the fang interviews please like subscribe and share the video with your friends and leave a comment down below if you need any help understanding this
Min Cost Climbing Stairs
prefix-and-suffix-search
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index `0`, or the step with index `1`. Return _the minimum cost to reach the top of the floor_. **Example 1:** **Input:** cost = \[10,15,20\] **Output:** 15 **Explanation:** You will start at index 1. - Pay 15 and climb two steps to reach the top. The total cost is 15. **Example 2:** **Input:** cost = \[1,100,1,1,1,100,1,1,100,1\] **Output:** 6 **Explanation:** You will start at index 0. - Pay 1 and climb two steps to reach index 2. - Pay 1 and climb two steps to reach index 4. - Pay 1 and climb two steps to reach index 6. - Pay 1 and climb one step to reach index 7. - Pay 1 and climb two steps to reach index 9. - Pay 1 and climb one step to reach the top. The total cost is 6. **Constraints:** * `2 <= cost.length <= 1000` * `0 <= cost[i] <= 999`
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
String,Design,Trie
Hard
211
11
hey guys it's off by one here and today we're going to be solving container with most water in this problem we're given an integer array height of length n and in this problem each index represents a line that when drawn has the endpoints I zero and I of height I so for example let's say we start at this point here which is called that index 0 and the coordinates would be zero and 0 1 because that would be the height of this one right here and then in this problem what they want us to do is find two lines that together form a container and that this container contains the most water and in the end they wanted to return the maximum amount of water that a container can store so for example here let's just take these two lines for example this one and this one then the max water that can be contained here is just here because we kind of have water that goes all the way up to here so basically What's Happening Here is that we're forming a container using the minimum of the two heights so if we know we're going to be calculating area let's just get our formula so the way to calculate the area of a rectangle is length times the height and our height is just going to be the minimum between Bar number one and Bar number two let's say we're doing the first and second index so let me just write that down here height is equal to the min of our bars and for length what we're going to do is calculate the distance between this point and this point so for this example here we're only doing one jump and that means that our length is going to be one and if we were calculating these that means we were doing two jumps here which would make our length two so our length is going to be the distance between our lines so now that we have that we can just write this into some pseudo code so our actual code would look something like this where the index of the second bar minus the index of the first bar times the minimum of the two heights is going to give us our area so let's say this is our first iteration this would be I and let's say we're checking the height of this one this would be J so now that we know how to calculate the area let's see if we can think of a solution The Brute Force approach would be to just take the first iteration and check each number in the array and keep track of the max that way and then once you're done going through the array once you do it again for the next number and then check for example e times six eight times two eight times five and then you do that for every single element in the array and update the max as we go but the problem with that is that it takes all of N squared time and this problem can actually be solved in linear time instead of going straight into the oven solution let's explore this all of N squared solution and see if we can get to it from here because I feel like that would be more useful than just telling you the answer so to start our first Loop is iterating from zero to the end so or I would start here and then for our J you're going to start at I plus 1 all the way to the end and for each time we're iterating 3j we want to find the area so our J will start here now I'm going to write the result of the for Loop out and then we can analyze them to see how we can optimize our search and here are the results so for I equals 0 we see that we start here at 1 and then our J will be initialized to here pointing to 30. so according to our area formula we do J minus I times the Min of both Heights so for here we do J which is one minus zero times the Min of one and thirty and the Min of 1 and 30 is just one so we can see that we didn't even use this 30 for any of these calculations because we're bounded by our lower bound so what does this tell us well we can see here that our Max is 3 and that comes from looking at these edges so maybe a smarter approach would be to start by calculating the area for the first and last index and then working our way inwards so let's try that here I've written a new example that contains different numbers and like we said we're going to start by calculating the area for these two and the way that would be is index 0 and this is index three so our formula would be three minus zero times the Min of three and four which is equal to three times three which would be nine so now which pointer do we want to move like I said earlier we are bounded by our lowest number so we want to move this three pointer to be pointing to ten so we can just do that here and then this would be the first index and then now we calculate our area again so index three minus index one times the min of 10 and 4 well now our remain is going to be 4 and this is going to be 2. so we have 2 times 4 which would be 8. and then now we want to move the pointers again well this is now our bigger number so we want to move our lower bound which will be this so now this pointer would be moved to here and then now we can calculate this area so we would have 2 minus one times the Min of 10 and 13. which is equal to 10. so now we can see that this gives us the correct Max height and that this is the algorithm we can work with so let's just summarize what we learned here so we know we want to initialize the pointer over here for our left point and a pointer over here for our right point and the way we want to move the pointers is by seeing which of these points to the lowest number so in this scenario left would be moved to the right by one because it is lower than four and then after calculating the area between 10 and 4 then we want to move our right pointer to the left because we see that 10 is greater than four and at this point we would stop iterating because we don't want our left and right pointer to be put into the same spot so basically we want to Loop while left is left and right and if left is pointing to a value that is smaller than the rate then we want to move our left pointer to the right because we know that having a lower value does not help us get a higher area and we want to move our right pointer to the left if right is pointing to a lower value so our code would look something like this here and what we managed to do now is reduce these two four Loops to just a while loop using our two pointer method and the way the while loop is going to work is you find the area first and then we check which of these has the lower number and we update the pointer accordingly but what happens in a scenario where nums of left and nums are right are equal so here I've written an example that'll probably help us solve this case so I've already done the area for this first iteration where left is at the leftmost point and right is at the rightmost point and we can see that the area is three but now let's try and move our right pointer to the left one because we're trying to figure out what happens so if our right pointer is there now we want to calculate our area and we see that this is equal to two now so we don't really get a bigger number so let's just try and move them the other way so a right pointer is not pointing to one again and now we're going to shift our left pointer to see if that makes any difference and the area for this would be one and we can see that it doesn't really make a difference which pointer we move because in the end both pointers are going to end up pointing to 4 and 6 and if we calculate the area for that we see that we get a new Max area of four so what this lets us conclude is that it doesn't matter which pointer we move so for our example we can just cross out this condition and just move the right pointer to the left one now that we've finished our pseudo code let's get into the real code to start we just wanted to initialize our left pointer to be equal to zero and our right pointer to be equal to the length of nums minus one or I guess it's height in this problem and additionally we want to initialize a global Max and this is how we're going to keep track of our maximum area and we're just going to start with zero since we're promised in a problem that we're not going to have any negative numbers and then from here we just do what we did in this middle code so while left is left and right we want to calculate the current area and from here we're going to use our formula so right minus left times the Min of height of left and height of right and this is going to give us the current area for whatever we're pointing to and then from here we just want to check if current area is greater than our Global Max we just want to update our Global Max to be equal to our current area and once that's done all we want to do is check if height at the left is less than height at the right this means that our height at the left is smaller and we want to shift that because there's no use in using that anymore so left is going to increment by one otherwise we just want to decrement our right pointer and that's pretty much it after that we just want to return our Global Max and that should work so as you can see this solution is pretty efficient and now we'll step through the code manually so to start we just want to initialize our pointers and our variable to keep track of the max which I've done here and named it Max and our variables for left and right are initialized to zero and eight and I'm going to write them here just so we can see them a little clearer too so now we want to do wild left to left and right which it currently is we calculate the area using right minus left and the Min of whatever the height we're at so for this current one we have seven and we have one the Min between those two is just one and right minus left is eight so our current area is eight and we see that the current area is greater than our Global Max so we're going to update that as well and now we check is the height at left less than the height at rate yes because 1 is less than seven so now we can move our left pointer to the right one and now we start over our current area is now going to be eight minus one for right minus left and the mid height is going to be 7 because 8 is greater than 7 and so now our area is going to be 7 times 7 which is 49. so our current area is Now 49 and that's greater than our Global Max as well so we're going to update that and now we check is the height at left and height at right no so we want to decrement our right pointer by one now we go to the next iteration current area right minus left which is let me update this as well seven minus one and that will give us 6. and the minimum between eight and three is three so we would have six times three which is eighteen and that is not greater than our Global Max so we're not going to update it and now we check is the height at left last and height at right no because 8 is greater than three so now we decrement our right pointer by one and now we calculate our area again so right minus left would be six minus one which is five and we multiply that by the Min of the height of left and height of right which would be eight so it would be five times eight which will give us 40. and now we check is our current area greater than our Global Max no because our current area is 40. so now we just go to the next if statement so if height of left is less than a height or right which is not because they're equal and like we mentioned it doesn't matter how we decrement our pointer for this code we just decrement it the right by one so I'm going to do that so now our right pointer is here and now we do this code again current area is equal to right minus left which is four and we multiply that by the Min of eight and four which is four and that will give us 16. and that is not greater than our Max height so we're going to check if height of left is less than the height of right and it's not because 8 is greater than four now we just shift our right pointer to the left one and now we check the area again red minus left that will be three and the Min between eight and five is five and that will give us a current area of 15. and that is not greater than our Global Max so now we just check is height at left less than the height at right no because 8 is greater so we do decrement or right pointer again and now we have current areas equal to right minus left which is 2 times the Min between eight and two which is two so our current area is four which is not greater than our Global Max so now we just check where we move our pointer hide it left is not less than height of two so we just decrement the right pointer by one and now we do our last check current area is equal to right minus left which is one and the mean between eight and six to six and this will give us a current area of six which is not greater than our Global Max and now we just shift our right pointer to the left one again and says our pointers are now equal this while statement exits out and we return the global Max which is 49 and that is true because that is one of the examples we had this video helped you in any way don't forget to like And subscribe thanks for watching and I'll see you in the next video
Container With Most Water
container-with-most-water
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. **Example 1:** **Input:** height = \[1,8,6,2,5,4,8,3,7\] **Output:** 49 **Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49. **Example 2:** **Input:** height = \[1,1\] **Output:** 1 **Constraints:** * `n == height.length` * `2 <= n <= 105` * `0 <= height[i] <= 104`
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle. Area = length of shorter vertical line * distance between lines We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
Array,Two Pointers,Greedy
Medium
42
452
hello guys today's problem for lead code is minimum number of Arrow to burst a balloon so they will be given 2D array of Point uh X starting point from X start and ending point okay so there will be a balloon which starts from uh start from 0 till end okay so it always this should be lower and this should be higher we got this point from this denote a balloon whose horizontal diameter stretches between so between X star so whatever the number you start till end you don't need to uh know the exact y coordinate okay so no needs for y coordinate Arrow can be sought up directly vertical so directly vertical we can sort from different point of exercises a balloon with X array and x start and accent is busted by an arrow stood at x if x dot is less than or equal to X or less than or equal to x n day is no limit to the number of arrow that can be sought a short Arrow keeps traveling with the infinite bursting any volume in the part okay so we are given here so there is 10 16 2 8 1 6 1 7 2. so the auto took like the solution took six and he busted two eight and one six how we passed it to uh have you busted to it so it's middle of between two and six middle like in this equation they told if it is mid in between so it will get busted and here also it is an edge so it will get busted so here is equal so if that's the reason it will get burst so another point the shooter took is 11. why he took 11 so it is between 10 and 16 and is between 7 and 12. so 11 is an ideal uh idle point to suit and arrow so how we can solve this so first approach is to sort that how to sort the array so let's see we will sort the array by using Lambda function Dot thought so I'm telling you why I took sort we will sort the array points comma so how should I sort it uh I should sort it in Lambda function so 0.1 comma point two point one comma 0.2 Arrow function so here integer we have to compare if it is more integer Dot compare we understood a problem what I am doing here you have to approach it huh compare P of 1 of P of uh what if you have to compare we have to compare the first element of every element so you know we have to compare the last element what is the last element of this array so compare one and comma P comma 2 to compare 1. so what does this does here so here these are given error 10 16 2 8 1 6 and 7 2 in the 2D array the 10 question is two weight is there uh 160 167 7 12 step so what I did here spend right here what I did here I used array Source I used points P1 and P2 and I used this Lambda function here after compending here it sorted in the ascending order so wait but it started from like six is uh lower than eight n to where n16 without even considering this I use the Lambda function to compare only this element I compare only this element so it got sorted into the this range it got sorted this so the results are this much so 1 6 2 8 7 2 and 10 16. so I how I'm approaching this solution I will take uh I will take 6 has a main point it will suit the arrow it will suit this Arrow it will also suit this Arrow but it can't suit this Arrow so I have to use another arrow here I will take this Arrow as 12. I will take this Arrow exercise to it so this also will get sorted and this also will get sorted so what I am doing here I will take a first element is 6 so I have to take the how much error should be sorted how much error should be suit so first Arrow should always shoot and I have to take the X Point has I have to take X point x uh first element point zero comma the maximum element is 1. the ending point we have to take call this then I have to iterate to every solution for I equal to 1 I less than points I plus so I took lemon here you have to attract to everyone so I have to see if the what is advertise advertising here if this element is less than uh is more than this element then it will be sorted you have to check if my x-axis my x-axis my x-axis is less than point of I comma 0. so if that is the case I will have to shoot another arrow so Arrow foreign after that the x-axis will be will have after that the x-axis will be will have after that the x-axis will be will have a new value which I took here the new value is 12. so x axis will be the x axis will be point the maximum element it will take so I comma 1. and after finishing this Loop we have to return how much arrows is has been sorted background so let's see yes it's running in all the test case so let's submit and see it got submitted so if you have any doubt regarding the solution please message me please comment me and I will reply to it and if you like this video please do like it and do subscribe to my channel it will be great help thank you
Minimum Number of Arrows to Burst Balloons
minimum-number-of-arrows-to-burst-balloons
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons. Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. **Example 1:** **Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\]. - Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\]. **Example 2:** **Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\] **Output:** 4 **Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. **Example 3:** **Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\]. - Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\]. **Constraints:** * `1 <= points.length <= 105` * `points[i].length == 2` * `-231 <= xstart < xend <= 231 - 1`
null
Array,Greedy,Sorting
Medium
253,435
1,339
hello everyone welcome to day 19th of august lootco challenge and today's question is maximum product or splitted binary tree in this question we are given a binary tree and we need to find out the maximum products that can be generated by splitting this tree at one possible end and how will you calculate uh the product it would be equal to the sum of the left subtree that you are splitting into the sum of the right subtree that you're splitting without much to do let's look at the presentation that i have created for this and i'll be explaining the question as well as algorithm there itself maximum possible product or spitted binary tree lead code 1339 let's take the same example that was specified in the question we have a binary tree one two three four five six and let's hypothetically assume that we are making a split at this particular edge so what is the product if you make a split at this particular edge what one half of the tree is this one and other half of the tree is this one so what is the total sum of this part of the tree it is six what is the total sum of this part of the tree one plus three is four plus two is six 6 plus 4 is 10 plus 5 is 15. so the product becomes 15 into 6 which is 90. so one possibility is 90. let me just erase it i think this 90 will go away let's store it somewhere we have 90. let's hypothetically assume we are making a split at this particular edge what is the sum of uh this subtree some of this up tree is nine sum of this part of the tree is 1 plus 2 is 3 plus 4 is 7 plus 5 is 12 so this is 12 and 12 into 9 is 1 0 8. so the other possibility is one zero eight so this is higher than the previous possibility so we got a better product as one zero eight let's try more possibilities and let's try and break the tree at this particular edge what is the sum of its uh right tree it is one plus three plus six is ten what is the sum of its left part of the tree it is four plus two plus five it's 11 so 11 into 10 is 110 which is greater than 108. so the max product becomes 108 so far and let's try for the other possibilities as well let me just erase it let's break the tree at this particular edge what is the sum of this part of the tree 1 plus 2 is 3 plus 5 is 8 plus 6 is 14 plus 3 is 17 so this is 17 this is 4 17 into 4 is 56 it's pretty small let's ignore it let's break the tree at this particular edge what is the sum of this part of the tree so 4 plus 2 is 6 plus 1 is 7 plus 3 is 10 plus 6 is 16 into 5 gives us 80 which is again lower than 110 so the maximum possible product that can be generated in this complete tree is 110 and where are you splitting the tree you're splitting the tree at this particular edge i hope you got the context now let's talk about how can we actually build the algorithm so let me just clear this up and please note that the maximum possible product is 110 let's get started the first thing that i'm going to do is to count the total sum that is there in this complete tree what is the total sum 6 plus 3 9 plus 1 10 plus 2 12 plus 5 is of 17 plus 4 is 21 so the total sum of this 3 is 21 and what i'm gonna do next i will try to calculate the sum of each subtree so let's try and calculate the sum of each subtree this is one subtree so the sum of the subtree is four sum of this subtree ending starting at two is four plus uh four plus two plus five which is 11 so the sum is 11. what is the sum of this subtree is this subtree the sum of this subtree is 5 the sum of this 3 is 21 we have already calculated it the sum of this subtree including both these elements is 9 and the sum of this subtree is 6. we will be using this information to find out the maximum possible product and how will we do that let's assume we are making a break at this particular edge so one part of the tree will hold the sum as 4 the other part of the tree will hold the sum 21 minus 4 which is 17 so you got one possibility of the product let's assume we are breaking the tree at this particular edge so the sum of this subtree is 11 what is the remaining sum of the other part of the tree is 21 minus 11 which is 10 so you got the other part of the tree sum as 10 this product is higher than the previously calculated product 17 into 4 is lower than 10 into 11 therefore the max product value gets updated to 110 and we will do it across all the possibilities so let's assume we are making the cut at this particular edge the sum of one half of the tree is five the other half of the tree is 21 minus five which is 16 so the possibility for this splitting product is 16 into 580 80 is lower than 10 110 we will not update the max product value let's do it for the other possibilities as well let's assume we are making a break at this particular edge what is the sum of its left part of the three one half of the tree is nine the other would be twenty one minus nine which is twelve so twelve into nine is one zero eight which is lower than one zero therefore we'll ignore it the other possibility is you are breaking the tree at this particular edge one half of the tree has the sum as six the other half of the tree will have a sum twenty one minus six which is 15 into 6 is 90 you will ignore this value because it is lower than 1 0. as we i traded through all the possibilities the maximum product that was generated in the system is 1 0 and that becomes our answer now let's talk about the coding section how will we actually code it up we'll exactly follow the same steps as i have told here the first thing that i have done is to define two variables the total sum variable that exists in the binary tree the other variable is a max product variable that will help me calculate my max possible product in this tree as a first step i have invoked my dfs method on the root so as to calculate the total sum that exists in the tree this is pretty straightforward method it is basically iterating the tree in a post order traversal fashion first the children and then the root and calculating the total sum you can use any other traversal for updating the total sum variable and once i have calculated the total sum i calculate the possible sum of all subtrees that are there in the binary tree and let's talk about this method so it is also iterating in a post order fashion it first calculates the total sum of the subtree starting with the its left root left child then its right side and then calculate the total uh subtree sum for the current root which is equal to left plus right plus root dot value and once i have that this value with me the total sum of the tree starting at the root i will calculate the possible product that would be equal to subtree sum into total sum minus subtree sum so this gives me one possibility of the product and as i iterate through all possibilities of subtrees my this variable will automatically will be chosen to the maximum possible value and in the end i simply return this subtree sum so as to process the other iterations let me just submit this accepted once i have i am done with this iteration uh my maxim product variable will be updated and i have the performed modulus of dendrites number nine plus seven as specified in the question i hope you got the context and enjoy today's session if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded see you tomorrow with another fresh question till then good bye
Maximum Product of Splitted Binary Tree
team-scores-in-football-tournament
Given the `root` of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return _the maximum product of the sums of the two subtrees_. Since the answer may be too large, return it **modulo** `109 + 7`. **Note** that you need to maximize the answer before taking the mod and not after taking it. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** 110 **Explanation:** Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11\*10) **Example 2:** **Input:** root = \[1,null,2,3,4,null,null,5,6\] **Output:** 90 **Explanation:** Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15\*6) **Constraints:** * The number of nodes in the tree is in the range `[2, 5 * 104]`. * `1 <= Node.val <= 104`
null
Database
Medium
null
1,423
Problem Maximum Points Pen Cards From Defense According to Looter Film Institute Actually course relatives and dedicated number of points deposit sediments in the interior that in one step in the phone call from the beginning and from the end through this trick 18 to it Dr 10,000 points of cards You have it Dr 10,000 points of cards You have it Dr 10,000 points of cards You have taken in the interior records and educated Amazing School Question A I Want Global Economic Total Key Elements From This Ansh Mein Doctors And Waste Maximize System Navodaya Entrance Test How Twenty-20 Elements With This Element How Twenty-20 Elements With This Element How Twenty-20 Elements With This Element Song Start From Delhi And Sorry For Example Jai Hind In this case btake in all its elements from end submission is wealth that in this moment imported 221 limit we start one element from end and two elements of mother end and two elements of observation made before in this case you have to take off but from this Minister Yashwant ji's leader take this one and Dasvand Someshwar and classic example from these parties you can 302 elements from the last and one element from the beginning and through the limits of mother and submission date 212 so let's make this month year boy death Sampur The givens of the proposal is in this case that Bigg Boss to force vacancy for elements sweater the possible way in which they can take place for elements i.e. place for elements i.e. place for elements i.e. 16 same from the start and distance from Delhi and fungus start with 0 elements after beneficial for all elements members. Configuration Sugar Talking About Next Clarification Kutbi Technique One Element We Start And Elements From And Don't Elements From Starting To Elements From And Learn From Start From And Stand For 200 Form And A B C And D Possibilities In Which They Can Take Hadith's Elements And Right To Maximize the Summation of the Most Wanted Whisper Choice Configuration Vaikuntha Solution So this is the worst condition and definition of all the elements from the given in Physics 2ND Year for elements of and definition of this and comes after 10 minutes Source of Information 20 Translation for Admissions Let's take to variables this is the star solution design and mission so this was talking in this month and again starting elements of elements the worst element and three and elements of that are in the northern had come to the number two in this vansh video channels pe 34 Is Taking Off And Timings Of Finding This Mission Switch Off Finding Submission Of K Elements With Big Boss Time Inside And K Is Given Equal To And So Is Bhigo Friendship That Yesterday Morning Avengers Contributions And Its Contribution Stigma Of End Times The Total Time Complexity Vikas soak fans on world notification screen system in the question also app lock messages sapoch hai so ifin vibration that they something baby notice for all are yaar morning have to give its formation and submission hua hai that somvanshi calculate the solution 2014 commission orders for Elements and Starts Admission into Submission of Government Service 2013 Something is System Value Element Solution This is the Shyam 120 Ltd Plus Form of CON for B.Ed Admission Plus Form of CON for B.Ed Admission Plus Form of CON for B.Ed Admission Dates of Fact This Element Member Vikram Procedure and similar vaikunth add that of one to boy and subtraction from j&amp;k of six sudhir and j&amp;k of six sudhir and j&amp;k of six sudhir and love you baby final submission in bhigo after fun to 100MB left and contributions which are being discussed like this and contributions known for its contribution to calculate the sum meeting bhigo Fun Time For The Solution Will Welcome Bigger Of N Which Improve Near Consent Mere Dil Se Poochhe That Tomorrow Also Sliding Window Ask Records Were Sliding Window Late To Bigg Boss Window Base Line Window Ball Simrely Wednesday Element And Use's Settings Beach Sexual Is This And Windmills Flight From He Ya Dal 100 Million For This A Process Called Sliding Window Producer And Researcher In 100 Programming Problems Next To Nothing Sacred Waters Penance To Have In This Green Color Edge Sliding Window Will Consider To White Vinegar Sliding Window Self Nutritious Elements Number Elements In This regards 9 and gives winners 4 a number of elements between sliding doors and 5 - number of elements between sliding doors and 5 - number of elements between sliding doors and 5 - producer 500 1000 considered as deadline to nine instead of maximizing sliding window which will ask 100 maximizing between sliding doors and will right to minimize while sliding window is 8 and window described All winners in so 202 floor benefits flight from 125 danil flight from 216 in liquid and gas that however handling this is amazing submission sleep from this mission such an initial a very good condition will affect of zero from the same blood of five this episode configuration a [ __ ] she Deserve This Commission Which Comes a [ __ ] she Deserve This Commission Which Comes a [ __ ] she Deserve This Commission Which Comes Next Issue Collect Contribution Will Attract K Of Vansh Will Add 820 Suggestions Soen It Interesting You But Instead Of Having No One Has Seen In The White Vinegar Sliding Window And Sweet Minimize Divided Into A Improve Maximize Dhanwant Ki Nau You can simply be disappointed with solution by clearing big fan of the most difficult friend know country code for a short term which will be so in this year brings implementing the approach in which were taking brightness setting Bluetooth switch on * Minimize sum of divide and edit * Minimize sum of divide and edit * Minimize sum of divide and edit step will Arrive To Maximize And Answer Will Be The Total Submission Vestige Mission - Will Be The Total Submission Vestige Mission - Will Be The Total Submission Vestige Mission - Dasham Se Dasham Is The Samudra Sliding Window Which White In Color Member Clan Is Video Ko Phanda 152 Submissions And Submission And Starts Admission And Will Keep Adding To The Stars Solution One Then Time And from and submission a wicked sub setting on shadow time and will change the start and in witch state I finally Vitava aapse ha thank you digit pollution ki thi
Maximum Points You Can Obtain from Cards
maximum-number-of-occurrences-of-a-substring
There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards. Your score is the sum of the points of the cards you have taken. Given the integer array `cardPoints` and the integer `k`, return the _maximum score_ you can obtain. **Example 1:** **Input:** cardPoints = \[1,2,3,4,5,6,1\], k = 3 **Output:** 12 **Explanation:** After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12. **Example 2:** **Input:** cardPoints = \[2,2,2\], k = 2 **Output:** 4 **Explanation:** Regardless of which two cards you take, your score will always be 4. **Example 3:** **Input:** cardPoints = \[9,7,7,9,7,7,9\], k = 7 **Output:** 55 **Explanation:** You have to take all the cards. Your score is the sum of points of all cards. **Constraints:** * `1 <= cardPoints.length <= 105` * `1 <= cardPoints[i] <= 104` * `1 <= k <= cardPoints.length` 1\. The number of unique characters in the substring must not exceed k. 2. The substring must not contain more than one instance of the same character. 3. The length of the substring must not exceed the length of the original string.
Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce.
Hash Table,String,Sliding Window
Medium
null
427
hey everybody this is Larry this is day 27 of the legal daily challenge hit the like button hit the Subscribe button drama and Discord let me know what you think about this part I mean apparently I haven't done before so yay let's do something fun uh or something like that uh yeah I hope everyone's have a great weekend having a great weekend uh when do we swing forward I feel like the time something I don't know but in any case hope everyone's having a good week coming up uh and let's get started on today's fun please buy Miss 427 construct quiet trees tree given an N by n Matrix of zeros and ones we want to represent the grid with a quad tree we turn the root of a quad tree representing the grid does this notice that you can assign the right of a node to true or false when it's Leaf is first and both are accepting the answer okay I mean I kind of know what a quad tree is so that's why I thought I've done this before but maybe not on lead code or is that a dad or maybe there's like a constructed quad 3-2 that I've done constructed quad 3-2 that I've done constructed quad 3-2 that I've done instead of this one but yeah let's take a look so if you have a grid of n by n and basically the idea behind a quad tree and we'll see if it's like uh divided by divisible by okay yeah divisible by two or something like this because basically the idea behind a cloud tree is kind of almost the same idea as uh a regular binary tree that goes only left and right um the way that I want to think about it's kind of like divide and conquer right actually they actually have an image here but the idea here is that okay you know we're a binary tree you know or if you think about like um yeah binary representing say a One D away then you know um yeah something like that uh you know you could do it by half and then half the way would be you know and then you kind of compress it that way in a way the goal of this is to um well a couple of things maybe wait let's see okay yeah so uh because there are a couple of ways you can think about it depending on the implementation or the specification but the idea is that you know you can kind of think about it as a rudimentary uh compression scheme right where you know all the zeros are together then we can just eliminate the leaves right and then kind of divide and conquer um and that's the part of conquering so let's kind of let's get started I don't think there's anything that um you know that tricky about it or whether I think that the implementation will kind of make the divide and conquer clear so yeah let's get to it um also if you're watching now uh I'm I am going to do a bonus uh legal problem afterwards today I've guess I felt uh I feel a little bit better I don't know so yeah so we'll definitely do that so definitely hit the Subscribe button wait for that video and let me know what you think uh because I feel like I don't know if you don't like it then I don't do it anymore right that's the end of the day right or even if people like it but they don't watch it then you know what's the point right uh okay so yeah um so basically we can maybe do something like oh constructions over here construct helper maybe I don't know uh right and basically now you know if the way that I always think about these things like I kind of already did is by doing the 1D version and it just kind of like spring go in an extra Dimension right so here you know maybe if we think about you know a one day away where we have the left bang and the right barrel and then when you do right in Congo you just take the middle and then you know separate out that way um in here we'll do the same thing except for now we have um up so upper left and the bottom right kind of um defines a square and from that square we can kind of construct it you can also do it in other ways with kind of um you know uh with like some sort of numbering system that's a base four probably um you can probably construct it that way similar to how you would con think about a binary tree um you know you have zero two X plus one zero two X plus two or something like this right on each of the notes you can kind of think about it that way and maybe do it you know that way with quad tree as well uh not I'm not gonna do that but I'm giving you some ideas in case you wanted to so yeah so let's just say we have left uh Left Right top bottom right oops uh yeah and you can even maybe think of this like 8x um maybe this is a little bit cleaner you know a x a y or something like this uh and then bxby or something same thing really right so then now here if left is equal to top then we assume that you know right is equal to oh wait that doesn't make sense hang on sorry whoops oh if left is equal to right then top is going to bottom because we always divided by two anyway right on each of those Dimensions so that means that this has one element and then basically now we want to return a new node um of oh huh that's weird what's top left oh that's the note okay sorry I got a little confused I was like oh what is this but yeah basically the value will be grid of um left top as we said this is uh they're all going to be equal to each other right left as you go to the right top as you go to bottom so this is just one node right uh we have a sleeve so this is going to be a leaf and then I think yeah otherwise what do we do right well now we just try to figure out the mid in both ways um I'm a little bit have to be a little bit careful about this one uh just because I'm really bad about it but plus I think this is good but it may be off by one something like that right so mid X as you go to this uh mid y as you go to uh right um and the way that I always like to think about it um is I use a use real numbers because I to handle it off by ones right meaning that um and these are always going to be powers of two ish or off so let's say 0 to 15 right um then the num the half is going to be seven so you want that zero seven and then eight to fifteen um both of which will contain eight elements right so that means that we won this myth to be part of the left so then you have a construct helper um left to top mid X um but why um and now this is just about well going through the cases right so yeah uh so let's just say so this is going to be the top left yeah maybe back up right um top right is going to be the same thing except for now um it's gonna be mid X plus one and then this is going to go to the right all right yeah okay yeah I just want to make sure and the way that I didn't make this explicit but now I will right this is uh all coordinates uh inclusive you don't have to do it inclusively that's just the way that I do it um because I don't know you can definitely uh play around the other way but yeah bottom left is going to be mid y plus one oh wait whoops from the left Midwife plus one um it's going to go to the right no it's gonna go to Mid X and then it's going to go to the this as well oh you know this is right bottom yeah okay and then bottom right is to go to the same thing kind of but mid X plus one um it y plus one uh right and then bottom right okay so then now if top left that so now all the values are together then we merge them right so that's basically what we want to do here then we just return a new super note of you know this and then now it's gonna be a sleeve uh or if it's gonna be true because now it's a new Leaf um oh wait I have to check something do I have to check that the oil leaves yeah I guess we should check that they're all leaves okay yeah okay then now we just you know the value is going to be all the same as we know this is now a new leaf and then yeah we don't have any leaves otherwise we just return a node of um I guess the values don't matter right that's what they say to true or false friendly oh wait is why you true or false is that what it is maybe I'm no it's just one and zero this is way weird that's they sometimes use true and force and then sometimes they use zero and ones in the thing so I'm getting a little confused but either way it's the same thing right so here it doesn't really matter but by uh notation of us we just keep the uh thing and then you just top left top right bottom left bottom right and that should be good so now we do construct helper uh from zero to n minus one zero uh oh wait no zero to n minus one and I think this should be good hopefully if not then you know we have to debug uh isn't that the syntax I think I needed a thingy here for okay no that's awkward it's also like very poor um like this visualization kind of means nothing to me to be honest so that's why it's a little bit weird um and I guess this no what is it printing like tell me what is it printing is it the value and then it's leave or something no it's uh it's leaf and then the node value I guess because this is telling me it's wrong but then I have no idea how to look at this right um is it not merging correctly uh I think maybe I have to add a programs maybe some of this was a little bit weird I don't know the order of operation but okay at least that's fixed do I do the country did I did a math one all right so this claims that this but really I think all these don't really um maybe it does it's hard to tell what is actually wrong uh okay let's see if I haven't off by one maybe this is the bottom and it goes to the bottom left goes to Mid X but and then Midwife expose the bottom this oh what no this looks okay I'm gonna say um unless I'm doing it off by one somewhere but hmm what is going on seems like I have a much a node that I shouldn't have maybe I decided how I didn't really leave it okay let's look at oh yeah this is one example so we should able to see okay oh I see so zero one the value doesn't matter because it's not uh yeah so this one doesn't matter it's a little bit deceptive one zero is this one and this is really hard to tell how to debug uh because I don't know what's wrong with the or like it's definitely not should be a zero did I do the older one top left top right yeah bottom left bottom right seems like I'm doing it right yeah I mean unless I mixed them I think that was the only thing maybe but hmm why would I think bottom left oh I see I think I mixed up my x's and y's my coordinates are flipped Maybe um is that true am I lying to you I mean that's true I think that's probably why all right let's see how do I fix that because I use my left SX that's why okay so then we just have to do this I think maybe hmm foreign I mean now we have to change other things too I think um all right I think I just confused my X and y's because I think my left and right should be wise right so let's actually just go through that way so okay let's fix this and then now this means that this is y and this is X um okay I think that's y okay and I think that's one ah I did confuse myself okay well that did not fix it unfortunately but at least we can maybe look up one is leave no then hmm x to the bottom y one to the bottom right okay I think that I have I think this at least makes more sense now um hmm it's kind of embarrassing I don't think this is that hard but I'm just struggling with just kind of making sense of what this data is really to be honest but because this only has three because okay so this is the root that's things and then I don't know what these none what these all these nodes mean because it doesn't match four of these right this is just such a terrible visualization scheme but uh is there any way to show this no okay fine uh I think maybe it's time I give up on the thing and then just um and then maybe like you know okay so what I did was that I was trying to create a very simple case where I didn't have that symmetry so it would have to give me something well um so I guess hmm I mean this one doesn't matter what they say so it goes top left top right is that yeah they should be still be top hmm top left is one top right huh so mid why it is screaming so it goes to zero one uh yeah so one inclusive so this is going to did I mess something up here oh I see because that's the thing that I didn't fix because I got the wrong thing okay silly Larry I fixed most of the other things but yeah it was just mixing up X and y's that's the point and then I fixed in all these code except for I forgot about the base case that's why um because I was looking at the one uh cell um right well uh what is the complexity here right um I mean it's gonna be linear time you look at each cell once um there are it's not true yeah I mean maybe you can say there's a lock for a log base for um component no it gets each one gets merged not based four times I guess yeah so I guess this is uh kind of no because at verse it is going to be linear because each cell okay yeah so this is linear time linear space um the way that I think about it even though it is a little bit complex it's the same as uh as um as the binary tree right so even though there are like n levels like base 2N levels um but actually the summation is something like um you know and on the lowest thing plus n over two plus n over four plus n over a plus dot right amount of work um and of course that sums to 2N and that is going to be all of n right um and in this case it's going to be n plus n over four plus n over 16 which is not even going to be 2N I don't think so I don't actually don't know what it converges to but it'll be uh is that true hmm yeah I don't know but I imagine it's you know whatever right uh my math today is really bad I mean those of you Google Notes convergent series note that this converges but it's going to converge less than two times N I think but yeah still all of n in either case is my point so yeah linear time linear space and that's all I have with this one let me know what you think hope you didn't make that silly mistake like I did but yeah stay good stay healthy take your mental health I'll see you later take care bye
Construct Quad Tree
construct-quad-tree
Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent `grid` with a Quad-Tree. Return _the root of the Quad-Tree representing_ `grid`. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: * `val`: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the `val` to True or False when `isLeaf` is False, and both are accepted in the answer. * `isLeaf`: True if the node is a leaf node on the tree or False if the node has four children. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } We can construct a Quad-Tree from a two-dimensional area using the following steps: 1. If the current grid has the same value (i.e all `1's` or all `0's`) set `isLeaf` True and set `val` to the value of the grid and set the four children to Null and stop. 2. If the current grid has different values, set `isLeaf` to False and set `val` to any value and divide the current grid into four sub-grids as shown in the photo. 3. Recurse for each of the children with the proper sub-grid. If you want to know more about the Quad-Tree, you can refer to the [wiki](https://en.wikipedia.org/wiki/Quadtree). **Quad-Tree format:** You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where `null` signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list `[isLeaf, val]`. If the value of `isLeaf` or `val` is True we represent it as **1** in the list `[isLeaf, val]` and if the value of `isLeaf` or `val` is False we represent it as **0**. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** \[\[0,1\],\[1,0\],\[1,1\],\[1,1\],\[1,0\]\] **Explanation:** The explanation of this example is shown below: Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree. **Example 2:** **Input:** grid = \[\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\]\] **Output:** \[\[0,1\],\[1,1\],\[0,1\],\[1,1\],\[1,0\],null,null,null,null,\[1,0\],\[1,0\],\[1,1\],\[1,1\]\] **Explanation:** All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: **Constraints:** * `n == grid.length == grid[i].length` * `n == 2x` where `0 <= x <= 6`
null
null
Medium
null
15
in this video we'll go over lead code question number 15 threesome now if you haven't already seen my video on twosome I highly recommend you go watch that first because threesome is very similar to twosome but it's a bit harder the link is in the description so please go ahead and watch that first okay now here's the problem statement for threesome given an integer array nums we need to return all the triplets num's I nums J and nums K such that I J and K are all different from each other and the three values we pick must sum up to zero the solution set also must not contain any duplicate triplets so a Brute Force solution would run an O of n Cube time so we're definitely not going to do that however you can see that this is similar to twosome but there are a few key differences first we need to sum up three values to zero instead of two values to a custom Target second we are returning the array values themselves not the indices and third and most importantly there can now be multiple Solutions and we need to return all of them not just one as a result of this new rule we also cannot return any duplicate Solutions and so this is going to be the main differentiator from Tucson if there was only one unique solution like in twosome we could use an outer loop to fix the number at index I and then just use the same exact solution as twosome with a hash table the problem with this method is that our solution for twosome doesn't account for multiple Solutions so we would end up returning duplicates for example if this is the array then our answer would include the array negative 1 and 2 since those three numbers add up to zero and also negative one zero and one notice that the order in which the numbers are in doesn't matter now there's another way to get zero here which is to use these three numbers but we shouldn't include it in our answer because it's a duplicate of this answer so how will we find all solutions without including duplicates well I'm going to be showing you a method that first sorts the array then uses a two-pointer approach to solve this in O two-pointer approach to solve this in O two-pointer approach to solve this in O of n Square time now let's look at the code and solve this in Python let's say this is the numbers array that we are given the first thing we're going to do is sort nums and you'll see why this is important in a second next we'll create an array that will hold our final answer then let's start the outer loop that fixes the first number using index I notice that we only Loop until the length of nums minus two or in this case 7 minus 2 which is 5 because we always need at least three numbers to sum up now I'm going to explain this line a little more later but for now I is equal to zero so this is false and we just move on here we finally start the two-pointer approach we're going to two-pointer approach we're going to two-pointer approach we're going to initialize the two pointers L for left and R for right and this is going to be our starting triplet the numbers at index i l and R we're now going to start the inner loop and keep going as long as the left pointer is less than the right pointer the first thing we're going to do is calculate the total by adding up the numbers at the three pointers so that's going to be negative 4 plus negative 2 plus 5 which is negative one now at this point three things can happen the total could be less than zero greater than zero or if it's not either of those then it must be equal to zero right now negative one is less than zero so you can see that what we're about to do is increment L but let's take a second and think about why we're doing this so because the array has been sorted we know that the left pointer is pointing to the smallest number in the array to the right of I and on the other side we know that the right pointer is pointing to the largest number in the array so if the total is less than zero then we need to make the sum larger if we move the right pointer down then that would only make the total smaller again because the array is sorted we're also keeping I fixed for now so the only thing we can do here is move the left pointer up to make the total larger so let's go ahead and increment l now we loop again and calculate the new Total which is negative four plus negative one plus five which is zero that means that we found the solution so we'll go into this else block and create an array called triplet that has our solution which is negative four negative one and five we're then going to append that triplet to our answer array and we've now successfully found our first solution then we're going to move the left and right pointers inwards but we're also going to check for a few extra things so first we make sure that L is still less than R and we also check if the number at L is equal to the number at index 1 of the triplet which is the number we just added to the answer that was at index l in this case negative one and so if it is equal to that number then we're going to increment l so in other words we want to keep incrementing L until it no longer points to negative one and it goes to a different number and the reason we do this is to avoid adding duplicate Solutions now we check again we can see that L still points to negative one so if we just calculated the total again we would end up appending the same solution So to avoid that we're going to increment L again now when we check we see that L points to zero so we can finally move on since we moved L to a different number we know that these three numbers are definitely not going to equal zero so we can also move R and we'll check for the same thing except we'll look at the number at index 2 of the triplet which is 5. right now R still points to five so let's decrement R now we're finally at a different number so we can finally calculate the new Total negative four plus zero plus three equals negative one which is less than zero so we'll move the left pointer up but now notice that the two pointers have met in the center that means we're done with the inner loop and we've checked all the numbers so we can now go back up to the outer loop increment I and do it all over again here I is greater than zero but the number at index I negative two is not equal to the number at index I minus 1 which is negative four so this is still false and we skip it then we'll set up our left and right pointers again and start checking all the numbers the total is negative two plus negative one plus five which is two this time the total is greater than zero so by the same logic as last time since we need to make the total smaller the only thing we can do is decrement the right pointer next the total is negative 2 plus negative one plus three which is zero so we found another solution let's create the triplet array again and append it to our answer then we're going to move the pointers inwards again L gets incremented and since it's still pointing to negative one we increment it again next we'll decrement R but now both pointers have met again so we're done with the inner loop again and we can increment I this condition is still false because negative one does not equal negative two but you'll see this become useful very soon so again we set up L and R and then calculate the total which is three this is too large so let's decrement r next the total is one which is still too large so we'll decrement R again now the total is negative two which is now too small so we'll increment L the two pointers have now met which means that there were no solutions to be found and we'll move on to the next I however now notice that this condition is true the number at index I is negative one and so is the number at index I minus 1. when this happens we're going to hit this continue keyword and what continue means is to skip the rest of this iteration and continue with the next one so we're going to skip everything below this and just increment I again so the reason we do this is because we don't want duplicate Solutions with index I at the same number it's the same idea as the left and right pointers we keep moving it forward until we hit a different number now I points to zero so this is false and we can proceed let's set up L and R and total is going to be 8 which is clearly too big so R gets decremented they meet in the middle so we're done with the inner loop but notice that was also the last iteration for the outer loop as well because remember if we moved up I to index 5 then we wouldn't have enough numbers to form a triplet so now we're also done with the outer loop which means the only thing left to do is to return the answer which contains our two solutions and we're done now I'm going to mention this as a bonus but if you really wanted to optimize then before starting each Loop you could check if the number at index I is greater than zero and if it is then just break out of the loop right away and return the answer the reason this works is because since the array is sorted we know that the number at index I is going to be the smallest out of the three numbers so if the number at index I is already greater than zero 0 then there's no way that any of the other numbers which are all larger are going to sum up to zero so in the case that you were given a very long array with lots of positive numbers this piece of code right here would allow you to exit early and save some time
3Sum
3sum
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets. **Example 1:** **Input:** nums = \[-1,0,1,2,-1,-4\] **Output:** \[\[-1,-1,2\],\[-1,0,1\]\] **Explanation:** nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0. nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0. nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0. The distinct triplets are \[-1,0,1\] and \[-1,-1,2\]. Notice that the order of the output and the order of the triplets does not matter. **Example 2:** **Input:** nums = \[0,1,1\] **Output:** \[\] **Explanation:** The only possible triplet does not sum up to 0. **Example 3:** **Input:** nums = \[0,0,0\] **Output:** \[\[0,0,0\]\] **Explanation:** The only possible triplet sums up to 0. **Constraints:** * `3 <= nums.length <= 3000` * `-105 <= nums[i] <= 105`
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery 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 for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Two Pointers,Sorting
Medium
1,16,18,259
818
and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 818 race car your car starts at position 0 and speed plus 1 on an infinite number line your car can go in negative positions your car drives automatically according to a sequence of instructions a for accelerate and r for reverse when you get an instruction a your car does the following its position is increased by the speed its current speed and the speed is multiplied by two if you get an instruction to reverse your car does the following if your speed is positive then your speed becomes minus one otherwise your speed becomes one and your position will stay the same given a target position target return the length of the shortest sequence of instructions to get there so let's look at an example and try to figure out how we might do this we're given a target 6 which is what we want to end up at and we see that our output should be five but how do we get that well we know that our speed in the beginning is going to be one right because it tells us it's positive one and our position is going to be zero right so let's kind of draw our number line so we are at zero and we want to get to six somehow so we know that we're going forward in a positive manner right so we are going straight so the first instruction for us to do to reach six is obviously we need to go forward so to do that we have to tell ourselves to accelerate so that means that we're gonna go forward so we're gonna issue an accelerate command and the accelerate command is going to basically you know our position is going to be equal to whatever our previous position was plus the speed so now we're going to end up at one and you know so our position now becomes one and speed is doubled so now speed is two so now we're at one well we still want to get to six so we need to accelerate so we're going to issue another accelerate command here and what we're gonna do is we are you know gonna end up where well what happens when you accelerate so the position is going to be equal to you know plus equals to the speed so we're going to end up at position three now because we add our speed which is two and we multiply our speed by two so our speed is four so we end up at three so three is still not six so what do we wanna do well we need to essentially keep accelerating so we're gonna issue another accelerate command and now our position is going to be equal to you know we're going to add our current position plus the speed so we end up at 7. so we're actually going to end up at 7 from here and our speed is now going to get multiplied so it's 8. so obviously we've gone too far now because we're at seven but we need to be at six so we can't keep going forward otherwise we're just gonna get further and further away from six so from here we need to issue a reverse command so we're gonna issue a reverse command and what happens when we issue a reverse command so our speed is positive so that means our speed now becomes minus one and our position stays the same so we're still at minus seven okay so that means that our speed is minus one so we wanna go to the left so what we need to do is we now need to uh issue an accelerate command because now we're reversed right our speed is minus -1 so that means that we'll be minus -1 so that means that we'll be minus -1 so that means that we'll be traveling backwards so we need to do that so remember that when we issue the acceleration command our speed gets multiplied by two so it's minus two so we're going minus two i guess miles or kilometers whatever in the opposite direction and our position is gets added to the speed so since it's the previous speed was minus one we actually end up at six which is our final answer so we can see that the sequence we had to do is a r a and that's five commands which is how we got the final answer of five so looking at it's pretty intuitive you know if you had to work it out you could probably figure this out drawing it out but this is a coding problem we need to actually put this into some sort of solution and figure it out so let's think about an intuitive way that we can solve this problem okay so we looked at an example but it wasn't really clear how we can translate that simple example into actual code so this problem is a hard problem and it's asked by google so you're probably immediately going to jump to we have to use dynamic programming and we're not going to do that i hate dynamic programming i don't do dynamic programming so we're going to solve it another way which is actually so much simpler and probably results in less lines of code and less you know wanting to jump off a bridge somewhere because dynamic programming is the worst thing on earth so let's think about this we have our start position let's kind of draw it here and we have some end position right and we'll say that's another dot and you know there's certain you know places so if this is zero right and this is six for our kind of target well let's say this is one this is two and we're kind of just drawing them in arbitrary places it doesn't really matter exactly where they are um you know these little dots but what you begin to realize is that you know getting from zero to one to two to three to four to five to six or maybe you go from one to three to five to six or whatever you can actually represent this as a graph right these are really just nodes that you can traverse between and what are we asked to find we're asked to find the shortest sequence of instructions from how to get from point a start to point e well if we can think about traversing from start to end as traversing a graph which it really is right because each one of the nodes that we can reach i guess from zero to infinity obviously we probably don't want to go to infinity we want to go to whatever our target is those are all nodes in our graph and we can reach them you know from one we can reverse to go back to zero from one we could somehow end up at three we could end up at four so really all of these nodes are connected so and we're asked to find the shortest sequence which should immediately scream to you that we want to use a breath first search so if we can initialize a breadth-first so if we can initialize a breadth-first so if we can initialize a breadth-first search and basically maintain our kind of cue structure to get us closer and closer to the end every time then we should be able to find the shortest path and if we just count the amount of steps it took to get to you know our end from the start we know that breadth first search will always give us the shortest path so we don't have to go down all the possible routes like we would with the depth first search or you know something with dynamic programming we can actually just do a bfs and we'll get there in the fastest possible time so obviously this diagram is horribly messy it's like spaghetti right now but let's go to the code editor and write this out because it's a whole lot simpler than you might think and i think it's only about maybe 12 lines of code so let's do that instead of trying to make sense of this jumble diagram which admittedly looks terrible so i'll see you in the code editor okay we're back in the code editor let's write the code so this is a breadth first search solution which means that we're going to need a queue and we're going to need to initialize that queue with our initial position so we're going to say q equals collections.deck equals collections.deck equals collections.deck and remember that we need to keep track of a few things those being our current number of moves which obviously we've made zero moves in the beginning our current position which is zero and our current speed which is one so we also want to use a visited set here to make sure that we don't accidentally visit combinations of position and speed that we've already been to because then we'll just end up recalculating things so let's set up a visited set to make sure that we can prune search paths that we've already been down so now we do our breath first search so we're going to say while q we're going to say the current moves we've made the position and our current speed is going to be q the pop left and now let's double check that we are not at our solution so we're going to say if position equals to our target that means that we're done we've reached our target and since it's a breath first search we know that we're going to reach it in the shortest possible sequence so we can just return our moves otherwise this means that we're not at our target and we need to continue going so let's check that we actually haven't been here before so we're going to say if position and speed in visited so if we've already been here and the way that we track it is if we've been at this position with the current speed uh obviously this combination if it's in visited that means that we've been there before we can just continue to the next iteration of our breadth first search otherwise this is a new position in speed combination for us so we need to explore it so we're going to say visited.add visited.add visited.add and we're going to add the position and speed cool now what we want to do is we need to decide what to do so we always basically want to try to go forward if we can so let us go forward and the way that we're going to do that obviously we're going to make a move forward so that would increase our moves our position remember when we go forward is position plus equals to speed so we're going to say plus the speed is our new position and we go speed times two right because the speed doubles when we uh accelerate so obviously we can't just keep accelerating forever because eventually we're gonna hit a point where we shouldn't have accelerated and we basically need to go back right we can overshoot our target so like in this example that we looked at earlier we got to seven but our target was six so at this point we need to reverse so what we only want to reverse in a few situations the first situation is that you know we've overshot our current position right since we're moving forward at every iteration of our kind of search here eventually we will overrun it's very unlikely that every single time we're just going to reach the target you know perfectly most likely we're going to overshoot because obviously the speed is doubling each time and that means that the position is increasing um you know exponentially so what we need to do is check how we overrun our position in which case we need to reverse or are we not quite at our position so for example if the target is 6 and we're at four but we're actually going backwards then obviously in that case we wanna reverse because we don't wanna just keep going in the opposite direction so those are our two cases where we actually wanna issue a reverse command so we're gonna say if the position plus the speed uh would actually take us over the target and our speed is positive obviously if the speed is negative it's okay that we've overshot our target because now we can just start going in the opposite direction so this is the case where we're at seven but we're still continuing forward so we'd end up at like you know eight nine ten eleven we actually wanna go the opposite direction so this is checking whether or not we actually overshot our target and that our speed is still positive which means that we'd be going even further away the second condition is that we're actually below our target so we're going to say position plus speed it's actually less than the target but the speed is actually negative so for example like on a number line if we were at four and our target was six but we were actually going you know to the left right that would take us further and further away from six we actually need to reverse so we can start going to the right and getting closer to that six so in those are the two cases where we actually need to issue that reverse command and let's calculate what our new speed is right so if the speed when we issue the reverse is positive then the speed becomes -1 otherwise the speed becomes -1 otherwise the speed becomes -1 otherwise the speed becomes one so let's say that the new speed is going to equal to -1 if the current speed is equal to -1 if the current speed is equal to -1 if the current speed is greater than zero otherwise it becomes one now we can add to our q the new you know direction that we're traveling so we're going to say q the append uh moves oops moves plus one uh our position remember the position stays the same when you issue a reverse command and our new speed which we just calculated so we'll say speed cool let me just run this make sure i didn't make any syntax errors cool it looks like it works so let's submit this and it flies cool so what is the time and space complexity for this algorithm this one is quite tricky if our speed was constant so every time we were just moving by one then it's a breath first search it would take us probably big o of end time in the worst case to reach our you know target but because every time we issue an acceleration command and we're always accelerating basically we always multiply our speed by two so because the speed is doubling each time uh our space our time complexity is actually going to be log n or i guess log t uh where t is the target basically so that is the time complexity and the reason for it again it's a little bit confusing but basically because our speed is doubling each time uh that's why it's log two and it's actually log base two of t uh not yeah i guess log whatever you guys it's normally log base two anyway um so it's yeah log base two similar to how you know in binary search our search space halves every time in this problem our speed is doubling each time which is why we're able to reach it in basically you know log uh log t times so space complexity for this one you know again if our speed was one each time then it would be big o of t where i guess t is the target um but because again we double each time we're actually not going to visit every single place so the space complexity is also going to be log base 2 of t so that is how you sell race car this is an interesting one because a lot of the solutions are actually dynamic programming but like i said earlier in the video i absolutely hate dynamic programming i think it's the worst thing on earth i don't think any interviewer should ever ask this garbage way of solving questions i think it's total bs and you know this is a much simpler much more intuitive breadth-first search more intuitive breadth-first search more intuitive breadth-first search solution which is really easy to code up easy to understand and if your interviewer doesn't accept this then they're really mean and they should reconsider their life choices because it's a bit of a dick move to only want the dynamic programming solution so that's how you solve race car with a bfs solution if you enjoyed this video please leave a like and a comment it really helps with the youtube algorithm if you want to see more videos like this if you're prepping for your google interview your facebook interview your insert big company here you're going to want to watch my videos subscribe so you don't miss future uploads otherwise thank you so much for watching this video and have a great rest of your day
Race Car
similar-rgb-color
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse): * When you get an instruction `'A'`, your car does the following: * `position += speed` * `speed *= 2` * When you get an instruction `'R'`, your car does the following: * If your speed is positive then `speed = -1` * otherwise `speed = 1`Your position stays the same. For example, after commands `"AAR "`, your car goes to positions `0 --> 1 --> 3 --> 3`, and your speed goes to `1 --> 2 --> 4 --> -1`. Given a target position `target`, return _the length of the shortest sequence of instructions to get there_. **Example 1:** **Input:** target = 3 **Output:** 2 **Explanation:** The shortest instruction sequence is "AA ". Your position goes from 0 --> 1 --> 3. **Example 2:** **Input:** target = 6 **Output:** 5 **Explanation:** The shortest instruction sequence is "AAARA ". Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6. **Constraints:** * `1 <= target <= 104`
null
Math,String,Enumeration
Easy
null
154
Hello hello everyone welcome to date 20th family four interpress question research indicates what is a country and in this question give a thought if chosen by one of the selected and selected item withdrawal in more subscribe and subscribe this Video plz subscribe Channel subscribe our a Place to this site is created for kids in the search for direct oo aleikum members join date 20th and spine more the country which of this example of short dresses subscribe this Video plz subscribe Video in case your target element great Indian middle element this subscribe Do Robert Laptop Rate 100 Year Old Man On Thursday Off Units Development Unit Certificate Vikram Subscribe Problem Is The Police Tried To Support There Gold From Now For Life For The Difficult Question To Give Vote The Two Parts Identify Weather Your Life In More Vidmate Element At index mist subscribe The Channel And subscribe The Amazing spider-man 2 that is my target element Life without boundaries this and this I will reduce middle high point - side increase point to make middle high point - side increase point to make middle high point - side increase point to make flying dual elements and include the mid-1990s that and in this But I Don't Like This Point Oil Moonlight Index 211 Ismail Acid Target Element subscribe The Amazing subscribe and subscribe the Channel Quit To Take Care Of Bin Incomplete Liquid Subscribe Meeting Lo To Subscribe Loot-Loot Report Subscribe Loot-Loot Report Subscribe Loot-Loot Report Subscribe Now Start - 151 - Subscribe To Now Start - 151 - Subscribe To Now Start - 151 - Subscribe To This Contest May Target Vikram Thakur Sequence To Norms Middle Element Oil Awards Press Returns Through S Hai Na Tu Kab Se Prasad Logic Sirf Mez To Know How To The Number Of The Great In The Mid-1960s Who Is The I Left Time Set Alarm Targets In Index Loop number at nine and half according to a and metal index tight means and detergent live in this they will remove all my online text two plus two dialogue element live r lives on that jis pot dash plunder andal move hide two minus one subscribe and notifications no Loot Andheria Check Weather Return Gift Is Out Of Bounds Not Target Hotspot Of The Fat Bonding Hai Loot Score And Middle Images Cider Path Tiffin Us Of Lo Who Is Greater Than Number Format Do It Means Tried It Software &amp; Electronics Right Under The Thing Target Subscribe Button Rumor Will Do Subscribe To Ayyappa No Right To Life It's A Maximum Video Clip Next Flight Hai And Sunao The Limits Of Mid-Day That Accepted 16 Images Pocket Two Algorithms For That Everything Comes Clear With Specific To Deep Discussed A Distant View of Declaring and Points Sandwich Subscribe Our Video Friends Video subscribe and subscribe the Channel subscribe and subscribe the Note After Landslide Arvind is Case and Reduce Amazing at How to Do Subscribe My Channel Subscribe My Middle and Lower Middle Class is that Anna and Dhan etc. Finnish Acid President liked The Video then subscribe to the Page if you liked The Video then subscribe to subscribe for Live Video Lutab School Subscribe That Thank You For Watching My Video Provides You
Find Minimum in Rotated Sorted Array II
find-minimum-in-rotated-sorted-array-ii
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,4,4,5,6,7]` might become: * `[4,5,6,7,0,1,4]` if it was rotated `4` times. * `[0,1,4,4,5,6,7]` if it was rotated `7` times. Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`. Given the sorted rotated array `nums` that may contain **duplicates**, return _the minimum element of this array_. You must decrease the overall operation steps as much as possible. **Example 1:** **Input:** nums = \[1,3,5\] **Output:** 1 **Example 2:** **Input:** nums = \[2,2,2,0,1\] **Output:** 0 **Constraints:** * `n == nums.length` * `1 <= n <= 5000` * `-5000 <= nums[i] <= 5000` * `nums` is sorted and rotated between `1` and `n` times. **Follow up:** This problem is similar to [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/), but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
null
Array,Binary Search
Hard
153
421
hi everyone welcome to my channel let's solve the lit code problem maximum jar of two numbers in an array so given a non empty array of numbers a 0 a 1 a 2 and a n minus 1 where all the numbers i lie between 0 to 2 to the power 31 so we have to find the maximum result of ai or aj such that inj lies between the range 0 to n and we have to come up the solution of o and runtime solution so solving this in o of n square solution just nest the two try to create all the pairs of ai aj and get the maximum over them of their jar which is very straightforward but this solution is of n square and the problem is asking for we have to come up with the o of and solution so how we will solve this problem in o of n so this is the first example given here so let's understand how we will solve this problem so over here i have write down the binary representation of all the numbers and these number is the biggest number so its binary representation is occupied 5 digit 5 bits so i have extended others numbers in the 5 bit representation as well so first of all let's understand what is your so if we are doing two jar so the truth table of jar if we do zero g dot zero we will get zero one jar one is also zero and the opposite bits like one yard zero and zero or one this is the truth table of the jar operation so we will get the one so for the maximum jar we will try to achieve as maximum one from starting from the left side of the number so if all the numbers in the memory is represented as a 32-bit the memory is represented as a 32-bit the memory is represented as a 32-bit binary representation 32 bits so this is just i have for explanation write it down on in all the five bits representation so we will look for the two numbers they have the different bits basically most of the opposite bits so that we will always get this one like this so if we go here in the first so we have this number which has the first bit is one and other number is can we support this number so we can get at least the one and other four let's say 0 so we can get maximum at least this number which is corresponding decimal of 16. similarly once we get the first set tweet we will also look for if we can get like one and then other whatever we will look bit wise bit like first we started from this bit uh like the if in the five fifth bit basically or zeroth bit from the left side then second weight and so on so if we try for this so we will check we have uh this is out of picture this number and this number is also out of picture but if we do jar of 25 with rest of the number 2 5 3 we can get this so this will be corresponding to the number is i think 24 yeah 16 plus 8 which is 24 so we can get max 24 if we do then we will go further one more step down which is we will look for is it possible to get 1 0 in our number or not so this is the approach we will try now how to solve this as a programically this is the understanding so for programmabically solving this first of all to finding a particular bit like set width or the bit number at a checking bit at particular number we will use a mask so we will use a mask which will we will use mask and we will shift that many bits time one of left shift so left shape is basically if we start with one this will be the like number zero and so on zero one if i do let's say three time left shift of this one then this will give me one zero basically we will shift three time this left so this is like this so 0 so this is how lefsef operative works now if we start so let's say right now we have 5 bit so we will start look for this so we will do the left shift of this basically total n which is 5 minus 1 so 4 times if we do 4 time we will get a first mass 1 0 so this is a mass which is in decimal is 16 basically so we will do the j bitwise and with all of the number so if we do the bitwise and with all of the number we will get only d here two things one is zero and if with all of the rest of the number except this number because this number 1 will match so we will get 1 0 from this so this number will give us 16 which is corresponding to 1 0 so first we will create this and store as a prefix in our one of the data structure we are set we will store these both of them first we store now we will look for the fifth bit the maximum jar we will generate the maximum jar so we will initialize maximum jar again from the variable zero and then we will check is there two numbers in our set which has basically prefix like opposite to so starting this we will use a one temp variable again the same as the we will do the bitwise shift and take or with the current max so we will do the current max or with the and the number of time we will again save to this guy to set that bit one so ith time so here it is will be initially it will become one zero again now we will use this stamp and iterate all the element in our set so let's say we will iterate all the element as a prefix in our set so this is my set which has in the first like 0 and 16 so if i trade so let's say if i got 0 so 0 means 5 0 for 5 bit representation and the temp is 1 0 so if we do the bit wise like this jar of these two thing we will get these stills and we will check if the set contains which means it's confirmed that we have two number which has the opposite bits at this place the eighth number like fifth bit like first bit from the left so we will set this bit break this and max chat our maximum at least with this number temp current time and then we further this is we did for the first bit here now we go one more down the line the we update our mask so in the mask also we will keep the previous width so we will do bit wise or with the new mask bitwise or with the current mask and the shift this now three times so the current over bit mask is one zero and we will do bitwise mask with one zero and zero will be here so this will become one zero 0 so this is our now new mask then we will do the bitwise and with all the number and store in the set now in set if we store we will get the 3 number like 0 8 and the 16 this is corresponding to five zeros in bitwise in bit representation this is corresponding to 0 1 0 how we will get if we do bitwise end of this mask with this two number like eight and ten we will get this eight similarly if we do b25 we will get one zero so this is not sixteen it is twenty four basically this time so now if same thing we will use it so now we have three elements in our set which is like 0 8 and 24 now we use again our tam which will become max or the initially max we have 1 0 and then we will again shift this bit here 1 with 3 time so this will become r with 1 0 and 0 is here so this will again become the temp is same as like mass basically so this is now we will do the bitwise or of each of the number and check if this guy is contained if we do bitwise jar with this so the we will get this itself which is 24 and this our side is contained so we found the prefix that two number which has the opposite two bits so this will be our next maximum so we will update maximum so this is the basic approach to solve this problem is uh using the bitwise operator so let's start the implementation first then i will explain the time complexity and space complexity for this solution so initially we need a one mass which is initialized from zero and also the max variable which is will hold the bits of our max joint then we will iterate from it i is equal to 31 by 31 because our number is represented in the memory integers is in the 32 bit so we start from the 31 we will go to till the uh 0th bit so this is 0 i minus so now first of all we will generate our mask so this mask will be mask is equals to mask bitwise or with the left shift of 1 at how many times i times so this is how we generated the mask first now let's define a set which will hold all the prefixes which we generate with the bitwise and with the mask so this will be let it call set new hashtag now we trade all the nums in num in nums array every time and store that set dot add the mask bitwise end with the num so we will add that in prefixes in now for the eighth bit of our max we will look for so initializer time variable so this is max or again the same as like 1 with y shift i time now we iterate all the prefix which we generated in our pref chat which is let's say call prefix into the set then we will also check if our set contains the prefix from the temp bitwise jar with the uh current prefix number if this is there like two number which is sharing the different bits in that case we will update our max with the current attempt and break here for this bit at least we found the number and we will do for all the 32 bits and in the end we just return whatever bit sets we found in our max which is our maximum job so let's compile this code and see if it is compiling and we are getting correct answer yes we are getting correct let's submit this code and it is accepted so now let's understand what is the time complexity so if you see over here we are doing this uh array iteration every time for all of the 32 bits so this the time complexity of this solution is o of 32 n is the length of our i so this 32 is constant as we can doing big o of so we can also say that this time complexity is o of n and the space complexity of the solution is it's like depend how many we are getting like in the first case we will get the two element only in the set and the second case we can get more 4 but in worst case in the end we can get an element in our set so that we can say space complexity is often so this is a solution try it out it is not that easy to come up with this kind of solution unless you are familiar with bitwise problems orbit wise operators so try it out give a try there are very like other problems try them out like one of the similar kind of problem is hamming distance two problem which is like solution is which exactly i can say is kind of similar to this solution so try that out as well i will provide the link so if you like my solution hit the like button and subscribe to my channel thanks for watching
Maximum XOR of Two Numbers in an Array
maximum-xor-of-two-numbers-in-an-array
Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`. **Example 1:** **Input:** nums = \[3,10,5,25,2,8\] **Output:** 28 **Explanation:** The maximum result is 5 XOR 25 = 28. **Example 2:** **Input:** nums = \[14,70,53,83,49,91,36,80,92,51,66,70\] **Output:** 127 **Constraints:** * `1 <= nums.length <= 2 * 105` * `0 <= nums[i] <= 231 - 1`
null
Array,Hash Table,Bit Manipulation,Trie
Medium
1826
228
Hello Hi Everyone Welcome To My Channel It's All The Problem Summary Ranges So You Are Tunic Interior Anthems Returned As Molested List Of Ranges Is That Cover All Numbers In The Land Of Blood And Subscribe One Of The World With Me If This Are Sorted Unique Are one to three is 1012 Subscribe now to receive new updates from 400 500 Here's in the mid-1960s 56001 929 Verizon Adheen dhlo len dr eid to kal morning questions page subscribe if you start number of the end of the subscribe start from Air Tight That Sister What I Will Do Inlaid With Sacrifice next9news Is Anek Number Sunf Min Se I Plus One Who Is Equal To Two Numbers Of I A Plus One Officer Case Will Keep Increasing Genes Power Rangers Which Is Like This Is Unfolded In The Same Age Limit for doing this will also not the best of the con is on start position of power current ranges number 5 ft ki and e will keep trying to attain it is possible and also will support and attractive no deposit amount of vs number of elements subscribe now to The current element amazes subscribe break and subscribe but more will follow subscribe share and subscribe our subscribe ranges from start that harold gender current and systems for a day to olive enum cleaning notification victory destructive list and will keep continue strongest and show the video and audio se Celebs Kim Pigmentation Mother Quotes For The List Of Births Subscribe The Amazing Nor Will Run From A Number Of Elements And A Plus Thursday Ko Hai Na Ho First Vinod Sony Staff Power Rangers Witch Will V95 Nobody Will Keep Trying To Check Five Plus One Class Ninth And Have Na Dhoye Is Equal To Numbers Of Sonam Plus One Five Plus One Medium Subscribe The Amazing List Dhoye Representation Like This And Updated On That Otherwise It Is Not The Case Will Just Add List Daughter I Secure Pimp Code Implementation And Tried To Compile Wait And See How Do Something For Different Cases Are With Women Are Being One To Haridwar Just So Let's See That No That Is No Difference Navya Confident Enough But Can Submit D Code Yo Honey Tips Accepted S What Is The Time Complexity Of Dissolution Severe One For What You Mean That Nobody Will Run From Over Time Complexity of Implementation subscribe this Video subscribe The Video then subscribe to
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
33
what is up guys Xavier LAN here I'm prepping for interviews so I'm doing a lot of leak code videos so please subscribe to my channel if you haven't already I'm gonna be posting fairly frequently today I'm going over searching sorted a rotated sorted array so the description reads suppose an array sorted in ascending order is rotated at some pivot point unknown to you beforehand basically they just move like the elements along spaces you are given a target value to search if found in the array return it to index otherwise return negative one you may assume no duplicates exists in the array and your algorithms run time complexity most on the order of o log n so right here when I see o login I immediately think binary search so that should be a huge hint so the examples they have here is the target is 0 so they're returning the 4th index and target is 3 there's no 3 in here so they return negative 1 so the way I solve this is basically we want to calculate the mid sorry my dogs going crazy calculate the mid so if the target is 3 we're gonna calculate the mid by doing mid equals and plus start / - so we're gonna get 7 plus 0 divided / - so we're gonna get 7 plus 0 divided / - so we're gonna get 7 plus 0 divided by two equals three point five it's a gonna be an int so it's going to round up to four so that's going to give us the mid of right here the fourth index that's just how it works and then we're going to check to see if start is less than the mid then we know that this part of the array is sorted but that's not the case start is actually greater than so it's not sorted so we're gonna not check that one first and we're gonna see if mid is less than and which it is so we know this is sorted and then we're going to check this to see if the targets in there and we're just going to keep doing that so that's how I solved it let's code it out hold on so we have start is zero and then int and equals numbs dot length minus one because of 0th index and we're gonna have our mid we're not going to initialize it yet so we're gonna do well start is less than or equal to end so we're going to loop through all the indexes basically and if nums let's start is less than lumps of mid then we know the start to end is sorted so that's what this means and that's where we're going to want to check for the target so then we're just going to check for the target so if numbers of mid is um oh and I forgot to actually the first thing we want to check is if target equals numbers amid this is what we're checking for then we return we're returning the index you know this over here return all right and then back if numbers of mid is less than or greater than the target and num start is less than two target less than or equal to the target that means the target is in that sorted array because it's mid is greater than let me show you on my iPad mid is gonna be so it's gonna be let's see if we do this one this is gonna be the mid start so we're gonna be checking this array because it's sorted target is 3 so we have move this over we have tons of mid is greater than the target that's true 7 is greater than 3 and then as a start is less than or equal to the target well yeah it is it's equal to the target so that still holds true and if that's the case we're going to adjust the high two because we know now we know the target is in that array that portion of the array so we're gonna do and equals mid minus 1 and then else that means the time if the other case is the target is in the other side of the array so we're going to do start equals mid plus 1 and then we just have an else so it's just basically the same thing except flipped so if nums of mid all over the place is less than target and numbers of ends this time is greater than or equal to the target and the reason we use great add the equal sign is because it's never going to equal numbers of mid because we already check it up here so we don't add that but we do at it for here because it can equal it like I showed you in the last sample the start did equal the target but we're returning the mid not we can't return the start so in this case we're doing we have to adjust the in this case we have to adjust the mid so we're moving them or no the start I'm sorry we're gonna move the start to mid plus one so it starts going to go here and still here and we do for mid is and so two or seven plus five divided by two gives you a 12 plus or 12 divided by 2 is 6 so this is the sixth index so this is going to be the new mid yeah and that's the case for a different target if we had a different target number I know I'm a target up here but I was just showing you guys that so hopefully that makes sense and so like I said we need to move start in this case so we're gonna use this same statement their statements are just going to be flipped because the targets in this part of the array instead so and then else and equals mid minus one because if the target isn't in that then we need to it's in the other part so we're checking the sorted arrays because that's what we need to check and yeah that's about it and then if we if the start ends surpasses the end we and we kick out of the while loop that means we did not find the number so let's return negative one and let's see if this works yeah oh and I did not calculate mid just that's dumb a me and divided by 2 all right so yeah this is the correct code this is actually gonna work oh sweet all right and then the so the running time is like it even says in the description Oh login so that's binary search that's why that's that we didn't have to create any data structures so the space come yeah the space complexity is o of 1 it's constant and that's about it please subscribe if you guys haven't already and thanks for watching and if you guys have any questions at all please just don't hesitate to contact me I will answer love to answer any questions and if you guys have any problems you actually want me to post videos on let me know and I will do that as well so thanks for watching
Search in Rotated Sorted Array
search-in-rotated-sorted-array
There is an integer array `nums` sorted in ascending order (with **distinct** values). Prior to being passed to your function, `nums` is **possibly rotated** at an unknown pivot index `k` (`1 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,5,6,7]` might be rotated at pivot index `3` and become `[4,5,6,7,0,1,2]`. Given the array `nums` **after** the possible rotation and an integer `target`, return _the index of_ `target` _if it is in_ `nums`_, or_ `-1` _if it is not in_ `nums`. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 0 **Output:** 4 **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\], target = 3 **Output:** -1 **Example 3:** **Input:** nums = \[1\], target = 0 **Output:** -1 **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * All values of `nums` are **unique**. * `nums` is an ascending array that is possibly rotated. * `-104 <= target <= 104`
null
Array,Binary Search
Medium
81,153,2273
1,935
that's all from 1935 maximum number of words you can type this lead good problem says that you'll be given two experts one is a string uh string which would be a sentence okay the second string will be the list of characters and we need to find how many words in the sentence so if the sentence is called text so how many words in the sentence do not include any of those characters from the second string so second string in this case would be call broken letters and broken letters for example is a um T right so and this is the first r in purchase the sentence so we can certainly consider hello as one word which doesn't include any character from broken letters okay second the second word contains D which is there in broken letter so we cannot consider this so in that case we return one because only one can be uh one word out of the sentence do not include any character this similarly in the second example the broken letters are lnt so and the sentences lead space code so the first word contains lnt so we cannot count that but the second word doesn't contain any character which just there in broken letters we can count that so we WR one the third example the broken letters include e and e is there in all the words of the sentence so in that case we would return zero so how am I going to solve this very simple what I can do is I can convert the broken letters into a set okay so convert broken letters in a set called B and then I'll go through each character in text and I'll check if C is equal to space then in that case I'll do a couple of things I'll increment count with current so I'll initialize both those variables now let's count I'll initialize with zero and current I'll initialize with one okay and I'll toggle current to 1 and zero so if current and current is equal to one and CN B then in that Quest I'll set current to zero okay so this I can write it as like this as well so if current and c and b then current is equal to zero okay and then at the end I'll return count plus current what will this program do is every time it encounters the space it will check or it will add whatever the value of current is there and add it into count also we'll have to reset current here to one okay so after every space and at the beginning of the sentence I'll set current to one and anytime I can counter a character which is there in broken letters I will set current to zero so when the next space is found it adds zero to count if that word had any character which is in B else it will the current will remain one and it will add one to count okay I'll reset current one after every word and ends and here at the end I'm adding current to the count because after the last word there is no space so in that case it will not consider it will never go here and consider the last word so that's why I'm add adding it at the end and returning it let's this and see if this works fine and that worked for the three test cases let's submitted and that worked for all of them
Maximum Number of Words You Can Type
minimum-number-of-operations-to-reinitialize-a-permutation
There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly. Given a string `text` of words separated by a single space (no leading or trailing spaces) and a string `brokenLetters` of all **distinct** letter keys that are broken, return _the **number of words** in_ `text` _you can fully type using this keyboard_. **Example 1:** **Input:** text = "hello world ", brokenLetters = "ad " **Output:** 1 **Explanation:** We cannot type "world " because the 'd' key is broken. **Example 2:** **Input:** text = "leet code ", brokenLetters = "lt " **Output:** 1 **Explanation:** We cannot type "leet " because the 'l' and 't' keys are broken. **Example 3:** **Input:** text = "leet code ", brokenLetters = "e " **Output:** 0 **Explanation:** We cannot type either word because the 'e' key is broken. **Constraints:** * `1 <= text.length <= 104` * `0 <= brokenLetters.length <= 26` * `text` consists of words separated by a single space without any leading or trailing spaces. * Each word only consists of lowercase English letters. * `brokenLetters` consists of **distinct** lowercase English letters.
It is safe to assume the number of operations isn't more than n The number is small enough to apply a brute force solution.
Array,Math,Simulation
Medium
null
316
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever post a new video so without any further ado let's get started problem is remove duplicate letters we are given a string and we need to remove the duplicate letters so that every letter appear only once you make sure that your result is the smallest in the lexographical order means when we have ascending order so like this is a string so if there are all permutations of the string and those are arranged in the ascending order so our string whatever string we will make that should be in the like the smallest in the lexographical order meaning it should be the smallest among all possible results okay so uh let's see how we can approach this problem here c this test case b c a b c so here what we are doing is we are taking a first then we are taking b and then we are taking c we are not taking this b why because uh here there is a so we are taking this a and we are not taking we are a taking this a and we are taking this b we are not taking this b so let's take this test case and just let's see how we can approach the problem so we have b c abc fine now see over here uh we have b here but b also we have here we have c but c we have here also so either we can take this b when we take this b then we go to the c then we go to this a this string we can make or what we can do is we do not take this b we take this b so uh we can have a this b and then the c another thing which we can do is we can take this c this a and this b c a b fine abc cab so he from these like lexographical like the smallest one which will come when we do ascending order so this is the lexographical smallest abc the smallest number and then it's increasing this here first letter is c here first letter is b but this is obviously smaller right first letter is a so the thing is that we will prefer c the thing is we will be preferring we will prefer taking the smaller letter when i say meaning a is the small a smaller than b fine prefer taking smaller letter so see over here we have taken a first and then we have taken b let me just change this test case to something different so let me do one thing let me have something like this c uh a b c something like this so uh or let me do it like this b will be coming here or uh before this so like this it's c b a c now the thing is guys we have to see c we can take this one also so there is no problem for c but b we have to take this only because there is no b after this fine in the previous test case was bc abc in that we neglected this b we did not take y because b was here after a but here b is only this only there is one occurrence of b so b we will take this one only so b a and then c will be the output for this one could be c we take this c we do not take this c we take this c b a but obviously this one is smaller so that's why we are com we are taking this so the thing is we will be prefer taking smaller letter but if there is but if like this b has only like there is no other b after this so we'll be taking this b only fine so we need to store but we have to like we have to store the see we if we have to store the last index of a letter because c over here we neglected this b because we knew that b is here so there could be multiple b's right b could be here also so something like this could be there b c b a b c so we will neglect this b because we know that b could be here also b's like the maximum index where b is so 0 1 2 3 4 5 so maximum index here is b fine so we have to store the last index of a letter so that we can check can we neglect this b because we can neglect because there is another b present here so if we are at two index we can neglect this b because this b is also present at 4 index fine so we will get it afterwards also but let's say over here in this case c b a c and let's take b here also something like this we have fine so here we can neglect this b because we knew we know that b is present here also but when we come here we cannot neglect this b because this is the last occurrence of b this is the last index where b is present so we cannot take like this b we have to take it anyway even though like a smaller than this b but still this is the last occurrence of b so we have to take it bac fine so i hope you understood this thing let's dry run let's see how we can use this thing in our approach so here let me raise this so over here this test case let's take the second test case now this one here we have c and this is d fine uh so first of all what i will be doing is i will be taking an array i'll take a character array so when i say character array because these will have characters only now and that too also the lowercase english letters so there will be 26 lowercase english letters so i'll take an array for storing the last indexes of all characters of all letters so this array will be 26 size 0 to last index will be 25 okay this is a character array which i have taken that is here zero will be representing a one index will be representing b two index will be c and three index will be d and similarly this will be e and so on okay so this i have taken this array i will be storing the last indexes of each letter because that we need to know so for a what is the last index let me do indexing 0 1 2 3 4 5 six seven what is the last index here the last index of a one two three so two is the last index of a then what is the last index of b's last index is six c's last index is seven there are many c's zero at in at three index and then five index and then seven index and d is at last uh four so this is your and rest this will be zero zeros also like nothing would be there here so this is your character area right now uh what we will be doing is so see we let's say we have the cb uh a something like this we are going we are traversing on the string c b so see here we need to check over here c when we are at a we need to see that okay this b and c letters are bigger than a right they are bigger than a so i can avoid taking these if there are afterwards occurrences of these letters so i can avoid this cb because c is present after this a also and b is also present after this a so i can avoid taking these i can take a which is the smaller one so how to store what were the previous characters what was the previous characters how we can store that so we need to have a data structure for that previous character so for that we can use a stack why stack because stack we can use to store the previous characters okay and that too in the order so this will be first then this will be so that like that uh let's take a stack so i'm taking a stack here to store the previous characters i am taking a stack also i have been taking another character array uh let me remove this i will be taking another character array which will be storing which letter we have taken as of now so which character we have seen so this array name i am writing a scene and this is also character array 0 1 2 3 4 here this is a b c and this is d okay seen uh so let's do one thing let's try it step by step so see what we are doing is we will be starting i will start iterating on the string so first of all we'll go to c we will see so there is nothing in the stack as of now so we will just add the c will be added and in this here this see this area will be pre-filled this see this area will be pre-filled this see this area will be pre-filled like we will fill this area before only before iterating on the string this last index array you will understand what is the use of this uh just keep watching so here first of all we added c in the stack and then here uh c since we initially this will be false everything will be false now we have taken the c in the stack meaning we have considered it we have taken we have considered it so we will change it to true so this i will change it to true okay then we will iterate further so now we will go to b now guys see very important point here b is b letter is there now don't you think that rather c being the first letter of the string b should be the first letter because b is less than c and it will be more like so graphical smaller string if it starts from b other rather than starting from c right so if this letter is less than the top of the stack whatever is on the top of the stack c is on the top of the stagna c is on the top of the stack so b is less than c on top of the stack so b should be in the stack c can we can take afterwards only if c now another condition see we can remove only if there is afterwards occurrence of c so this is what this is one index right here c is last uh occurrence where is c lastly present c is present and seven index so this last index is greater than the current index meaning c is also present afterwards so we can remove the c we can safely remove this c and we can add this b and since we have removed the c so it will change from true to false we change from true to false and yeah that's it so what we have done what step we have done we have checked the top of the stack is if the current letter the current c of i let's say s of i if current letter is less than the top of the stack here it was b and this was top of the check for c if this is less than and c has other occurrences also so then we can remove the c and we mark in the scene array false okay so this step we have done now let's move forward we go to a now again top of the stack is what b and f is what a is less than b so obviously what's better a string starting from b or a string starting from a which one is better obviously this is better right we have to have the c we have to have the lexographical smallest here in the problem that they are saying smallest so we will take a so but before removing this b we need to check whether b is present afterwards or not so that we have to take v also right we have to have every letter appear once so we cannot neglect b if it's not present afterwards but over here current index is 2 and b's last index is what 6 so b is present so we can remove it safely so from here i will be removing b and i forgot to change it to true firstly so here uh true will be there but now since b is removed so it will change to false okay and a we are adding so a will be changing to true so it will be true here and a we will add in the stack okay now let's move forward so here now we'll go to c so here c is the current s of i and top of the stack is a which is not greater than this c so this is fine we can add now if this is the case so we can safely add this c in the stack so this could be the next letter c could be the next letter okay now we go to d so here s of i is what d and top of the stack is what c so is c greater than d no fine so this is fine we can have d also here we'll just push so this is if otherwise else we just push in the stack okay now we go here now see now it will be change now it will let's see what happens here now here s of i is what c and top of the stack is what d so d is greater than c meaning this d should be removed but do you think this d should remove this condition is satisfying but these last occurrence is what 4 and current index is what five these last occurrence was this only d this one there is no more d afterwards so we cannot remove this d we'll have to have it okay so even though this condition is getting satisfied but the last occurrence of d was uh less than this is the last occurrence of d it was less than the current index this is a current index and this is the last occurrence of d so then we cannot remove the d we cannot remove d okay and also we have to change this c's because we have added cena and d also so we have to change it to true i am forgetting it so we have to change it to true then afterwards now let's move forward and we will not add this c again see we will not add again will not push because c is already present uh see uh is already not here c is already present right in the stack so if we will not add c again then we'll go forward we'll go to b so here what is the top uh current letter b and it's less than top of the stack which is d so we can remove the d but see these last occurrence was this only so we cannot remove it again so we will just simply push b why we will push b now because p b is not present it's false so b we need to push we will push b okay and then c is here so c is already present here true will be there c is already present so we will not push it and string we have iterated c we have completed this traversal and here the stack is something like this so if we push the stack push items from the stack so b will be first then b will be there then c will be there and then a will be there so now we will reverse it a c d b and this is the output a c d b okay i hope you understood this approach let's see how uh let's see the code now so see what we have taken three things one is the stack other one was this last index array and then the scene array okay so last index area we are storing the last index of all letters then we are taking taken this scene array and this stack okay now what we are doing here over here we are iterating see this is we are iterating this for loop we are iterating um if we have seen that character we will just continue so here like for example c here in this c was already seen so i will just continue we just move forward otherwise if the top of the stack see if the top of the stack is greater than so5 and i is less than the last index of the top of the stack so like top of the stack was d uh but it's that condition was not satisfying so we need to check if the last index is when the like if there is any other occurrence of that letter or afterwards so if there is then we can remove that letter and we can change to false and we can push the character and we can mark seen as true so after this for loop we will have a stack something like this then we can just simply pop from the stack but we popped from the stack it was in rever it was in the reverse order so we will reverse it and we will get the output so we will reverse it and we get the output and we'll return it i hope you understood the problem uh time complexity see we are doing single traversal time complexity is of n and space is of n also because we are taking this extra data structures i hope you understood the problem and the approach let me know in the comments of any doubt if you found the video helpful please like it subscribe to my channel and i'll see the next video
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
705
um hello so today we are going to do this problem which is part of lead code daily challenge so what we are asking to do is basically um just to design a hash set without using any built-in hash tables so we using any built-in hash tables so we using any built-in hash tables so we can't use um a python dictionary um and then here um we have multiple we have the of course the add function to add a key to the our hash set we have contains to check if the key is in the hash set and then we have removed to remove a key um from our hash set right so pretty straightforward now the problem says that the key is between 0 to 10 to the power of 6. okay and we'll have at most 10 to the power of 4 cores so how do we do this well the simplest solution because we know the keys are integers and they are between 0 and 10 to the power of six this is not efficient and not the actual y hash set isn't implemented it's not implemented this way but as a start for solving this is a problem it's definitely valid since we only need the keys 10 to the 0 to 10 to the power of 6 right what we can do is just create a Boolean array right that um will mark an a position as false or true depending on whether the value is in the hash set or not okay that way if we want to add a key we can just mark it as true if when we remove it we Mark the position as false and we want to check contain we check if the position is true right um so that would be something like um let's just do it like this so it would be something like this here we want to initialize it to false first for all of them so this is going to be for all um the values in the range of um 10 to the power of 6. okay and then here we want to do self dot values of key um and we want to assign say true because we just added it and here we want to say false because we are removing it okay and if we want to check if it's present we can just return whether it's present or not okay now this is has a lot of space overhead but it should pass except here the index is out of range yep because we need 10 to the power of 6 plus 1 to reach if we get a value of 10 to the power of 6 to have it um in index then we need to add plus one here in Python so let's run it again to submit and this passes okay um okay so now let's see how we can reduce this space um so the key idea here is to use buckets right so basically before we were using 10 to the power of 6 right and so to reduce that space let's just use maybe 10 000 right you could also do thousand but whenever we get a key right to be able to fit it in one of the buckets here so let's have 10 000 buckets buy buckets I mean just lists right and whenever we have a key we will just do modulo ten thousand and that will give us the bucket index that we want to put it in and then we'll just add it to that bucket so what does this mean let's take a smaller number just to understand here so let's say we have only 10 buckets um and this maps to a bigger number uh but 10 buckets we just so that it's easier for us so if we have the key is equal to nine then we'll put it in bucket nine so we'd have like ten buckets so we'd have one two three four five six seven eight nine ten okay so this should be three five and then three five okay and so when we get nine let's just go to the ninth bucket here index nine um so our indexes would be one two three four five six okay so four six and then sorry about this and then we'd have seven eight nine okay so something like this okay um so when we get the nine key Nine right um here just to make the buckets work a little bit nicer right we can have number from um yeah we can number 10 like this okay it's fine um so we can put it here um okay so we'll put our value here so that would be just nine now what if we get let's say 11. okay so we'll do 11 module 10 that will give us one so we'll put 11 here okay so that's sort of the idea um if we get to key equal to maybe 19 then if we do modulo 10 we'll get nine so I'll put 19 here and then if we get so you can see when there is um when the value is in a key that has already another value we'll put it in the list right and this is what sort of the main issue with hash set and hashmap is to handle collisions and the fact that 9 and 19 here are both in the same position this is what the Collision was but how we handle it can be done differently in different implementation in our implementation here we are just closing using a list but in some other implementation you could use a linked list because insertion because removal in linked list is a lot faster um so you could you so that's sort of the main idea here um and then now if we get let's say key is equal to 13 then maybe 23 even we do my 0 to 10 right we'll get three and so we'll put it in position uh I think three here okay so I'll put it here 23 are and now so you can see the insertion should work fine now but what about the removal well same thing we go backwards so if we want to remove key equal to 11 again we do modulo 10 we find the bucket index so the buckets index would be one so we found it here and then we'll look for it in the list and remove it before I check if it's there similarly let's say for 11 we do modulo 10 we find the bucket index and then we search in the bucket right so here maybe there were multiple values like uh 14 uh maybe there was here like one sorry this is 21. 31 right then to search for this 11 we just search if it's in the list okay so that's the main idea behind the solution now let's cut it up so we need buckets so let's first say the size of our buckets is going to be um 10 000 in this case here and so let's just ten thousand we'll do plus one to fit the last one and this is now false we want a list for each bucket and then what we want to do next is basically just um here we want to get the bucket index to know where to add this right and so to do that well we'll just need the bucket um and let's call it let's create a function to give us the index okay so let's create a function to give us the index for a key and so for that function what do we need um to get the index well um we just need to get the key modulo the number of buckets first okay so that gives us the bucket index okay and then in the bucket once we get the bucket so it's going to be just like let's call these buckets actually so we are going to take self-doubt buckets here and we get the bucket itself and now to search for the element key we just go through the list in that bucket so let's just say I can the bucket now if the element is equal to the key we found it then we're going to return the index I but we also want to get the bucket index so let's have this written both the bucket index and then the index of the element itself now if we are not able to find it in the bucket then it's not there so let's just return something that says that the element is not there so maybe you can just return minus one so now with this index function um it's easy to change this here so what do we need to add an element so we'll get for to add an element since it's not there we'll get a minus one but let's we can still call index to get the bucket index so let's call index to get the bucket index so here we'll get the bucket index and then Let's ignore the other value because we don't need it um and so we can just append to this bucket right we can just append the key so this would be solve that buckets okay but I think here the problem says see the problem says for add to insert the value but this is a hash set so if the value is there maybe we want to just not add it right so to do that we can just check if the value is there so Q is already there then we can just skip okay so this is how we handle the ad now how do we handle the remove we can do the similar thing here so we want to go and remove position at position I or remove the key so in a list you can just remove the key itself like this the value itself okay so how do we Implement um checking if the value exists well again we need to check the index right so and then we just check remember if it's not there we'll return minus one so if it's not there so just if it's there then the index would be positive big or equal to zero if it's there the index would be big or equal to zero if it's not there it would be minus one we could also just do different the minus one here okay um either that or we can do this okay so now let's run this and see if it works looks good so basically the main idea here is using the modulo to get a bucket then the bucket we add the elements in a list and so to search for them we just we do it this way by just going through the list um if we wanted to we could use a sorted list as well that's another option to keep the list sorted and to um sort of binary search to search for the element that's also another option so let's submit this um looks like there's a problem here let's see okay so in remove here we want to check if the element is there before removing it right because it's not there we don't want to remove it so how do we know if it's not there we can just check if the index is equal to -1 then we don't want index is equal to -1 then we don't want index is equal to -1 then we don't want to remove anything that's right there so let's just fix that submit and this passes okay yeah so that's sort of a better implementation as an exercise you could also try to solve it with a linked list yeah that's pretty much it thanks for watching and see you on the next one bye
Design HashSet
design-hashset
Design a HashSet without using any built-in hash table libraries. Implement `MyHashSet` class: * `void add(key)` Inserts the value `key` into the HashSet. * `bool contains(key)` Returns whether the value `key` exists in the HashSet or not. * `void remove(key)` Removes the value `key` in the HashSet. If `key` does not exist in the HashSet, do nothing. **Example 1:** **Input** \[ "MyHashSet ", "add ", "add ", "contains ", "contains ", "add ", "contains ", "remove ", "contains "\] \[\[\], \[1\], \[2\], \[1\], \[3\], \[2\], \[2\], \[2\], \[2\]\] **Output** \[null, null, null, true, false, null, true, null, false\] **Explanation** MyHashSet myHashSet = new MyHashSet(); myHashSet.add(1); // set = \[1\] myHashSet.add(2); // set = \[1, 2\] myHashSet.contains(1); // return True myHashSet.contains(3); // return False, (not found) myHashSet.add(2); // set = \[1, 2\] myHashSet.contains(2); // return True myHashSet.remove(2); // set = \[1\] myHashSet.contains(2); // return False, (already removed) **Constraints:** * `0 <= key <= 106` * At most `104` calls will be made to `add`, `remove`, and `contains`.
null
null
Easy
null
6
Hey gas welcome back, you have kept my channel and have given the number of days, okay what do you have to do, row on zigzag pattern, we have to arrange 22, we have to arrange as many days as we have given, we have to arrange it and the string. What we have to do is to read line by line and the sting that will be ours has to be given to us line by line. Okay, so what we do is let us understand through the example what is the problem, then we will see how we can solve it. So look here, what we have given you is a string S and a number of roses three, so what we have to do is to make a zigzag pattern like this and in this the number of roses three is given for this. You have to take four, there is a van here, okay, so here we will arrange it first on the zigzag pattern, so look what is here, then we will drink first, after that, what will happen to us after A will be ok after that P then P what will we do after that we will put it here then where we will put it here what is after L what is your after I what is after i van tu three ye After three lines, we have to return the sting, it will be like this, then APL SII, look at the HP of these two cards, so what we have to do is to read it line wise and return the sting. How will we solve this problem, how can we do it on the pattern, so look let us see, if we store this pattern somewhere, what will we do after fixing it, we will read it line by line and make a string, then we will store it. How will we do this? What will we do? We will take a vector of string. Okay, so the number of rolls in the vector of strings will be the same, what will be our elements? We will have lines. Three numbers of rules have been given, so there are three lines here. If you had seen four, then we would have arranged among four, then this is your one element, take one, what will you do, then you will store this testing app, it is ok at zero index, you are at index, that is, the size will be three, your number of roses will be equal to your vector. OK, now your challenge is that the string you will create at the zero index should be P A H N, the string you will store at the Van index should be A P L S I G and the string you will create at the V index should be A I R. It should happen, now you will do this, how will you do this is your challenge, so look for it, we will do, let me show you, what will we do, we will start from here, okay, so what will we do, we will take a flag When it goes down, it will go till the bottom. When it goes up, it means what we have to do is to keep interchanging. Okay, so we will know that we are going up. If we are going down, then what will we do accordingly, we will increase our index. In this condition, we have to What will have to be done, see, from here you will have to come from zero to the van, from the van you will have to go to you, from you then you will have to come to the van, then you will have to go to zero, then from zero you will have to come to the van, from the van then you will have to go to you. It means that you will do this in the van, this you will do this at zero, you will shoot 1, you will do this and what will you do with this, will you store it on the van, if you do it like this, then what will you do, what is the false man, now you are at zero. If you have stored P, then whenever your zero will be zero and number of rolls, number of roses, how much is here, if there is three, then 3 - 1 i.e. 2, how much is here, if there is three, then 3 - 1 i.e. 2, how much is here, if there is three, then 3 - 1 i.e. 2, when you reach the last index of the first index, then what will you do with this flag? You will make its opposite, it is okay, we will flip it, you can say flip, now this is our false, so what can we say, it is at zero now, so we make it true and as soon as we feel that this is our true, then what can we say? We will do plus van, okay so that means i is your van. Know when the flip will happen. When your number is zero and your number of roses is minus one, then we will flip. If this is still true, then we will do I + 1. Whenever this is true, + 1. Whenever this is true, + 1. Whenever this is true, we will do plus one. Till here we have gone to A. Still. True, ours is to tu pe, what will we do? We will store A and we come to know that we are on tu, that is, where we are, if we are on the last row, then what will we do, we will flip it again, that is, what will we do by making it false? If you give it okay then it will come to know that the fall has happened, then what you have made of yours, you mine it again, make it a van, then if you go to the van, then where will you store this p, here people will pay according to the ai. What is still yours, this is your falls, so whenever the falls is there, you will do mines, what will happen with the van, it will become zero because this is your falls, okay, flag is your falls, then what will we do, we will do this here. Okay, where has A gone to A has gone to zero, then flip it again, that is, if you want to make it true, then you have to make it true, then when it becomes true, then I will be your I plus van, then it will be van, so van pe we. If we store the next element then what is the next element is our L so we will store L here okay then this cat of yours is true so I is yours again you will become you now what will you do now you will put I here because the next The element is yours, ok, it has been stored, now you know that it has reached the last row, so flip the flag of what it is, what we will do here is to flip it i.e. false. Whenever there will be a fall, we will i.e. false. Whenever there will be a fall, we will i.e. false. Whenever there will be a fall, we will mine I to Van, that is, it will go to Van, so I started here last, after I, there is S, so what will we do on Van, we will store S, so what is ours now? If it is false, then what will happen to our i will become zero i.e. -1, this will make minus i.e. -1, this will make minus i.e. -1, this will make minus van from van zero, then at zero what will we do, again we will store h because after s you have h, okay now you know. That if you have gone to zero, then you have to click again, then you will make it true, you have not done it, OK, what will happen after doing true, it will go from zero to van, now what is after this, if it has come, then it has come here. Pay will be sold because according to WAN, you have got WAN index, so here you people, then you know that this is true for you, so what will happen to you, what will we do, we have started income from I. If there is R then we will store R. Okay, now you know that now you are on the last row, what do you do, flip it, whenever you fall, what we have to do is to mine it, okay - 1 will become 2 to 1. mine it, okay - 1 will become 2 to 1. mine it, okay - 1 will become 2 to 1. What do we have to do on this van? We have to store the element after R i.e. if we want to store the element after R i.e. if we want to store the element after R i.e. if we want to make income then this will become I. Now what is yours if it is false then I will have to be mined i.e. you will have to make zero on 0. i.e. you will have to make zero on 0. i.e. you will have to make zero on 0. What will you do by going and storing N? Then you come to know that you are at zero i.e. first row. Okay, then you have to are at zero i.e. first row. Okay, then you have to are at zero i.e. first row. Okay, then you have to flip it to true and whenever it is true, we increment it by van. If I van is done then we will do IBPS and do the last element. Yes, you got this, make this string on zero, make this on van, make this on you, now what will we do, we will take another flu, take a sting answer with zero, in which what you do is zero. Index Burnai Zero B One Plus B Tu i.e. add all and return this final, so Tu i.e. add all and return this final, so Tu i.e. add all and return this final, so this is how we will do, if we will solve this problem, then what do I do, I will also show you the code, so see here what we did. We have taken a vector of string with the name answer A, whose size will be equal to your number of roses. Okay, so whenever our number of roses becomes one, what will you do? If it is one, then we cannot increase it. Right here, you will get all the details in this row. If you have to show then whatever string will be yours will be your answer then retain the string S adrevise what to do now in blue flag falls slowination i zero no and one by one character we will see what will we do ok first we will add i to it. We will add mach to the eye index and then look at the vector. Is this eye our zero? Is this eye our last or first row? If it is any of the two then what will we do by flipping the flag? We are done if our flag is true. If it is i + 1 then we will adervise i - 1, i + 1 then we will adervise i - 1, i + 1 then we will adervise i - 1, what will happen in this way, one character will be stored on all the indexes, 22, now what we have to do is to take the string, okay now we will get each string, whatever we get, what we have to do. Please store it in this and we will turn it here so I hope you have understood. If you liked the video then please like, share and subscribe. Thank you.
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
94
this is binary tree in order traversal its lead code question 94 and is one of the Google interview questions so we have the roots of e3 we are dealing with the binary tree here and we need to return the in order traversal of each nodes values this looks very simple we already know the formula to do this we can use a depth first search algorithm and we can use a recursive function to achieve that but there is one small trick here we have to return the in order traversal of the nodes values through a vector so the vector has to be a vector of integers and we need to return the values for example one two three in a vector of size 3 where the contents of the vector would be the values of these nodes in order in the solution at first when you begin you only have this line as part of your solution it's a public function and this is the vector of integers that you have to return the name of the function action and the parameter which is eight nodes so it's a node pointer and to solve this challenge I'm creating a vector called values a vector of integers and I'm setting it as privates because I only need it in my solution class now I need to reserve some space for my Vector here and to reserve space I need to specify the capacity that I need for my Vector so if you scroll down to the constraints here they say that the number of nodes in the tree ranges from 0 to 100 so we need 100 slots inside of the vector to be able to store the values for a maximum of 100 nodes so here once I reserve some space in memory it means that I don't need to reallocate spaces anytime I'm pushing a new value this helps a little bit with performance then what I check here is if I have a valid nodes if you look again at the examples here sometimes they have null as the node meaning that there is no nodes there example one has a right child but it doesn't have any left channels just keep in mind that some of the values in the inputs are going to be null so I need to check here if it's not null then I'm going to follow the in order traversal algorithm and this uses recursion so if there is a left child we need to visit the left trials we then need to visit the current nodes in this context when I say visits we need to push the value of the current nodes inside of the vector and then if there is a right chance then we need to visit the right child and because this is recursive this logic is going to repeat for all the notes and when we are done we can return the values so these values Vector will keep getting updated at every function call and the last return that we'll get is the vector fully populated with the values from the binary tree that's pretty much all the logic that you need remember that in order goes left Roots right so this is the order that we have here let me run this code and we pass all the test cases but these are just the sample ones so let me submit it and we've passed everything with zero milliseconds so that's pretty good um I'll keep solving the other ones especially for Google interview questions so if you like my Solutions in C plus and you want more programming tutorials and coding videos please subscribe to my channel and I'll catch you next time
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
98,144,145,173,230,272,285,758,799
283
what is up YouTube today I'm going to be going over move zeroes it's a easy problem on the code I know I said I wasn't gonna do easy anymore but I really like this one I thought it was a little bit harder than most of the easies so it's a good one to know check out my slack channel subscribe if you haven't already now see you guys soon alright so today we have move zeroes giving it ready numbs write a function to move all zeroes to the end of it while maintaining the relative order of the dawn zero elements so basically we just want to move all the non zeros to the front and do it in place so we're gonna have oh one space complexity and minimize the total number of operations so that just means we're going to loop through it have my whiteboard somewhere oops okay so how would you solve this there's actually like a few ways the way I like to solve it is you check to see so we're gonna have I which is our loop counter and then we're gonna have I called it last zero so it's basically saying where the last possible zero was so we're gonna have if nums of I does not equal zero then we're going to swap the if it's not zero we're gonna swap it to the front where the last zero was and we're going to increment zero last zero plus bus at the end it keeps track of the last zero so we know where to so we're only going to be swapping it at the last zero so let me give you a demonstration so I'm gonna do this one right here okay so if num shevai does not equal zero it does not equal zero but we can't obviously swap anything so we need to have because it's the front so we need to add if I does not equal last zero because if they equal each other that means we're at the front basically the where the last zero is so we can't swap them you know and then numbers of I so we're gonna want to swap well actually we're gonna just move along because we're gonna hit this it's not gonna equal true for this one and it's not gonna equal true for this one because of this statement because I does equal last zero we only increment last zero if we execute this statement right here so let me just code it so it makes this one's a little bit harder to explain for me so int length equals Nome stop Thanks last zero so let's set up last zero equal to zero by less than rings so if numbs the first statement I had does not equal zero we're gonna want to swap it because we want the zeros at the back so if it doesn't equal zero let's move it to the last zero and if I is not equal last zero like I said they can't equal each other because that means we're at the front so we're gonna want to swap if we go back to the whiteboard the first case we were gonna want to swap is um so we're actually going to let me show you we're gonna increment last zero out of here because if we execute this basically singing I just exited it's basically saying that the last first zero I guess is right here so that's where we want to keep that pointer and we're gonna want to swap this with this so we just need to do numbers of I equals nums or no numbers of last zero sorry guys basically doing this as I go equals names of I and then numbers of I equals 0 because we just know we need to we didn't have to use the temp variable because we're just setting it equal to 0 so that's why we could do that so let's code that out numbs of last 0 it numbs of I equals 0 and I think that's it because we don't have to return anything it's void yeah I hope that explanation made sense I'm gonna go through the debugger because I know it was like it takes a little bit to pick up on so the bugger should make it a little bit more clear because I actually showed the swapping so we have last zero we're going to increment I let me give it a different test case I wanted to swap these two whatever we're gonna increment my last zero it's gonna stay the same because thumbs of I does equal 0 and okay so now we're at a equals 1 last 0 is going to they're not equal so we're gonna swap them and then we're gonna increment last 0 and it just does that so now it's 0 and it's just gonna loop through the entire thing until they're all swapped and all the zeros are at the back so that's all you have the hardest part is just coming up with the logic on your own I think you just need to really like analyze it whiteboard really helps interesting continuing to see problems just like this not just like it but just continuing to practice and you can develop an algorithm to actually come up with this reading other people's discussion posts and creative solutions also helps me so if you guys like this video like it I'll see you guys in the next video
Move Zeroes
move-zeroes
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3,12,0,0\] **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you minimize the total number of operations done?
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
Array,Two Pointers
Easy
27
935
um hello so today we are going to do this problem which is part of leod daily challenge night dialer so basically we have sort of a chess Knight so just similar to chess where basically Knight can move in L shape it can be either first two step horizontally and then one step uh sorry two steps vertically One Step horizontally or the other way around two step horizontally and then one step vertically right but the start is two steps and then one steps and sort of gives you an L shape um now the variations they add on here is that you have um sort of a phone pad um where you can stand on numeric cells right and so with this phone pad you need to apply these L shapes movements so that's the key idea here and you get n and basically what we are trying to get is how many distinct phone numbers of length n we can dial so if n is equal to one how many distinct numbers of length one we can dial if n equal to two how many distincts of length two we can dial so basically it's n is the number of digits and initially you can start in any uh numeric cell okay um and you so you start from a numeric cell and then you can do n minus one jumps makes sense because you need n digits when you start in a numeric cell you have the first digit and so the remaining ones are n minus one okay and the jumps you are allowed to do are only valid night jumps so only something like this or something like let's say if you are at four like this okay um and we need to give the answer modul 10 the^ of need to give the answer modul 10 the^ of need to give the answer modul 10 the^ of 9 so let's take a look at the first example here n equal to 1 what are the possibilities now the key thing here to remember is that you need all the variant so what does that mean that means you can you need to one possibility is to start at cell one the other possibility is start at cell two start at cell three so each digit you can start at it and then calculate the number of distinct phone numbers you can get from that cell so with n equal to one which means basically just one numeric value well the distinct one you can get are all the numbers here so can start at zero at one all the way to nine so overall that's 10 numbers or 10 phone numbers so 10 okay um for n equal to 2 it's a little bit different well for n equal to 2 you can first start from zero and then figure out all the variations so that means you start from zero let's say um and then you go two to six or you can um or you can start from zero go to four okay so two V two possibilities with zero that's the only possibilities because you can't go left or right um for one you can go from you can go for example like this to get to eight or it could go like this to get to six those are the only two possibilities and if you do all of those you get 20 at the end okay so that's sort of the idea and the bounds are 5,000 so not too big so the bounds are 5,000 so not too big so the bounds are 5,000 so not too big so should be doable now how do we tackle this well the main thing to think about here is that this is actually sort of can be done recursively because let's say um when you are at for example if n equal to 3 and you start here you get to six you get to four now you use two out of that three so you have one more jump so now you do six which you can only do like this okay or maybe you could do like this okay six you could go to one you could go to seven or you could go to zero like this back to zero okay and so for six so basically that means when you get to six now you are at six with the jumps one so you can see there are sub problems basically that's what I'm trying to say now what is the state of a sub problems of a sub problem here well first the current Square you are at but also how many jumps you have so the remaining jumps okay and for let's say n equal to 3 um let's say we start first at zero we have two remaining jumps okay and so we go to six so when we go to Six now we have we are at cell six we have one remaining jump we go to from six we can go to one and we have zero remaining jumps and so what's the overall number here for this 0 61 okay and you do the same thing for other numbers so you then you start from one and you try all the possibilities of course zero um starting from zero you have another possibility which is to go to four right so you can go to four and then you have one remaining jump okay so this is clearly is a dynamic programming recursive solution um basically we just our state here is going to be this okay and for each um we know for each number we know the valid numbers it can go to that's the key inside here is for each number you can only go to specific places so for example for zero you can only go to six and four for one you can only go to six or eight sorry to six like this or to eight and so let's just have a map with this so let's have a map uh let me just copy it over that says for each number what are the valids places you can go to and now when we are let's say let's call this DP then for each number we just need to get the next n squares we can go to B basically let's call this jumps valid jumps okay then we can just check the valid jumps for that current square and go to those and of course from that next one we need to decrement the remaining jumps by one right because we just utilize one and that's pretty much it we can of course cash because there will be repetitive States because for example six you can get to it from zero you can also get to it from one so we don't need to calculate it multiple times so we can just cach um our DP here okay um the other thing um is what is our base case well base case should be if there are no more remaining jumps right we are done and when we don't have any remaining jumps that's one way we found a way to a valid way to get to uh to get to um a number of length n so we can just return one and the result here needs to add up all the different ways right and that's what we return at the end of course we will need to do modulo but um that's the idea here now the next thing to think about is we can start on any numeric cells so this one needs to be called the start Point need to be zero with two remaining jumps one with two remaining jumps two with two remaining jumps three with two so basically from 0 to 9 we need to try all of them as a starting point so that's something we need to take care of in the code but that's the core idea so let's just implement it here um so what do we need to Define our function so we need current square and then remaining jumps let's just copy over what we just did um like this and we need to Cache so this needs to be a cache here and we need to Define our valid Chumps map so this is going to be like this you could also use an array because the index is um because the values here are consecutive you could use um an array if you want to um so we have our valid jumps array and then here we said we need to try every number as a starting point so start let's call it in the range of we need 0 to 9 so we can just do range of 10 so that's going to be DP of that start Point remaining jumps are just n minus one because we already utilized one by placing the number in the start position now what do we need to get all the different ways so we need to add up each one of these and then we need to return that okay let's call this ways just so that it's clear same thing here and then we need to Define our mod so our mod that we need to do we need to mod by on for each addition so it's going to be 10 the^ of 9 plus going to be 10 the^ of 9 plus going to be 10 the^ of 9 plus 7even um and then we can just here this is going to be WS plus and we need to apply modulo same thing here we need to apply modulo like this okay um and that pretty much is it um so let's run it and make sure it passes um looks good let's submit and that gets accepted okay um yeah so that's pretty much it um the key idea is to figure out that you can actually just hard code the this possible state for each number and then from there you could do a recursive dynamic programming solution um yeah so that's pretty much it if you uh need one-onone coaching it if you uh need one-onone coaching it if you uh need one-onone coaching feel free to reach sh out uh to me on um super Pier um yeah feel free to reach out to me on super Pier if you need any help thanks for watching and see you on the next one bye
Knight Dialer
orderly-queue
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell). Given an integer `n`, return how many distinct phone numbers of length `n` we can dial. You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps. As the answer may be very large, **return the answer modulo** `109 + 7`. **Example 1:** **Input:** n = 1 **Output:** 10 **Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient. **Example 2:** **Input:** n = 2 **Output:** 20 **Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\] **Example 3:** **Input:** n = 3131 **Output:** 136006598 **Explanation:** Please take care of the mod. **Constraints:** * `1 <= n <= 5000`
null
Math,String,Sorting
Hard
null
1,512
so this problem is leak code id 1512 number of good pairs so given an array of integers nums a pair i and j is called good if nums at i is equal to nums at j and i is less than j return the number of good pairs so this problem is one of the best problems to explain time complexity because intuitively a new programmer might think okay i'm just going to get all the pairs check if the numbers are equal and check if i is less than j and if so i'm just going to increment you know some count and that's fine it works but it's not good because it's n squared it's for every i we have to go through every other number so that would be n squared and there is a linear solution for this and we're going to go over that linear solution instead the best interview solution that i can think of basically so what we first want to do is we want to create a hash map and this is going to be of type integer so it's going to map an integer to an integer we're going to call this map and we're going to say new hash map and then we also want to have a count which is going to be and then i'll actually call this res to make it more clear that's going to be the number of good pairs the result basically so i'll explain why we need a map but it just works for this um it's like twosome which is another problem i'll go over where you can optimize it with a map it's very similar so basically the idea here is we want to go through each numb because we're going to have to do that regardless so if we go through each num so what are we looking for here so we're looking for pairs that have the same number and we're looking for the i less than j so basically the number must come after its pair so because we're looping through nums in this way every number we access is greater than the index is greater than the last number we've seen so this condition is taken care of by default just the way that we are doing this and basically we want to see um how many numbers do we have that equal this num so this is taking care of this nums i equals nums j case so we're going to search our map and how many numbers do we have of this num and basically how we do that is we're just going to check um if map dot contains key num so have we seen this number before good how many times have we seen it so we're going to do map dot get knob and this probably makes no sense because it's just like an empty hash map so at the end here we're going to actually go um put num map dot get or default um num zero plus one so basically what's going on here um we're incrementing the count of this num and why we do it this way is this getter default is because this num might not exist yet so if it doesn't uh we're going to do 0. if it does exist we're going to get the current count and then whatever goes on here we're just gonna add another one to it so basically we're going through the nums we're checking if this number already exists have we seen it can this make pairs is what we're asking and if so how many pairs can it make and then we just increment this we do this after we increment it because we don't want to count the current number as a pair because um moving on to this test case to explain this further so if we have this and we have one and we put it in the map to put two in the map put through the map then we hit this one um there'll be one in the map so that makes one pair so this one and one is a pair it wouldn't be two pairs it's just one pair so that's kind of why we do all that and let's go ahead and run this and we'll see that we get accepted and let's go ahead and submit it we'll see we get 100 run time so pretty straightforward uh this is an o n solution it uses o n space o n time uh because we have to go through every num and we have to keep a map that stores the num so yeah i hope this helped tried to make it as clear as possible pretty straightforward thank you for watching i appreciate it as always
Number of Good Pairs
design-underground-system
Given an array of integers `nums`, return _the number of **good pairs**_. A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`. **Example 1:** **Input:** nums = \[1,2,3,1,1,3\] **Output:** 4 **Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. **Example 2:** **Input:** nums = \[1,1,1,1\] **Output:** 6 **Explanation:** Each pair in the array are _good_. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
Hash Table,String,Design
Medium
2285
332
in this problem we have to reconstruct itinerary from a given list of flights between different cities so you will be given a list so let's say this city is a this city is b and this city is c so you may be given a list like uh ba then you will be given a list of all the edges so ba means flying from b to a and these all are the flights taken by a common person single person but you don't know which order so you have to construct a valid itinerary that means it's not possible that person first flew to c because there is no outgoing edge from c is just the end point or destination you cannot go anywhere from c so this cannot be the first flight so first maybe either b to a or a to b but if the first flight is b to a then it comes to a then either it takes c or b in both cases or one of the other flights will be missing you have to cover all the edges all are valid flights taken by a person so the valid path would be here go from a to b so the person was initially at a then went to b then came back to a using this line so this is the one two and three then back to a to b to a and then finally c so this would be the valid for this one in this case we had just one valid path but in some problems there can be multiple valid paths in that case we will return that value which is lexicographically occurring earlier and you are also given that the source is always a city called jfk so these are the airport codes in three digits so you have to start from jfk only this is the starting point so let's see how we will solve it clearly it's a graph problem and we are given a list of edges so this is just one example so these are the different flights taken by a person and this is a valid output so first step is to build the graph so we will represent it in adjacency list form so there is a flight from jfk to sfo so jfk to sfo there is one flight taken by this person then jfk 2 atl so this is another flight this we have done then sfo to atl so there is another flight like this then atl to jfk so there is another flight like this and then atl to sfo so we have constructed all the edges now let's see the adjacency list of each node so these are the nodes in jfk sfo and atl so jf sorry it's in jfk then we have atl and then we have sfo so from jfk there are two outgoing edges sfo and atl but we have to first try to traverse lexicographically earlier so we will keep them sorted atl first and sfo next in atl there is two outgoing edges jfk and sfo so jfk and sfo and in sfo there is just one outgoing edge which is atl and we have to always start from jfk in all the problems so this will always be one of the airports in the input so we are starting dfs from here only thing is that instead of normal dfs in normal dfs we if we reach a vertex we consider it wasted and we don't visit it twice so if we came from some vertex to some other vertex then some other vertex and there is an edge like this so once we reach here we don't take this edge since this is going to a vertex which is already wasted but in this case the only difference is that we will not mark it as visited instead we will come back here since there may be more outgoing flights so here the notion of wasted has changed we will not mark it as wasted but instead to ensure that so if we don't mark it as wasted what's the guarantee that we will not come back again since we take this edge again and reach here and now we will look at its neighbors so this will also be a neighbor so we may again come here so in order to get rid of that once we move from this to this we remove this edge so person has taken the flight so there is no point in taking it again although the person may have taken this flight from a to b multiple times then we will have multiple edges like this so first so this b will be occurring multiple times in the adjacency list of a so every time we reach b we delete one edge so that we don't repeat it like in this case so this way we are keeping track of uh avoiding taking one edge multiple times so we will trav take each edge once so here the notion of which state is not there we have to take each edge once and once we take an edge traversion is that is we come from this to this there is no need for this we have listed this edge so here the notion of which state is not for nodes but for edges so we can mark that wasted by just deleting it so you come here delete it so let's begin how we will do that so we will modify our dfs approach here so let's start from jfk so we will start from here and then we go to atl since it's first in the adjacency list since these are sorted and here instead of labels from 0 to n we have string values so we cannot use some fixed size vector which we know beforehand but instead we will use a map where the key will be this airport code so a map of a string and the second is a list or a set and we will keep this sorted so we can use set in c plus set uses red black trees internally so these will be sorted we are not using unordered set and in java we can use a priority queue or we can use a tree set or tree map where we keep track of this string and also the count how many times it has occurred or we can use simply priority q that will sort it based on uh alphabetical order of strings so uh we come to jfk we are here then so we called dfs of jfk then we look at its neighbors so first it will be atl so we will come to atl or we will call dfs atl and then this edge we have taken so let us delete this or mark this in blue so assume that this edge does not exist now we have come through this edge so in actual code we will also remove this so this atl will go away from this adjacency list so we pick the first neighbor and they'll also delete it from the list so now this jfk will have just one value and here again we will call dfs and at atl we have jfk and sfo so which one we will take alphabetic order so it will call dfs of jfk and get rid of this and we come here and jfk again look at its other neighbors that is it will pick the first one in the list and now there is only one so it will call dfs on sfo and it takes this edge and we remove it now we are at sfo so we go to sfo and see what is the first neighbor which is atl so it will come here it will call dfs on atl and we get rid of this then we come to atl we see what is the neighbor so only sfo is remaining so we will take this edge go to sfo and delete it so you can see dfs getting called for same node multiple times and here we are considering edges as vested now we come back to sfo and we look at its neighbors there are no neighbors so that means we are done with this so when we are done with this we insert it into a stack so let's write the code first then we will run through complete that example so uh create itinerary and we are given as list here so first adjacency list this will be a map where key will be the airport code or a string and this will be a set or rather multi-set since set or rather multi-set since set or rather multi-set since there can be multiple edges like this multiple flights from a to b in the same direction as well so build the adjacency list based on the edge list that is given to us just like we built it here manually so jfk sfo means in jfk insert sfo in jfk insert atl in sfo insert atl and so on this way we will build this adjacency list this is the first step and once we have built this we will start doing dfs and we have to do dfs from a particular airport which is jfk this is always the starting node and in dfs function if ah so till we have some node in this adjacency list of s a d j of s is not empty then what we do we pick adjs dot front that is the first neighbor and we do dfs on this and finally this when this becomes empty that means there is no way to go from this node and when this will become empty so whenever we take an edge we delete it and we delete this once from this its neighbors list so finally it will become empty when we have taken all the outgoing edges so when this becomes empty we will insert this s to the stack push s and finally we will take one element at a time from the top and print it or return in the result so let's complete this example so we had completed at sfo so we had inserted sfo there then this call of atl load terminate so this call terminates here so atl is printed inserted into the stack then this terminates back to sfo and this call terminates here so jfk will be inserted and this call again terminates here so atl will be inserted and this call terminates here so jfk will be inserted so from where we have started that will be the final node in the stack that is at the top of the stack so let's write the path it simply keep popping one element at a time so jfk is popped then we go to a till then we go to jfk then we go to sfo then atl and finally sfo and let's match if it matches our answer so jfk atl jfk sfo then atl sfo so this is the this is a valid path there can be other solution as well from jfk we can go to sfo and from sfo to atl and then again jfk and then atl and then sfo that will also work but we will take this which ever is lexico graphically first so this one will be the correct answer here let us take one more example let us say we have j f k and then we have let us say x y z and back here and then y x z like this so again we will start from jfk so dfs of jfk it calls it will take this path since this is smaller x so it takes this path so it calls dfs x yg and then this takes this path and calls dfs of jfk and this calls yxe and now this one has no other neighbor so this vertex is done so this dfs call terminates and we put it into the stack that is y x z then this terminates here jfk then xyg and jfk so what is the order jfk xyz so jfk we are first here then we go to xyz then again jfk so this is the second flight and then finally y x g or third flight so this way we have to uh code this thing so let's code it in c plus java and python so this is the same example i had taken this second example since this was slightly generic so this is our adjacency list here it's a map and we will take multi-set instead of and we will take multi-set instead of and we will take multi-set instead of set because we can have edges from a to b multiple times so we have to build this so simply adj uh t will hold two values so in t0 insert t1 and that's it this will build the adjacency list then let's create this result and then we will call dfs on jfk let's make it private and it needs this adjacency list we can also make it member of this class or we can pass it by reference and it also needs this result where it will populate the values so while this is not empty then we will pick the front and once we have our traverse or outgoing edges we will insert it into the result so instead of a stack we are we will directly push it into our result but we will be we can push in the beginning or end if we push in the beginning we don't need to do anything we can simply return that result but pushing in the beginning is very costly in this vector everything needs to be shifted so overall if we insert n items it will take n square times first time no shift second time one shift third time two sips so one plus two plus three all the way up to n square so it's better to append in the end and finally we will reverse that so that will be overall order n or you can push into a temporary stack and then finally pop one by one and keep inserting into the result both are same things so here we will reverse it so let's submit and the solution is accepted and it's right here around 78 percent of the submissions now let's do this in java so in java uh you can use there is no multiset so either we can have a tree set and also tree map and where we will have string and also a count so if we have multiple times we will increment the count and while we want to remove we will decrement the count and when count becomes zero uh either we remove it or we devise our code in such a way that its count is more than zero so it's better to use priority queue here that would be much simpler so let's first copy dfs so key of the map remains same string and here instead of multi-q we will have and here instead of multi-q we will have and here instead of multi-q we will have priority queue priority q u e here we need to check if it's absent then we need to create a new priority queue for corresponding to that node when we are inserting a neighbor to the first time so adj dot put if absent uh this is the first one is the source that will be the key for this adjacency list since we are adding it for the first time and new so t zero means uh so adjacency list is built and our result is list of a string so here we cannot directly check like this if this is absent then this will throw an error so let's save it string pq not empty here it's a linked list so we can directly add in the beginning in the c process we had not added in the beginning since that was costly for vectors so here we will not need this reverse and the java solution is also accepted and we are right here around 100 mark finally we will do it in python 3. and here we will sort the tickets so that's why whenever we are creating our adjacency list already we will add uh the one which comes early in lexicographically first so let's sort it beforehand and we will sort based on second thing uh if there is an edge from u to v we will sort based on v because that is what we are adding as a neighbor of the first if you has already been inserted a key has already been created corresponding to you then we will simply append it if not then we will create it and then add a value there you and we start dfs from jfk and here also we are appending in the end and we need to reverse it line 16. first neighbor and the python code is also accepted
Reconstruct Itinerary
reconstruct-itinerary
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. * For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. **Example 1:** **Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\] **Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\] **Example 2:** **Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\] **Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\] **Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order. **Constraints:** * `1 <= tickets.length <= 300` * `tickets[i].length == 2` * `fromi.length == 3` * `toi.length == 3` * `fromi` and `toi` consist of uppercase English letters. * `fromi != toi`
null
Depth-First Search,Graph,Eulerian Circuit
Hard
2051,2201
1,914
Ki Rupa Is This Video Baikunthpur Discuss About This Question In The East Coast Celebrity Speaker Advocate In Great Souls Scooter Question Was So He Jehovah's Rules Against Matrix Where Women Are Both Very Fierce And Forgive And Jerk A Consistent Amazon Nutritious Several Years Were Now Show Me the picture image where each other is only where she can see this particular bhi color is amla de dega phone liya m.a. this particular bhi color is amla de dega phone liya m.a. this particular bhi color is amla de dega phone liya m.a. Second year Ishwar Singh so that rotation to get metro system so that chakli rotating middle player of the matrix will sleep situation security particular dear of the matrix so isi aggravating this luli a that show is love rotating recipe advocated counterclockwise direction is therefore today's inquiry and over and tips For the spelling of changes so soon 10851 so rotating 10 toughest welcome to 10 questions page control this question will come to this position for them to follow were some simple remedies prescription disposition list Muslim Sudhir WhatsApp questions friend this grade appointment um one beer Can upgrade and see how to return final spread which is rotation five units in the water cooperation so let's see how they can be updated on which situation metric app should perform according to were ritual direction metrics and offer hussain's hai to is 232 compromise retention Seen Scientific Process One Will Move One End To This Post To Facebook Discussion Will Issue This NRHM Dishum Bittu 12321 56001 Yesterday Morning Previous How They Can Oppose Solution Is That You Can Think And This Particular Layer That They Are So This Is Right This Thing If edit suggestion directly safe from this vansha was continued in this session and written all office numbers in a very active 150 over 140 now converted second husband took these dark gold it 1008 all things this suicide note to corporation chicken leg piece Cut This One Films Police Facebook Did Acidity Test Will Appear For Next Editing Regional One Products Listen This Particular 15 Day To-Do List Straight Define Listen This Particular 15 Day To-Do List Straight Define Listen This Particular 15 Day To-Do List Straight Define Presidential Africa And Convert Your In Bill Gates Secondary In This Number At Or C21 Phase Senior Officer Rotation Of This Stupid Saath Final Hari Mirchi Is Form 580 Activists Have Every Right To You Made The Fighter 134 On You Is This Concept 100 ODI Cricketers This Particular Morning Will Put Back Side District Member Is Feeder 34 Rotation Is Cheesy So Ultimately What Means That Divided Into Three Sub Problems Create A Quitting Shayari Sacrifice Rotating Diary-2 That A Promise Cutting Is Hair Pack To Retail Pack To 10 Particular Friend Sulta Services Wicket This So That This Time Play List Till Office Of History And See How It Works That You Sabko This Last Patience To Those on time day suffer from it first time Champcash also 376 length of address kids saugandh skin who is the lunch this number Russian phone number call extends support number of wealth plus am so am naqsh loot you whenever MS Word - two plus and minus two you whenever MS Word - two plus and minus two you whenever MS Word - two plus and minus two * Plus And Minus Two Days Later He Got This * Plus And Minus Two Days Later He Got This * Plus And Minus Two Days Later He Got This Fact And Every Year 98100 That This Seven For This Position And Were Going In This Direction Shooting's Validity Date Decide Swift 20 This 1575 Similarly Practical Dance Acting Forex Sweater Doing Well In Preventing Extend's Setting The Value From the great red spot in greater noida address and click on subscribe rss service benefit welcome of this particular look so wick but this hadith number 468 feel that in the ear but not so x minus two x back to difficult thing and white picture previous column That Access Vivo's Election 70 Go Back To Here Single Face Lifting To Times One Majority Ko Subscribe Now To Us Among Us Asli Ruke The Bike Is Us War Festival School Na Yes Beg Sudhir Oppressed Sample Sharifa Rotation Is Given Key So What We Do Diya Is seat is roti yes ki vestige to date use what are the values ​​of this day the and skimming values ​​of this day the and skimming values ​​of this day the and skimming person mode song in this that this is the front what I am going to your help shyam limit for little champs is what is good that everything into The Half 3310 I Position Will Behind A Plus Point Is Suicide Plus Result Plus K With I Plus Number 124 Everything Is The Name Of The Committee Member Final Year To All The Politics Of Bachte And Specific Advocate Sunil Sihag Medical Shop You Mita Since Creating A Very Rare Coins Switch Off These Elements of This Beneficial Survey Team of Things Will Do Justin Bieber Doing This You Will Not My Tab Value Do This Book This Everything Else Will Be Amazed by Shaving The Team That Stuff Scientists Develop This Later Based Medical ft s places wich was initially fruit 24 hotspot of intent 2003 one hair fairer leave one and order and share subscribe tappa liye vacancy jitna roti the pie cheese isko chhut senior division far hai aur is particular liya main course certificate par cigarette and previous a bike Shamshuddin 10 Pickup Set Clear Converted Into A Single Every Settings Single Leg Piece Needle Rotator Sakta Are And Pushed Back Side Tak Tweet 180 Rishta Khoon And Submitted A Kya Hai So Ise Soon This Is What Is Active 800 i10 Tulsi To Fateh Jhalak Hi Bata Give number of columns of which the volume to retail position 3000 Android 2.2 Yes and Changing Weather 3000 Android 2.2 Yes and Changing Weather 3000 Android 2.2 Yes and Changing Weather MP3 1000 Half points will continue Hath Surya First what happens if voted To is with a unique position Slip 600 Kamal ji thanks Mamu Twist and turn layer Pickup deep famous battery saver mode temple strong supporter of is located please do you do that touch ghrit and that this green of clans wrestling wave where you want to rotate pie that from this group this 281 home tips and architecture of the pulp From the point of view of this back portion Protein Vitamin C 12123 subscribe to The Channel that if taken fight you office length of the sense of the Voice of Nation - New length of the sense of the Voice of Nation - New length of the sense of the Voice of Nation - New Model subscribe to the Page if you liked The Video then subscribe to the switch off यहान पर अंब्रादरी कन्सीव सौहार्द इस वीर यहान पर अंब्रादरी कन्सीव सौहार्द इस वीर यहान पर अंब्रादरी कन्सीव सौहार्द इस वीर वे क्लिए छीज पे बासिक माथ्स 10th है क्या आप जासी आर तार्फ टीम इस हैप्टी विशेष टी बी टक्स उप इंडियाटली कैसी तारन टीम समोकिंग क्या आप जासी आर तार्फ टीम इस हैप्टी विशेष टी बी टक्स उप इंडियाटली कैसी तारन टीम समोकिंग Secession Pass Jhal Not Such Inside Serving Rice Distic In Increase Search Multiple Of Restoration Dena Can Ofton Included In This Technique President General Secretary Sorbets Obscene Come Close To Bread And This Contestants Problem Thank You
Cyclically Rotating a Grid
find-the-subtasks-that-did-not-execute
You are given an `m x n` integer matrix `grid`​​​, where `m` and `n` are both **even** integers, and an integer `k`. The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating **each layer** in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the **counter-clockwise** direction. An example rotation is shown below: Return _the matrix after applying_ `k` _cyclic rotations to it_. **Example 1:** **Input:** grid = \[\[40,10\],\[30,20\]\], k = 1 **Output:** \[\[10,20\],\[40,30\]\] **Explanation:** The figures above represent the grid at every state. **Example 2:** **Input:** grid = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\],\[13,14,15,16\]\], k = 2 **Output:** \[\[3,4,8,12\],\[2,11,10,16\],\[1,7,6,15\],\[5,9,13,14\]\] **Explanation:** The figures above represent the grid at every state. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `2 <= m, n <= 50` * Both `m` and `n` are **even** integers. * `1 <= grid[i][j] <= 5000` * `1 <= k <= 109`
null
Database
Hard
null
650
Show More MP3 Video Song Hi Guys Anurag Side So We're Back General Questions 10 Minutes Call to Keyboard So what to say in it He is saying Initials Otherwise Keyboard Only One Character S President A Keyboard A Notepad Surya Went On That One Character Presented Okay You can perform two operations from another notepad. You can perform two operations on the notepad. The first is copy all. You can copy all the characters present in a notepad. You can copy all the characters present on the notepad. Okay, the second is paste. If you have copied it, then it is okay, then by asking the second question, you can paste till the characters, thoughts, copied last time, okay, he is saying that the beginning is present, so I have to tell you that the governor number and one number and given. You need so many, you have to get exact panasonic1, okay, so if we look at the situation, it is something like this is a notepad, okay, this is a notepad, so I have given it here, you can get two operations done, well. The operation has been done by copying it, look at one, the other operation has been done, copy the copy of paste and copy and this will mean that as many as this is from late here in which area there are four, so if you copy then it means do not do this. You can copy three of them, you have taken 21 off, you will read all four of them to copy this, velvet is four of four, these are the copies, this is oil, but it is copy and this is the meaning, so now what is he asking you to give you a single initially So I told you how to take NS, how many minimum operations have I done, how many minimum operations can I do for copy and paste, how many minutes can you make, it's ok from late, now if you want to see, let's remove all this. A note has been made to explain what's in it. In Let's Typing, I have given you an egg in typing. Okay, so I told you that in equal to zero, tell me that even a single adv1 exam is becoming possible. Okay, so how is the test going to start? If we look at it then it is there or Anil Bindal &amp; 1210 An Inquest is there or Anil Bindal &amp; 1210 An Inquest is there or Anil Bindal &amp; 1210 An Inquest zero is possible because one is already available then if we see that if their value becomes my one then it is that if I make only one then one at least. If you are already pregnant, then I make a small table here, how is the table in between these and the main steps or in the middle of the environment step, if I make a table then it will look something like this, ok, this is vegetable. If you have become a, then stable, if you have filled it, then if it is my NGO, then it is possible in these steps, take it, believe it is infinite, give is possible in it, you remember, you can delete it already, now his mobile number is one, so I Don't do anything, one is already available, so I am looking for one step further, it is zero, okay, then I say there is two quests, two have to be made, I have a way to make two of you, I will open one at a time, okay Then I will make space here, so how many steps are taken to make one copy? Now keep in mind that copy is a corporation and paste is also another operation, so it is one plus one two. Copy paste is not one operation, it is two operations. So if their value is my two, then I have returned it to How to. Okay, then what am I saying that if you see, there will be no other way to make three each, to make me the top 3. You have copied it and one. The operation is done, then you paste it, okay, wash, the operations are done, plus one, then you will have to present it one more time to make it free, three operations have been done, how many free steps do I need to make it free, there is a little interest in voting. For interesting, see that now you have to make four of these from the left, you have only one given for typing, so what will happen, we will make it in two ways, see from the shop, one is that you have copied this one, okay, so one operation. Is it ours or we have presented it three times, after selling it three times, two or three operations, that is, like OnePlus 3, it is costing me four for four, basically four, what is the other way to make it, I have got it since late. Okay, I will not do it, I will open the settings, make a copy of this one and then I have done it, so this is done, how many have I used so far, OnePlus One Two seems to be in one copy and on One, it has A, now what will I do, then I can copy it from, it is completely fine, these are the two, I have copied them, I have applied operation on one of them, bar operation offer has been presented to both of them, so it is visible and one step, so it takes time, the chart is applied only then. It looks similar but the method of operation is different. In this we brush it 1193 times and what we do is make it 12 times and then do the face. Okay, so right now it looks like it is four. Then let us give five but that. If I have to make five, then five will have to be taken from something similar, so how do I take an example so that you can understand things in a better way, then I take nine from late, I do n't know why I am typing but five is right now We will see what will come, should I take it now or is there a line that if I make 9:00 then how that if I make 9:00 then how that if I make 9:00 then how can I make that, then if I make it at nine then you will understand what approach should be taken, till now it is normal. Everything is going on, now look carefully, okay, here it is written that what I tell you to do is to make it in nine, so one of the most travel way is to copy it, okay, the copy will cost one per hour, then present it eight times, okay. So 8 this oregano will be applied on the side and then the tilak of the total will be applied. In this way, there is at least one way to make it. Kevin 9 put the cost and keep in mind that if you want to make any N number then you have to make it. The maximum cost will be the maximum cost, it is okay, we cannot exceed this, so if we make a hunter number, it will never cost them more, if we extend this then what can be the other way? He said that he wrote, okay, one copy of this. You have done so much pressure, you have got one friend to pet you, so the sum is 12. Okay, now how many operations are OnePlus One. Now see, if I paste these two any number of times, I can never make a Northern, why because new models, you are sometimes my zero. What it means is to say that this number of S should always be divided into our goal, only then we can present it that many times. How to clear this thing? Okay, so you are clear, two chords have been placed, I have added one more. If you press one bar, how many times will you get the sequence of the team, now these are the three, if I paste these three one more time, then how to go on foot, how much will it cost to make it eggless, then I got stuck one more time. Okay, here n how much cost was incurred, the total status should be 1234 552, our work is done, earlier our work was being done in non, see, so basically what do I have to do in this question, what will I do in this question, like this, I will start from the van. I will start filling my form that I will make it, how much will it cost, I will make it, that will work, if I put three, how much will it cost, if I call, how much is it, then how much will it cost, then find out the answer for six 600 flour, so what will I do now that this is my nine and How many numbers can this mark be divided into completely, before that I will check it. Okay, so how will it be the ninth hottest? Click on the like button. Here you are nine two, the second one is three two three and then 129. Okay so note my I have to make it does n't matter, I will see for you what is the cost of making it for free, if there is compulsion, tell me to make this situation, these are the three, what is the cost of making them, then I will include in that cost, the method of making it, the situation is fine. So what will I do with this cost, how many times can I paste it to make it nine, I will see that these are three A's, then I will press them twice, once again if it is my own, it will not be made, then how will it come out, what should I do, there will be a knot in it. Divided by three, it's okay, so once I have already kept the paste, how much should it cost? 333, so let me sell it two-three times, I have to press it two times sell it two-three times, I have to press it two times sell it two-three times, I have to press it two times because it is already there once, so I will say okay. Just paste it a couple of times and copy it once. When you copy it will cost you, so it will be effective. Look at it once again, it is not okay, how have I been? Nine. If I keep making it from three then it is okay then how many times will I have to present it through and to make nine I will have to pass that free time but once it is already available I am copying at this time ok so basically I will have to present it from two time Will have to do but copy it AB Corporation Atul two plus one is okay so this is my work which was already done Pistol Advisor If copied then basically 913 means it will not take three operations for me, okay what do I do it will take three operations A nine Let's look once again at the intention of making one, how much money did it cost to make Than A, okay, then if it cost like this, then I copied it, so four operations were done, okay, and I presented it twice like this, how much did it cost? Meanwhile Galis, six operations have been done and Shiksha will come here, okay, six operations have been done, I had written it wrong, at one time you told me this number, if that flat gets broken in time, then I will see that at which- I will see that at which- I will see that at which- So what will I do, I will start looking at the multiples of one text, this is the 821 one, so I have to make it, okay, after that, maybe two, maybe f4, maybe f-18, two one. Maybe it's f4, maybe f-18, two one. Maybe it's f4, maybe f-18, two one. Maybe it's fine with multiples, so I will check which late I am making from 4K group. I don't know the cost of the add because I am making my answer once, from 12345 to eight. I know the answer to this first, if I make a group of this, then how much is this, then I can see that if this one is the Madonna of the whisker, then how much will it be, okay this one is two. If I want to make it using this, then what will be the answer? So for that, I have just found out from the human being that I have given one number and how many steps and it seems okay to me, so if we want to write in the court then see how we will write. So first of all see this end request one is fine if only one is made then nothing should be done return zero why do we have to do anything one is life imprisonment to make and one is already made ok then what will we see request If there are two, then brother, I will copy one each and present it to you friends. Now you will have to return to two, then what can I say, if I make a camera, I will name it as 'Previous' because of name it as 'Previous' because of name it as 'Previous' because of how many times it takes to make 'Previous'. You can tell me how many times it takes to make 'Previous'. You can tell me and Its size will be as much as you want to make and make. Okay, now fill it, one thing told me that the previous zero has no meaning, it is infinite, one, start, if I become one, make this. So there is zero cost, if I start with two or if I want to make this then its cost will be two. Now I will make a loop for the rest. Let's see how it will work. So I started the loop with three because I have to start filling it with 36 hours in advance. Answer: filling it with 36 hours in advance. Answer: filling it with 36 hours in advance. Answer: I know it, okay, I will do it. First of all, I will put it together that the TV is clear, I am the only one. What I mean to say is that if I make a number and then only the maximum can be done to make it then and. So my answer is, if it is better than this, then take it. Okay, so my answer is, if it is better than this, then take it. Like the net, if we cannot sleep, then to make nine, there is a line operation to make nine. There cannot be a number, there is no better answer than this. So I am saying, I understand that this thing is fixed, then what will be the previous five, I have agreed, then what should I do, I will take it, Jai Guru, I start with I want to, then it means to say, look, it is like ATM is eighty from light. If I want to make my number a multiple, then its smallest number will be 1622. What has happened, it will become * 21, What has happened, it will become * 21, What has happened, it will become * 21, then it will become into six. Sorry, I am writing here that a train will go to education, it will be okay, by doing this it will become very useful. If you multiply any number by train, it will be 1220, then the first one who is its multiple must be practicing this, the even number is 9 and you have taken some other number. So it was said seventh class 6, then it became 70 less than that, ok it means to say that we need a number to divide, so I am wondering from which will it start, now you will accept that we started from 8, then make the ad a matter with you and send it. If you give it, will it increase? If you consume it, then F-18 will come. If it is If you consume it, then F-18 will come. If it is If you consume it, then F-18 will come. If it is not there, then we will look further down and see if this 1622 is coming, will you find such words, then 512 is a multiple for three basic. Its fine. So I want to sons of unlawful How long will I do of wild a great many 1212 Okay okay as long as my country is greater than one 121 Now what is there to see here I want to see my here that means that if I am DJ Ek Object August 2018 What does it mean, what should I do after making notes18's ATM that the soil has taken the ticket till active on this occasion, so what I started doing, see, you are please check that while dividing not, write to the team by If he does ninth then C is in a hot mood right, that is, nine is basically one of its factors, after bursting, I will check add, do the same again, then check six, for which I will answer, okay, so what am I doing? I am here FIR Model Jaggu Secretary, DP Sharif Previous of I What will happen to me that I am Dormant Yadav, the answer given right now is there, if he is better and he is younger then let him be, otherwise what else do I have to do, what have we seen here. Now listen carefully, we had to make this difference nine, one is one, so I saw that if I press it twice in Delhi then it will be right, then if we need the cost of making three, then three will be our model, so I What will I do aa previous of j ok this cream all this place means how close to make the free co look plus i visor meanwhile sexual - oneplus one should be well sexual - oneplus one should be well sexual - oneplus one should be well why because so many times don't present me your body come times ne do Advisor - If you want to close it but you will have to copy it again, then Advisor - If you want to close it but you will have to copy it again, then Advisor - If you want to close it but you will have to copy it again, then it will be effective - 9 paise it will be effective - 9 paise it will be effective - 9 paise here, you will get cancer. Okay, so this is done, you have saved it in the environment and this - - I will done, you have saved it in the environment and this - - I will done, you have saved it in the environment and this - - I will do it, but I don't have to do anything, advocate. Give the returned DP of those who were kept in it, I will make it my warden at my end, I will try and see, there is no good OTP, its name is sorry, by the way, there is a question on DP, DPR is used in the definition, hence there is a little confusion. If yes, then you have to submit it and see, I am reading everything, if the answer is yes, then you are done with it, okay, now this one has got it, okay, this question has a catch in this question, well, now that may be an opportunity for you and now not. It is possible that if you do this much in the interview then your work will be done but it is late, okay, there are many ways to make the team, make 120, okay make two into nine, okay make 326 or else 1957 16231 Hello Saifina. * make 326 or else 1957 16231 Hello Saifina. * make 326 or else 1957 16231 Hello Saifina. * Make it or whatever text-21 we have to make, Make it or whatever text-21 we have to make, Make it or whatever text-21 we have to make, all these will be its what will be its murders, its factors will be there are ways to make the team, then you will observe all the numbers you get, you will see that always with the largesse factor. What will you do with the largest factor, if you multiply, blaster means editing, okay, then 13 back to Noida will start from Noida, basically multiple and if it is any other number, let's say it is 1000 by loot, then its tense. So let's start tension that we will see if we divide by 10:00 then it will not work, no, when we 10:00 then it will not work, no, when we 10:00 then it will not work, no, when we consume quietly, then seven into thin will be the main and answer to it, now how is it, that was basically observation, friend, nine for you too. By doing this, you will see whether 123 is 1297, 3237 or 921, then you will see that the one with 323 is the one who is always giving the answer, so we can directly save the complexity of the people, we will do this to save them from this. To protect it, if you immortals come into conflict, then basically unite them, then what is the benefit of this, unnecessary checking will be going on, we will not have to do that checking, so what I have done here is that if I am checking for one team so I will do CBI team will do 290 if I am dividing then Noida will be my answer only one cool ok so if we submit then it is taking 21 milliseconds and now we If you submit then it will be done in milliseconds, it is ok and 15159 percent Paas like from Java solution, this is a 3D question of this question, if it is an easy question then I would have understood it and if there is any don't then you can reduce it in the comment section below. Ho and you can ask on Instagram Tak Ram's handle is N U R A G Anurag COD Just okay so this is the handle of Takraar, now you can go and ask and if you have any question request then you can also put it in the comment on your Instagram. By the way please make this question so I will make it for that 10:00 bye for that 10:00 bye for that 10:00 bye take care a
2 Keys Keyboard
2-keys-keyboard
There is only one character `'A'` on the screen of a notepad. You can perform one of two operations on this notepad for each step: * Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). * Paste: You can paste the characters which are copied last time. Given an integer `n`, return _the minimum number of operations to get the character_ `'A'` _exactly_ `n` _times on the screen_. **Example 1:** **Input:** n = 3 **Output:** 3 **Explanation:** Initially, we have one character 'A'. In step 1, we use Copy All operation. In step 2, we use Paste operation to get 'AA'. In step 3, we use Paste operation to get 'AAA'. **Example 2:** **Input:** n = 1 **Output:** 0 **Constraints:** * `1 <= n <= 1000`
How many characters may be there in the clipboard at the last step if n = 3? n = 7? n = 10? n = 24?
Math,Dynamic Programming
Medium
651,1033
1,042
hey what's going on guys it's ilya bali here i recorded stuff on youtube chat description for all my information i do all liquid problems uh make sure you subscribe to the channel give me a big thumbs up to support it and this is called flower planted with no adjacent you have and gardens labeled one to n in each garden you want to plant one of four types of flowers bad at the position of i is equal to x y describes the existence of a bi-directional path from carbon x to bi-directional path from carbon x to bi-directional path from carbon x to carbon y also there is no garden that has more than three pad coming into or leaving it your task is to choose a flower type for each garden such that for any two gardens connected by path have different types of flowers return any such choice as an array answer or answer the position i is the type of flower planted in the i plus one garden the flower types are denoted one two three or four is guaranteed an answer exists uh well let's look at those examples we got n uh is three but one two three one return output one two three and is equal to four but one two three four output one two and is four but one two three four one three two four output one two three four well um n is greater than or equal to one and is less than or equal to 10 000. the size of those path is greater than or equal to 0 and is less than or equal to 20 000. no garden has four or more bats coming into orlando it's guaranteed an answer exists uh right to the bad we can create an array to type integer and return that array the end new integer length of the race equal to the number of gardens they said before return that answer we could use map we got integer the type for keys and set of the type integer for values we got a key value volume is associated with the specified key type integer this case it's called map nothing special new hash map the type integer key and set of type integer is the value um create a for loop and i is zero is less than the number of gardens i plus at each iteration we put i as key and new hash set the type integer as the value create another for loop uh we're gonna loop through those rows in path b pass map door at the positional one minus one then for a neighbor get e one minus one that at b at the position of zero minus one we have um undirected edges yeah and we create the for loop and i is equal to zero uh i is less than the number of gardens i plus uh the time complexity for this solution is uh big of 1.5 and uh 1.5 and uh 1.5 and uh where big o of you know n and big of past the time the space complexity is big off we go n um okay here at each iteration we will be creating an array it's called um types you could notice from the description of that problem that um this problem that we have for types we say the length of that array is equal to 5 because that's one based indexing yeah use five instead of four here uh j on map door get i and in the case when our enabler has not used uh the type yet we do nothing in the case when the neighbor has used the type uh we mark that type as used set up the value 2 1 um use you know types at the position of the answer the prediction of j one create another for loop into a is four j is greater than zero k minus um in the case when uh the type is not been used yet we can use that type we use that type so types the position of j is zero we got a bunch of zeros by default here types uh answer at the position of i is j that's it um let's run this code accepted good let's submit success well you can imagine um a graph and let's look at this example this one we got pass one two three four and four uh after this loop we would have zero one two and three and sets right there here we are looking through those uh through those rows uh b at the position of zero one minus one e zero we add uh b at the position of one two minus one um so right here you can imagine an edge uh like you know zero or let's say one two right one two it's like zero and one yeah um so from the position of one we can get to two and then mob that get be at the position of one which is two minus one which is one we add let's set uh b at the position of zero one minus one zero so from this point from two we can get two one as well undirected edge and the same for this one three four you know three four the position of uh zero minus one we got two to uh four minus one three here like three to four uh 2 and 3 and then from you know 4 minus 1 3 2 uh 3 minus 1 2 to two from four we can get to three and from three we can get to four um that's it like and then we do those things already explained right yeah thank you guys for watching leave your comments below uh i wanna know what you think follow me on social medias follow me on instagram admin snapchat and i'll see you next time bye
Flower Planting With No Adjacent
minimum-cost-to-merge-stones
You have `n` gardens, labeled from `1` to `n`, and an array `paths` where `paths[i] = [xi, yi]` describes a bidirectional path between garden `xi` to garden `yi`. In each garden, you want to plant one of 4 types of flowers. All gardens have **at most 3** paths coming into or leaving it. Your task is to choose a flower type for each garden such that, for any two gardens connected by a path, they have different types of flowers. Return _**any** such a choice as an array_ `answer`_, where_ `answer[i]` _is the type of flower planted in the_ `(i+1)th` _garden. The flower types are denoted_ `1`_,_ `2`_,_ `3`_, or_ `4`_. It is guaranteed an answer exists._ **Example 1:** **Input:** n = 3, paths = \[\[1,2\],\[2,3\],\[3,1\]\] **Output:** \[1,2,3\] **Explanation:** Gardens 1 and 2 have different types. Gardens 2 and 3 have different types. Gardens 3 and 1 have different types. Hence, \[1,2,3\] is a valid answer. Other valid answers include \[1,2,4\], \[1,4,2\], and \[3,2,1\]. **Example 2:** **Input:** n = 4, paths = \[\[1,2\],\[3,4\]\] **Output:** \[1,2,1,2\] **Example 3:** **Input:** n = 4, paths = \[\[1,2\],\[2,3\],\[3,4\],\[4,1\],\[1,3\],\[2,4\]\] **Output:** \[1,2,3,4\] **Constraints:** * `1 <= n <= 104` * `0 <= paths.length <= 2 * 104` * `paths[i].length == 2` * `1 <= xi, yi <= n` * `xi != yi` * Every garden has **at most 3** paths coming into or leaving it.
null
Array,Dynamic Programming
Hard
312,1126
284
hello so this question is picking iterator so you have to design the iterator let's support the picking operation on the existing iterator in addition to the test next and then next operation so this is uh pretty straightforward for iterator uh implementation so uh what do I need to do is I need to uh incremental class and then there are three different methods and basically you just need to uh using the iterator uh something like this and then you put in the inch right you put an inch into the uh iterator class and let me say this is ID and you need to also have the next is what is the next value of the iterator next so which is uh I Theta next right the next should be what equal to this and then you just traversal and then this will be here right so uh let's just start coding so what I will do is what iterator and I also have an integer next so I will have to uh to find my ID which is iterator to iterator right so I'll basically just reassign and next I will say it go to default and then so uh once I set next to uh next to no I need to make sure that's my iterator integer ID has next so I'm going to just call hazmax if you do and then I'm going to assign my next so I'm actually Traverse uh Traverse my it and for this one has next I'm going to just say that's my next is no uh that's not equal to no or what I T that has next right so I basically can Traverse my uh area but I don't actually call over here this is because if you over here this is because if you over here this is because if you do then you probably will miss out the next function we want to override it and then for the pig right since you have next value but you are not actually moving your index so imagine you are at least index so I'm just uh join a box over here so you are here this is your current ID Index right and this is your next value right but you are not actually moving right so you need to uh just uh return the value of names for the kit right and then follow next you need to actually store the value so I'm going to say current equal to next then I will move my pointer to the next one right and then reassign my next to here if there's a value right so straightforward you know so this is going to be next and now I'm going to just stored in my current value to next right return the current for sure and then if it dot has net right you cannot just call if ID dot next because you need to make sure if I did the test next then you need to return something which is next equal to 80. if not languages I then just Define next to no so this is going to be pretty much a solution so yeah Summit alright so let's talk about the timing space this one for the time uh this is what although all of one right because you don't actually Traverse all of the value in the iterator you uh you assign a memory allocation and then for the space this is definitely all of them and representing the lineup later right now take it they pick it should be about all of one for timing space this one all of One Like You are not actually Traverse the whole entire area you just Traverse the next one right and this is all of one so follow quick notes this is pretty much a solution so uh subscribe if you like it and comment if you have any questions so I will see you next time bye
Peeking Iterator
peeking-iterator
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations. Implement the `PeekingIterator` class: * `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`. * `int next()` Returns the next element in the array and moves the pointer to the next element. * `boolean hasNext()` Returns `true` if there are still elements in the array. * `int peek()` Returns the next element in the array **without** moving the pointer. **Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions. **Example 1:** **Input** \[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 2, 2, 3, false\] **Explanation** PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\] peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\]. peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\]. peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\] peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\] peekingIterator.hasNext(); // return False **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 1000` * All the calls to `next` and `peek` are valid. * At most `1000` calls will be made to `next`, `hasNext`, and `peek`. **Follow up:** How would you extend your design to be generic and work with all types, not just integer?
Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code.
Array,Design,Iterator
Medium
173,251,281
548
okay so starting to so now I have three five six eight nine is the total sum here and then starting at 3 and a 3 that is 1 and this adds 2 3 4 6 and 7 and similarly God just let see if we construct this table 5 6 and this is 1 3 4 I still this table 2 &amp; 1 this is not 1 4 I still this table 2 &amp; 1 this is not 1 4 I still this table 2 &amp; 1 this is not 1 so this one so here's 3 so by doing this we have calculated the sums of all sub-arrays with an A so now sums of all sub-arrays with an A so now sums of all sub-arrays with an A so now I let's see if we can use this information to get the final result we want is for sub arrays that have the same sum so I think we can do this in okay so again this is gonna be another N squared skin so the skin square decathlete table and then let's try n squared skin so let's start at 1 let's look at 2 to know send me 3 4 &amp; 5 &amp; 7 so in this case we 3 4 &amp; 5 &amp; 7 so in this case we 3 4 &amp; 5 &amp; 7 so in this case we have 4 indexes but we could have looked at the sum of 2 &amp; 3 or this actually not sure if this actually give us because we need to take directly one 1 two 2 three 3 four 4 if they're not equal to any backtrack and take 5 or 6 or 7 so this is still in into the 4 eventually let me mmm how much time do I have left I have 18 minutes okay let me just strike two so again I solution like let's just try one compared to find these separate so let's okay so this is me and squirts cancel it take the very first element and then starting index to scan until you find something that's over the current sum and then you start at three and then this is over for four or five six okay so I think this is actually still eight and squared scan so it's on the N squared total in this case okay let me just count this and then we'll see if this passes okay so here so DP of zero is if written so at least let me think it's gonna be the start and the end index so okay I think we can just do D P of n okay so let's create the table first so we start at the let's say I'm for some difference is zero if less than n plus and then for all right there should be we start at the left equals zero and now the right is let's just eat DP left equals right okay so that's four into equals one plus three plus the name right plus okay so now we want to add a right plus DP left right minus 1 which we should have already done on the previous iteration so it's 2 DP left right cause this you just make sure this tables I'm just make sure this function is correct before move on that's two so just 18 okay so one DP so this is one three two three four five this does not look correct what's going on so one three four six seven nine tenth the first rows correct the second row two three five six eight nine so it's the very seems like the very last element oh he's not being let me just do a smaller test case here just so it's easier to think about my g1 so it went three four so okay so seems in the second row left is I didn't name these scribbles very well quick equals a row sorry she not sigh yo+ right he goes anybody she not sigh yo+ right he goes anybody she not sigh yo+ right he goes anybody cross the road okay so let me try the base case like going to okay so that works I just the second row is not okay so 1 plus 1 is less than 2 so this is row okay I see should be blue plus right so we're not increasing this quickly to 2 that's also right TP row-column plus one - okay I see TP row-column plus one - okay I see TP row-column plus one - okay I see little plus right here this is Rho plus right minus 1 3 4 2 3 2 1 ok now this looks correct let me try - one - one let me try - one - one let me try - one - one this one's we had two three eight nine six seven five one three four - three six seven five one three four - three six seven five one three four - three and one okay now this table is correct now let's try to derive the answer these nice table it's initialized to false now so we want to iterate no 8 that considers every possible prefix so again we start with left equals 0 less than that's plus and then let's do the end so for a less than and weight equals goes left right less than in great plus okay now the candidate this will generate every possible starting candidate for us so let's just say candidate equals DP left right okay so now for each of these we want to Ford scan our table and see how many total equal sub arrays of a cell and we can do this free to e as soon as we see one possible sub array we will take that answer it's always gonna be the best choice so let's do this in one scan private say this is find take a dpi ring so the starting index is gonna be the right plus one to start in and equal zero we want this to be at least three equals start J less than n j+ boss so yeah so we start at J and C seven minutes so we start at J you scan one pulls up J less than n + + + o so pulls up J less than n + + + o so pulls up J less than n + + + o so there's DP j + end holes so we need our there's DP j + end holes so we need our there's DP j + end holes so we need our target sum here and target this equals target down + + and then we want J target down + + and then we want J target down + + and then we want J equals end and I want to break out of this loop and then that's featured sound if he did it the start will be the rate plus 1 and then the candidate is the target true okay let's see if this runs it won't but well CPU right plus one candidate returned true signed 51 I found has to be at least three holy I kind of worked okay let's try another example here so let's say our target sum is 3 1 2 0 3 1 and then let's say or take the 1 so let's see if they add to 3 there's no false here that's a 3 2 sides 2 3 4 negative 1 a 3 maybe they don't consider like no they do zero okay I misread the question so we are trying to find I J and K such that if we take away these three numbers the four remaining sub arrays are equal so I did this question wrong okay how do I so I have three minutes left let's try to think about this real quick so like I think for that question let's just see if this solution works for like what I thought the question was should be false this is false so I mean at least I coded up this shitty function oh good job all right let me delete this is a lesson learned I can hope your father watches this and choice me fail so if I have three so instead I want to find three values where if we take them out for submarines or equals value in this case again we can do this naively we just take out try every combination of three indexes trying to think of how to do it better so again I think if we take the sum so for any if we know we have to take out three values only then let's then we know that the sum of these three values has to be up this array has to be a divisible by four right so after taking out three values the total sum of that means FGP Xian 3 Daly's the total sum has to be divisible by 4 so we could this could speed up the naive approach were like for any three indexes like if we take them out if we subtract them out from the Sun if we know it's not divisible by 4 then it is ok so looks like we've had out of time we did not I'll see we did not pass this question but I will now go ahead and actually try to solve this and without the mock contest okay so like now it's in the new format so unfortunately like this recording is not gonna work anymore but anyways thank you for watching I'll just end the recording here and I'll try to sell the question on my own
Split Array with Equal Sum
split-array-with-equal-sum
Given an integer array `nums` of length `n`, return `true` if there is a triplet `(i, j, k)` which satisfies the following conditions: * `0 < i, i + 1 < j, j + 1 < k < n - 1` * The sum of subarrays `(0, i - 1)`, `(i + 1, j - 1)`, `(j + 1, k - 1)` and `(k + 1, n - 1)` is equal. A subarray `(l, r)` represents a slice of the original array starting from the element indexed `l` to the element indexed `r`. **Example 1:** **Input:** nums = \[1,2,1,2,1,2,1\] **Output:** true **Explanation:** i = 1, j = 3, k = 5. sum(0, i - 1) = sum(0, 0) = 1 sum(i + 1, j - 1) = sum(2, 2) = 1 sum(j + 1, k - 1) = sum(4, 4) = 1 sum(k + 1, n - 1) = sum(6, 6) = 1 **Example 2:** **Input:** nums = \[1,2,1,2,1,2,1,2\] **Output:** false **Constraints:** * `n == nums.length` * `1 <= n <= 2000` * `-106 <= nums[i] <= 106`
null
Array,Prefix Sum
Hard
1678
387
he-hello there so got to quickly talk he-hello there so got to quickly talk he-hello there so got to quickly talk about today's recruiting challenge question it's called first a unique a character in the string and the question is as follows given a string we want to find the first non repeating character in it and return its index if there are no such character meaning every character has at least the more than one x then we should return active one so this question yes I think it's a sort of like a watered down version of 1429 first tunic number which is also our coding challenge question for last month's so I do have my own video about it if you interested you can check out a link there I also put our spin on it to support pop so the video is quite long yeah it's kind of interesting if you want to consider pop so definitely check out the video if you want are you interested in looking at that so just for that let's go back to this question so if we look at the string lead code we see that Karthik LT Co D the all appeared only once e is the only character that appear more than once so the question asks us to grab the rare first one that was no repetition so it's L so the index is zero so to solve this problem we can just do one scan through the string to cut up at the number of times each character appeared in the string and do a second round of check from left to right for each of the letters we encounter we check whether the letter has a frequency column one or not if it's one then the first one we find you know from left to right it's going to be the one that we want to return its location so that's a two linear path in the worst case and the space is going to be the hashmap which stores the in a number of times each character appeared so the size is equal to the vocabulary size that's the total number of you need the characters in a string so it's a it's actually quite optimal already if we want to do even slightly better we can utilize something like order to map order dictionary potentially coupled with a set or not we can do that either there are multiple solutions we can use a set to do deduplication or we can use the order dictionary which the values be a couple of number of times it appeared and the last locations we find it and just keep moving that whenever we update that key value pair we'll move it back to the linked list and of the linked list and we're fine so there are multiple ways to improve the first brute force solution to be strictly one pass the missus it the necessity is not as not very high so I'm just going to code up the hashmap frequency count and do a second scan to find it first and then code a set plus order dictionary solution that's the solution is pretty much essential to the 2d to the solution here we have a set and a dictionary but to support pop it won't be a little bit more difficult so again if you're interested you can check out my video yeah so just going to talk about this question the simple straightforward solution we're going to create a hash map a store the character to its frequency count let's call char frequency which is the just gonna contour on the string and then do a second scan from left to right we want to grab the location as well so if this character has a frequency count of exactly 1 we'll just return its location if we don't return anything while this for loop meaning whether for left or right we tested every character we still couldn't find one with the frequency comping 1 we return negative 1 so that's the code yeah so in terms of the solution this is definitely our easy level question so a little bit improvement can be that we repurpose this hash map use it to store the last location we see the character and it has to be ordered so the keys of sorted based on the time it's being inserted so onto the hood it's a hash map plus a linked list kind of data structure hybrid in there and we're gonna just assess to do deduplication so every time we see a character more than once we make sure that we remove it from this hash map so in the end we can just check on the key value seen here in the hash map those will be the characters with only one appearance in the string and this is ordered we can just grab the rare first one it's guaranteed to be the first non-repeating character industry so it's just they're just going to be a house branch based on whether we see this character or not just pizza the second time at least as a second time we see this character we will make sure that it's never in the hashmap anymore so we pop it off and else we will remember yeah this is the first time we see it and we want to remember its location so we can after this just a one pass we can you know a return statement here so if the hashmap is empty there is no character with exactly one time appearance we can return negative one otherwise we'll grab the rare first one yeah so this is pretty much the code it's a linear in time just the one pass strictly one pass through the string and the space it's proportional to the in the worst case is going to be to multiply by the character size the size of the vocabulary because both seeing and character location can take up until if everything is unique it's going to be you know to multiply two data structure each with number of unique character as the size so let's submit this one as well I do have an arrow so next I forgot a if statement it runs example yeah so it works here you are to solution one is to pass with strictly one data structure that's linear in size with the book I'll resize the second one the space can potentially double but the time can potentially be half so you got a trade-off there so half so you got a trade-off there so half so you got a trade-off there so that's the question for today
First Unique Character in a String
first-unique-character-in-a-string
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`. **Example 1:** **Input:** s = "leetcode" **Output:** 0 **Example 2:** **Input:** s = "loveleetcode" **Output:** 2 **Example 3:** **Input:** s = "aabb" **Output:** -1 **Constraints:** * `1 <= s.length <= 105` * `s` consists of only lowercase English letters.
null
Hash Table,String,Queue,Counting
Easy
451
458
Hello friends to Jhal Ajay, once again welcome all of you to your YouTube channel Teacher Thi, so in today's video we will list some very interesting questions of Purti Vriksha, so basically the questions are of mathematics category type and a little bit of Ko Minute Vriksha is also included. Have to pay money to this question 21 times and then let's see how it can be this year then dacoits executive work at a point to figure out which you have to contact then they will not unfair means to test to determine which this Point is E and then after that he has given some ways how we can fit the picks to get some tips and then give each one some time to sign The Pick Will Consume All Rituals But Sentence Real Admit 19 Time can try all the opposition and no one will take time but after consuming any but who, neither a single minute is this a factor or a parameter, so it has to be seen how much time will be spent after accepting any side. We will have to hold a long meeting of that last month i.e. i.e. i.e. how much we will have to wait for it to dry then that is the minister you may not find any other pics during this time to this time you can't do any more stupidity You want to say this terminus to divide is text debit the point but different appointment diner dash roy printer professional attitude and not the time to point let's see it that where look like suppose I have passed some but okay some three wickets From and exactly one butt, what is one of these exactly, a big problem, should one drink the confirmed chakli, one, even I do n't know that is the point, that's why I gave him some to drink, I bought some from the market, okay, did I grind it or did people make him drink it? And let's support everyone's key value is two, take two pieces, I am here, this is two, don't go to the diagram, just go to the conductor, so these are some people, this is I have to test this, which butt means I will ride it, so this is There will be a back side and after that there will be a test. It is very important here that you note that if there is Malviya page number one on any one, this is pin number two, then I will admit this paste and send one text at a time. Okay, one thing. And three, I will do this, why if I say that I am doing this and this from the pocket, I am doing this and this, okay, now it will weaken both of them, all this also, now even if this one dies, it becomes like that. Even if it is there, who will tell me which of these but I was poisoned because I have got him tested for both, now I too could be in this too, what will I have to do for him then I will have to do it again. From one more time you will have to call another one and see but kilometer topic long on adapter day match gas is any one butt poisoned or not then pick at that time you are not like that with a goat also you can get it consumed Two, if you make it consume two, then what will happen to us, advocate, when will we get this confirmation, which butter was we, so this is a little bit of a very important point here that we will make a page that even a bird will consume at a time, this is this. There is also a verse in this option, I am not denying that either this one, he has the options, he will do all three, only one at a time, then this or this, then the confirmation will come, why is this done? Now it comes to the point of operation and after applying 21 minutes to the sector, enter the minutes and 1 minute to test, ok, what is this thing, both of them are telling that it will pass the test in half an hour, I will give the pause to my customer in an hour. Even if I do it, I don't care about it, within half an hour and that's it, I have controlled this pest, now I came here and stood up, now I went into the room and for how many minutes can we do this, maximum, before 10 minutes, this is it. No, any melt will take 10 minutes, it will happen within 10 minutes only, if it happens in more, then spend 10 minutes in this observation period, if it all comes in the observation plate, then it means that if not only in this, then never. In this type, I have a little more of this, which takes 5 more minutes and what he was saying, I told that it will take any time and test it and if any customer of mine can weigh it in so many minutes, then I said that Mirwaiz and I believe in the thing which That in every trial, in every experiment, in every method, he never reads any topic, when a wanderer in any of the trials, if he does not die then what will matter, at what maximum will I perform the experiment, such as Suppose I did an experiment once, Ignored did not come, did not accept, second, what happened next, 15 minutes before my death were wasted, I invested in females and he did not even refuse, in the next time period also he will be wasted not only in Marathi but also in females. So how much will this 1615 go to, if I add a number time plus to 1615, then it should be equal to this, so I should really have it because above sixty minutes or above aerial minutes, I will never be able to perform the experiment anyway, so this thing is loosening it. It happens, by the way, I take it one more plane that next two will go to maximum equal to two, then this shows that the numbers and trials, the number experiments which will be mine, will be the waypoints that if brother it sticks with me, there is a meeting of the front. So the minimum is four, so I will be able to do this, the maximum is four, I will be able to make zero trail, I have not made this crazy journey at this place, so this was an observation here, now a little question, now it is a bad frame, now this should be understood after this type. Now this much is known that friend look maximum friends, 215 dowry phone means virus will go to this compound maximum now if I talk about travels then how many trains were there, we have come to know that travels will be Raipur Nak, ok this much is clear now one The thing is there is an extra oil, that will also be there will be one in it, in which there will be one from one side, so therefore we will save all the picks, in the total tribes page, next page, there will also be one oil in the plus, in which if there is one left, then investment time. We will have that butt noise, whether it is printed without any pack or not, it will tell us in the same way that we have a tab in which the points will be butt, it will definitely be hundred percent, so this point question will be the total number of trends, now let's talk. If I know how to get out of the landscape, if I get the numbers and the pick near me, then I know how many holidays and how many travels can be a part of the gas, on which I said, Shetty is behind this pick, now this Not Marathi, if this is the first trail, if you have made it in the back race, then the next person will also have to pass from behind, after this, all the people will have to go behind, how many things will Yogi speech give, he can take part in the trial, because of this he is total. The choice that was made, how much is it made of power, that it has become stars, that now if it has become stars, then I have also increased the speed, the power points, how much of the attacks have gone, you tell me, how much will it go, I said that it is more. Whatever travel award travels and goes to whatever number, all this should remain as much as the alarm set max loosening question number of but should remain as much as Birds Beerwa because if but SIM will not be left but it's In the end, if it becomes zero and goes negative, then nothing will happen, there is no benefit, so whatever is done atomic, the work will continue till October, then put a lot of cider cloves to open the lock P Shirdi strong also, leaving the last one, days should be added. People should have a divide lock, now whatever we seal here, we will do it, here we have sealed it, we will take the job, hence total 10 to 12 times, I must do it, if you want a little complicated, then now we accept it. First of all, what have we told you that the number of tiles, I said, take out how many total tracks will be by porn I have already said that he will send a value unnecessarily, so he will do it, so let's cover this also in the bracket, it was a mistake, but if I sleep, then it is not in favor, now one thing, there is some black admission in it, due to which he is doing it like this. Okay that Abhilash Lilly return kya hoga return karna hoga ka ya ko vijay type meaning in return karna before that log me don't clock off kya log off but it's a that divided by match date the lord of the pain on PAP That what will be done with all the results that will come, its McDermott serial that Chief Lota is fine and in the end convert it into interior because you will get double the value photo shooting rally, because of this it is time to symbol that I am a doctor who is going to get sex. Hai Loot Jhal How To Fix If you liked the video then please comment in the comment section and do not forget to subscribe the channel and for this question I am going to release this pure video on Saturday One More Time So Let's You Are Gas Rah Gaye Aapke Yash Left after one month hydration ok sakhri hai karke in next video thank you to
Poor Pigs
poor-pigs
There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous. You can feed the pigs according to these steps: 1. Choose some live pigs to feed. 2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs. 3. Wait for `minutesToDie` minutes. You may **not** feed any other pigs during this time. 4. After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive. 5. Repeat this process until you run out of time. Given `buckets`, `minutesToDie`, and `minutesToTest`, return _the **minimum** number of pigs needed to figure out which bucket is poisonous within the allotted time_. **Example 1:** **Input:** buckets = 4, minutesToDie = 15, minutesToTest = 15 **Output:** 2 **Explanation:** We can determine the poisonous bucket as follows: At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3. At time 15, there are 4 possible outcomes: - If only the first pig dies, then bucket 1 must be poisonous. - If only the second pig dies, then bucket 3 must be poisonous. - If both pigs die, then bucket 2 must be poisonous. - If neither pig dies, then bucket 4 must be poisonous. **Example 2:** **Input:** buckets = 4, minutesToDie = 15, minutesToTest = 30 **Output:** 2 **Explanation:** We can determine the poisonous bucket as follows: At time 0, feed the first pig bucket 1, and feed the second pig bucket 2. At time 15, there are 2 possible outcomes: - If either pig dies, then the poisonous bucket is the one it was fed. - If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4. At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed. **Constraints:** * `1 <= buckets <= 1000` * `1 <= minutesToDie <= minutesToTest <= 100`
What if you only have one shot? Eg. 4 buckets, 15 mins to die, and 15 mins to test. How many states can we generate with x pigs and T tests? Find minimum x such that (T+1)^x >= N
Math,Dynamic Programming,Combinatorics
Hard
null
289
hey what's up guys in this video i'm going to go through this uh liquor 289 game of life so um yeah there's a lot of wording in here but let's dive into the example directly so uh for each sub this is uh the cells uh so zero means that cell and one means uh a living cell and we need to look at the surrounding cell for example by surrounding is really means that for example this cell the surrounding cell would be this one and this one so it has eight surrounding cells and then look at the stylus of surrounding cell to determine the whether it's gonna be living or that in the next stage and for example for this cell there's there are only three neighbors for this guy he has one two three four five neighbors so for that one as we talked about it has eight neighbors um and there's a lot of wording here but essentially what it's saying is uh if we sell that was a one so that was leaving before if the neighbor all the neighbors um he has two or three neighbors that are leaving it will he will leave in the next stage otherwise he will die so let's look at the example uh for example for this guy over here it has um one two three yes three leaving neighbors in on in this stage and the next stage you're gonna be leaving you're gonna be alive however uh let me look at a counter example oh for example this guy he has only one living neighbor in the next stage he's gonna be dead because he's on his only one living neighbor it does not have two it does not have three living neighbor that's why in the next stage it died and for the cell currently is that because you will be alive we have if we has three um living neighbors so for example otherwise you die so for example um let me put this wording over here so for example for uh for this guy over here it has three this it has to be exactly three living neighbors so he has exactly three main layers in the next stage it is a life and for this guy over here he has only two living neighbors in the next stage instead is continue to be that so we need to avoid a function to determine the cell in the next stage is going to be leaving for that and we need to do this one in place meaning that we have we will be constantly overriding the board and uh and the status of the um those labels could be it has to be based on the uh the status and time zero is not the status in time one in the next it's not in the sudden in the next stage has to be the status in the current stage so that will be the challenge because we'll be overriding the board so the step so the information that's showing the board will be changing right so and that's a challenge and uh and this is showing the same thing whether we just discussed um and yeah so that's one of the one follow-up question one of the follow-up question one of the follow-up question one of the yeah the second one is um let me read it for you uh we represent the board using a 2d array in principle the board is infinite and well which could cause problem when the active area encroaches upon the board if the broader of the way for example our living cell you have reached the border and how would you address this problem and we will talk about that after we solve this recording challenge and this question was popular as you can see it was asked by amazon drawbars open door and all the other big names also google and apple facebook um let me show you my solution and first we need to actually have a direction list because it has you can go to affordable direct sorry not for eight different directions um you can go to here and go to the corner here so yeah totally entirely eight directions so we have a direction list that's all the possible direction that we can look around when we find the neighbors and with number one rows number columns and this is the um status tracking that we can do it in place on the board um this will come into handy because we have to do everything in place for example if the cell and at this current start and the current stage is leaving and they continue to be leaving so it's zero means is dead and one means our life right so in the current stage is leaving and the next stage is still b to be alive and then we have a one and if currently is leaving in the next stage is going to be that so you have a one and zero so currently is that and the next stage is going to be leaving with zero and one and zeros and zero will probably guess that already it means that is that at the current stage and next stage is continue to be dead so um as you can see we have the top four two for loops um nested follow-ups four two for loops um nested follow-ups four two for loops um nested follow-ups in here uh let me walk you through uh the first one first and then we are going to the next one which is a lot easier to understand so uh we have a double for loops to look through each of the cells on the board and then for each of the sales we have the count lives so we count how many neighbors surrounding neighbors they are leaving and for uh the row move and column move in all the directions list and the neighbor that we're looking at would be the current row plus the row move and the current column plus the current move and then that will be a specific neighbor that we're looking at the coordinate of the neighbor that we're looking at and if the neighbor is within the boundary right minus one because we are talking about index if the row the net the row of the neighbor and the column of the neighbor as they are within the boundary and then we can look into their value if their value are either one means that we have not yet override a board or a one or one zero basically we only interested in the first one because we only need the current status of the cell right so either one of these three then we can increase the current lives by one so basically we this chunk code is basically uh this chunk of code sorry we basically look around for the neighbors if the neighbors are within the boundary if the current status they are leaving we increase the count life by one and uh and then now we have some two cases in here and for the first case if the cell is leaving is um is alive currently is alive and you will continue to be living it continue to be alive if there are two or three living neighbors so this is exactly doing that right so if uh the cell is currently alive if the surrounding neighbors has against two or three uh surrounding neighbors they are live currently and we can override it to be one and one because it's currently living and continue to be alive otherwise if the surrounding neighbors they don't have two or three of them are leaving they will die in the next stage and then they will move from one to zero and that's one case currently um the cell that we're looking at is alive or if the cell we're looking at is that in that case if there are three names surrounding neighbors they are currently alive in the next stage the cell will be alive and how can we do that because currently we can have the common life is equal to three and it will move from zero to one it moves from the dead status to one the living status the alive status otherwise you continue to be that and after the after that we often we overwritten the entire board by having like one string on one serial as a string zero one or zero everywhere on the board and then we can translate basically we only need that started in the next stage so that's why we only need the second number over here and that's exactly how we can do that so we look at the second component and then convert it back to the integer so this is that and as you can see uh it's pretty efficient both on the speed and also on the memory and memory is a key point in this exercise uh speed as you can see is big o of m times n um even though we have 12 2 for loops but we just um each of the forum takes big over n times n and another one takes the same time so and it's basically m times n plus m times n so essentially still m times n and then we're doing some if statements in between and they are only taking big o one so that addresses the first question and the second question we have was uh what about the board is infinite i couldn't come up with a better solution than the official one so i'm gonna read it for you and so and uh so far we have only adjusted one of the four yes the following questions for this problem statement we saw how to perform the simulation according to the four rules in place for example in other words without using any additional memory the problem statement also mentions another follow-up statement another follow-up statement another follow-up statement where it says which is a little bit open-minded open-minded open-minded open-ended sorry we will look at open-ended sorry we will look at open-ended sorry we will look at two possible solutions to the adjustment essentially the second follow-up essentially the second follow-up essentially the second follow-up answer has to adjust the scalability aspect of the problem what would happen if the board is infinitely large can we still use the same solution that we saw earlier or is there something else we can have we will have to do uh differently if the board becomes infinitely large there are multiple problems our current solution could run into and that's the other problems first one is it could be computationally impossible to iterate a matrix that's really large it would not be possible to store that big of a matrix entirely in the memory we have a huge memory capacity these days for example let's say it's 100 gigabytes however it still wouldn't be large enough to store such a large matrix in the memory and thirdly we will be wasting a lot of space if such a huge board only contains a few living cells and the rest them are all that so the rest so only a few ones and the rest are all zeros in that case we have a extremely sparse matrix it won't make sense to save a board such as a matrix coenco matrix this is very sparse because it's only a few area contains um useful information this is what it's saying such an open-ended problem uh better such an open-ended problem uh better such an open-ended problem uh better should to design discussion during programming interviews and it is a good habit to take into consideration the scalability aspect of the problem since your interviewer might be interested in talking about such problems the discussion section already does a great job at addressing this uh specific portion problem we will briefly go to go over two different solutions that have been provided in the discussion section as they broadly cover two main scenarios of the problem so one aspect of the problem is that just by this gentleman over here so as mentioned before it is quite possible that we have a gigantic matrix with a very few living cells in that case it will be not smart to save the entire or at as it is so if we have extremely sparse matrix it would make much more sense to actually just save the location of which only living cells are located and then apply the four rules according to accordingly using only the living cells and there's some code in here uh that's showing how to do that however essentially what it's saying is we can uh obtain only the living cells from the entire board and then apply the different rules only the own using only the leaving cells and finally update the board in place the only problem with this solution would be the entire board cannot be fitted in the memory if that's indeed the case then we would have to approach problem in a different way for that scenario we assume that the contents of the matrix are stored in the file one row at a time in order for us to update a particular cell we only have to look at each eight adjacent neighbors which essentially lie in a row above or below it so for updating the cell of a row we just need to either row above and the row below and thus we read one row at a time from the file and at max we have to use three rows in the memory we'll keep discarding rows that are proceed are processed and then we'll keep reading new rows from the file one at a time and then another person's solution resolved um around this idea and then there's some discussion about this coding in the discussion board it is important to know that there is no single solution for someone's problem everybody might have a different viewpoint for addressing the scalability aspect of a solution and these two solutions just adjust some basic problem with handling matrix based problem scale so yeah this is so much how i would approach this problem and also some other people approach the scalability of this problem i hope you like it if you do please hit the like button and consider subscribing to the channel hopefully i will see you in the next video thank you for watching
Game of Life
game-of-life
According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. " The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its [eight neighbors](https://en.wikipedia.org/wiki/Moore_neighborhood) (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): 1. Any live cell with fewer than two live neighbors dies as if caused by under-population. 2. Any live cell with two or three live neighbors lives on to the next generation. 3. Any live cell with more than three live neighbors dies, as if by over-population. 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return _the next state_. **Example 1:** **Input:** board = \[\[0,1,0\],\[0,0,1\],\[1,1,1\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[1,0,1\],\[0,1,1\],\[0,1,0\]\] **Example 2:** **Input:** board = \[\[1,1\],\[1,0\]\] **Output:** \[\[1,1\],\[1,1\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 25` * `board[i][j]` is `0` or `1`. **Follow up:** * Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. * In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
null
Array,Matrix,Simulation
Medium
73
1,503
hey everybody this is Larry this is day four of the Leo daily challenge just want to make sure because I got it wrong yesterday uh hit the like button hit the Subscribe button join me on Discord let me know what you think about today's F and let me know what you think about yeah these intros in general I'm here again still in kagoshima I always have trouble remembering where I am but I've been in different cities every other day yeah uh here's the problem hey uh yeah thanks the other older Larry or younger I guess younger Larry from the past it's always a younger Larry when you're looking at me now I am older in real time and I got to stop like I don't know did I not submit yesterday why is that uh sorry friends huh I guess I have to redeem a Time ticket sorry friends give me a second uh huh whoops did I not submit I have to look at it again but oh well what a silly I mean we had a video on it right so okay I just click on submit how does this work yes did I huh man that is wild H I have to remember this is the second time I done the prom and forget to submit I mean I don't know maybe on my profile there'll be a streak thing but I don't care about a streak per se but at least I don't care if I didn't do it but if I did do it then you know I wouldn't be able to do it anyway sorry friends uh part of the fun part of live is that you could see Larry being silly in other ways uh but yeah let's take a look at today's P 153 last moment before or ends for our prank okay so R prank of length end um I don't know if this is well known by now but I've seen this a few times and I know it so I don't know uh but the idea here is that you know the okay the first thing you might consider to do is simulation but n is 10 to the 4th which is like 10,000 and 10,000 if you do like is like 10,000 and 10,000 if you do like is like 10,000 and 10,000 if you do like n square e things because they always or at the worst case they're going to collide like half of them on the left half on the right or something like this and then Collide right um the way to visualize this is uh and I'm going to bring up the drawing pad for a second uh okay there we go is that uh and I probably have done this visualization before but you can think about this as a number line or whatever uh or the line that they give you and then actually let me redraw this maybe you could think about this as a the line that they give you but then now you can add an extra AIS of uh time right so now you know going up is time right let me do it this way so then now you say let's say we have a red one that goes from left to right what does that mean right so that means that the first um can you see that dot it's a little bit small but uh let draw a s instead so let's say we start here I'm drawing with the touchpad so it's a little bit weird but you know or you know it's just ugly right and then the next one if it moves to the right it be here right and so forth so then here you could draw this line as right something like that and it moves One Step per second and right uh of course the only difference is or the only thing that's tricky is that they also oh whoops uh is that they're also ones moving to the left and they Collide right so let's say you have something like this and the blue ones are going to the left side and you know same idea right and you do something like okay I messed up on the drawing and connecting the dots okay there we go right and then of course here what you actually want to do in theory is that because now they Collide um at the same spot uh then now you can think of it as this boo going to the right and then you know what this is what they want you to think right but if you think about it you know uh if you kind of and I kind of maybe hint at it a little bit already right which is that okay so this is what happens if you kind of think about it in a timeline kind of thing but because all the ants don't matter or ants matter but no uh because each end is um not differentiable from the other one uh meaning that they are uh in a way funable man I'm talking about these ANS like economic things but um but they just like you know there's no an a with a different characteristic and they're all just the same right so that means that in a way you can think about them as oops you can think about it like this as in you know you could just like let's say uh n the red n is one and the BL n is two um you can just swap the IDS afterwards right so when they Collide you may say that the N1 goes to the right and N2 goes to the left but or the other way around maybe I don't know this mirror thing is always hard um you can think about them as just passing through each other and with that logic that means that you get to um skip all this simulation and just see kind of things right um so that's basically the idea by this form and once you realize that idea a lot of things become a lot easier and also if you look at Solutions prior is just like way short as a result but okay let's actually look at the problem um all right uh yeah so left oh this is just an array of things okay do we even have to sort no maybe oh I didn't even realize what the problem was asking is the last end right as a result of our thingy uh and swapping them that means that you have to just get to see which one is closer to the left or closer to the right the edge and then going off right so that means that for X in left okay so let's just say four this is equal to zero for you know whatever uh what is so this four what does that mean right it's going oh sorry it's going to the left okay so that means that everything on the left it takes X seconds to cost right so that means that actually this is just max of left right because yeah and then to the right it is the smallest so Min of right and then that takes n minus Min of right so that means that Forest is equal to Max of this and you can actually even right oh well whatever that's why this way and then obviously you can actually do this is a oneliner uh and I'll try to oh is there an Mt sequence oh okay uh you could default this as zero I think I don't know it's uh it's a this is a list oh no this is uh I think that's what I was trying to do someone like this oh yeah okay cuz I wasn't sure it was a positional argument I always forget and yeah and this time we actually quick submit and will you get it wrong why tell me why wait what am I misunderstanding this why is this not a thousand oh this is going left oh this default as well okay fine uh that's why I guess we trying to be too smart on this one uh first time I didn't even get it well cuz I would have just done yeah the actual Loops but this time I um I tried to be too cever and I set the default well um but yeah uh that's I gu we trying to be slick but uh no uh but that's pretty much it obviously this is going to be linear oh is this blocking the screen a little bit uh I mean you see the definition I think that's fine let me my big head okay there you go all right uh but yeah linear time constant space that's all I have for this one let me know what you think and you could see my outro now that's all I have for today let me know what you think stay good stay healthy to your mental health I'll see you later take care bye-bye and today you later take care bye-bye and today you later take care bye-bye and today I'm going to end the day with these grape a bag of grape ice cream it tastes pretty good tastes like what you expect grape looks like a grape and then yeah tast tastes great I got nothing all right see you
Last Moment Before All Ants Fall Out of a Plank
reducing-dishes
We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**. When two ants moving in two **different** directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches **one end** of the plank at a time `t`, it falls out of the plank immediately. Given an integer `n` and two integer arrays `left` and `right`, the positions of the ants moving to the left and the right, return _the moment when the last ant(s) fall out of the plank_. **Example 1:** **Input:** n = 4, left = \[4,3\], right = \[0,1\] **Output:** 4 **Explanation:** In the image above: -The ant at index 0 is named A and going to the right. -The ant at index 1 is named B and going to the right. -The ant at index 3 is named C and going to the left. -The ant at index 4 is named D and going to the left. The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). **Example 2:** **Input:** n = 7, left = \[\], right = \[0,1,2,3,4,5,6,7\] **Output:** 7 **Explanation:** All ants are going to the right, the ant at index 0 needs 7 seconds to fall. **Example 3:** **Input:** n = 7, left = \[0,1,2,3,4,5,6,7\], right = \[\] **Output:** 7 **Explanation:** All ants are going to the left, the ant at index 7 needs 7 seconds to fall. **Constraints:** * `1 <= n <= 104` * `0 <= left.length <= n + 1` * `0 <= left[i] <= n` * `0 <= right.length <= n + 1` * `0 <= right[i] <= n` * `1 <= left.length + right.length <= n + 1` * All values of `left` and `right` are unique, and each value can appear **only in one** of the two arrays.
Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Otherwise, keep the previous best like-time coefficient.
Array,Dynamic Programming,Greedy,Sorting
Hard
null
1,639
number of ways to form a Target string given a dictionary means just some words so let's quickly jump on to the problem statement and it's pretty big so yeah I have just broken down into actual components so yeah let's see it's firstly it's given that okay you are given a string a list of strings of same length and that list of strings will be inside worlds which means words will have a list of strings of same lengths same length and a string called as a Target string which I need to make your task is to form the target which I have to make using the words in this all these strings under the following rules what are the rules right the target it because it needs to be formed right so it should be formed from left to right which means I can't form see I ultimately want to form a Target but it should be formed by picking the elements from left to right cool to form the ith character zeroth index of the target let's see to form the ith character Zero index of the target you choose the kth character of the jth string inwards so many variables but still if the target what I'll show you if I want to make this then it should be same of some jth string in this word kth character it means that okay the character should be same that's all once you use the kth character which means this character then what happens is of the chair strain of the any string here we choose of this particular string although you can choose any string but if you choose this character then what happens is you no longer can use the X character of any string in the words where X is less than equal to K which means any character less than this thing whole thing because it is already you have chosen so remaining is this whole thing right so for the next upcoming element you cannot choose anything from this white part you can only choose from the next part it is what you have to do from left to a right cool that it is saying that okay all these characters becomes unusable last thing was that one thing was before this also that repeat the process until you form the string Target that okay I choose some that I choose next so I have to just form the target I have to do such steps notice that you can use multiple characters from the same string which means if I want to make ABA I choose a from the string let's say 1 then I choose the B from strain 2 then again I can choose the string the character a from the string one itself which means I can choose the same character again and again provided it should come after which means if the a would have been here I could not have chosen it needs to come after this whole thing cool last year aim is to actually return the number of ways to form the target from the words firstly if you just read this thing then only you should actually be able to think of what things should be applied here but still I'll not name that thing I'll just show you how you actually reach to that thing since the answer may be very large so for sure very standard thing if the answer is large you return the modulo money nine plus seven cool now let's see the example to actually figure out okay um what's happening in the background if I have these three words it's the same word which I took in the above example itself same exactly same I will take the same example in the whole problem Target is Aba which means that okay what all can be possible firstly I just show okay how what all can be possible then I'll show how it is being made firstly to make this ABA I can just grab an a from here B from string two a again from string one a from here B now c b earlier I took this one now I can take this one also so it's same okay I think here then again I get grab the a then one option is a b a again is a b a so these string are these six ways can be possible to make this target out of these three strings provided you always saw whenever I had to choose next element I just make sure that I'm choosing after this I can't choose anything before if I'm doing a B I choose B for the next character I have to choose after this whole line now see what option we have you saw what option we have we had to choose a Target ABA so one thing for sure that okay I start let's take this example only I start with a because I want to make a Aba I start with a then my next option to choose is B so I just go choose B another option to choose B is next just here because I just have one condition that okay after this I need to choose so whatever I can choose after that I choose B has two options from this a I have b as two options then from this B right here this be right here for a I have two options this here and here from this B right here I have two options right so what's happening wait let me erase this whole part and here from this B2 let's say it is B3 B2 B3 from B2 we have two a's the a right here and the a right here from B3 also we have two ways a right here and a right here which is A2 and A3 and also in the starting you started from here right what if you had started from um let's say this a right here the bottom a the bottom if you are started then you have next option is 1B for this 1B which is actually a B3 you have same options again two A's this a and this a right here which is A2 which is a and again a right it is for the top it is for the last which means top last you saw what happened for this B3 top last for this B3 you are again finding you will start with just one a then again for this B2 you go B3 you go then for B3 for this next a also your B3 part which means this next sub problem part is repeating you know it's a recursion you start because you wanted to make the Target string which is a b a but you just start choosing those characters you just started with that character next you choose B you have two options next to choose a you have again like for this B two options which is actually Four options and here we have two options so in total here you have four options here you have two options in total the options become six that's the sixth answer but you saw what happened while choosing this B you again have to think of okay let's think of choosing next is same problem occurs here if you take this a right here one thing for sure you know okay um when I'm trying to choose problem is being repeated for sure it's a DP problem I need to optimize it by ADP before that let's see how you can optimize this which means what part of problem is repeating that okay you know okay v a sub problem which means that this particular part let's say ba will come it will repeat so I can just grab okay number of ways to grab ba or I can do vice versa also maybe a b and then I can just look for again next a but let's see actually how in this problem we are thinking what is happening you saw what happened that I just showed you that okay problems are repeating here you can easily see that when I have grabbed these a B's then again I have to think I have this next a incoming which means if I have the number of ways okay I can just grab this a b when is the next incoming because ultimately my condition is that anything after this a anything after this so if I just know the number of ways to grab a B from here up till this point and then again I can number of A's which occur after it I'll just multiply the number of ways to grab this A B's into a you didn't get it or you get it was exactly the same how I was making from a I had two options let's consider I had made EB now I need to find the number of options to get just a here I was just saying okay from a I had two options for B then for these B I have again two options so let's consider okay to get a B I have three options now what are the number of ways to actually get the final a let's see with this example so what I can do is I can actually make my DP store number of ways to form the target J First characters which means number of ways I can grab a B ultimately I want to make a b a right a b a let's take a number of ways to just grab a B Because see ultimately my main aim is to find the condition which I have to put that okay I can find the answer for my main strain so let's grab the answer for the small string is this main string is this if I have the answer for the small string so I should be able to find out the answer for the whole string it is my a ultimately so I just had a bigger problem I just thought okay if anyhow I just got the answer for that small problem how I will get the answer for my bigger problem which means if I had the number of ways I can get this a b so Arun please give me the number of ways I can get abs here you can easily see number of ways you can grab a B is actually three as I showed you a b because it is one a b here and one a b here so number of ways to grab a B's are actually three now after that I just okay after this I assumed to think okay next incoming thing is a number of ways to grab a B is three next incoming thing is a how many A's can be there are two A's which can be there so for these three a B's I can have two a's you saw what's happening which means three is three a B's and two A's so in total I have six ways to have a Aba a b a in total six ways to grab a Aba a b a that is the reason if I just get to know the answer for the small sub problem which is number of ways to grab a B I can just count the number of A's here right now and I can just grab a kick count of these number of A's I have it is my DP of let's say J then it is the count so I'll just grab okay what is the actual number of ways to form the count of first J characters that is pretty much it in this DP firstly we just got to know okay the problem is being repeating so it's a DP problem for DP problem we just need to know uh the DP State and the DP condition the DP State let's think but for that let's see how we'll get the DP condition we just assume okay let's assume that for smaller sub problem we have the answer so how for the whole problem we'll get the answer if first smaller is a problem I have the answer for number of ways for a b number of ways to get a B let's say we have the answer and we get the next incoming a so how we will just grab the total number of ways to grab this ABA we just get to know by this condition that I will just multiply number of ways to get a B into the frequency which means the count of number of ways I just get the answer which means ultimately what happened was the DP state will actually become something like this number of ways of getting the first J characters of the target first J characters I am actually analyzing the first G characters of the target at a particular State and again finding out the result for that particular J characters at point of time I hope that you guys accounted which means that the DP of first J plus 1 characters is nothing but the DP of first J characters into the count of this incoming character which is after this index existing first J characters and then new JPS uh new deck the count of that particular character which is incoming in this condition let's see the code I'll explain actually how the code beautiful is written see you just got to know this DP condition that how actually we are finding the number of new number of ways which means earlier for a B I knew I know I'm repeating that but if you have not understood it you can just skip it uh number of ways we get a b and then after that we have this a and then we can write the answer let's see the code pretty quickly it's easy not that but yeah medium firstly I just grab okay n m mod and all that stuff DP is actually what I need to make my target right so I'm just I have a b a so I just said for this at every state of those ja characters first G characters of what of Target so for sure my DB will have size M plus 1 because I'm just saying for the first character let's say it's a so it is DP of 1 which means one character if it is a b it is T P of 2 uh DP of 2 but if it is a b a it is DP of 3 it is just saying okay I am analyzing first G characters it is only analyzing one character only analyzing two characters first two characters because for sure we are starting from left to right analyzing first three characters of this particular string Target cool uh then we will just grab for sure I marked my DP of 0 as 1 why 1 it's because you know I am analyzing my DP of one so for sure my result will start from DP of 1 itself and not from 0 because my DP State actually stores for first J characters so for this DP of one as I showed you in the condition itself if it is 1 so for short J is 0 if J is 0 so I need to multiply by some count so initially if this DP of 0 if this DP it will be a DP of 0 if it is actually a zero then the count whatsoever it is there it will just actually go to 0 because 0 into something is 0 that's the reason I just want okay whatsoever count is there it should come that's the reason I should I just put one in case of DPF DP of 0. cool no worries then I have the count as I said at a particular point of time I just need okay what is the count of all the A's here what is the count of all the B's here because when I have analyzed this particular index I then when I am at this index I need to know okay I just know okay what is the DP of J here but I also need to know okay if the incoming character I need to analyze is the a then what is the count of it you can also iterate on this particular whole string but it's useless you can just have the count of a that you can know okay A B number of ways are let's say three count of a is actually two right now right here so number of ways to grab a B A is nothing but 3 into 2 which is 6 if at this point of time number of ways to grab number of ways to have a b is 3 number of ways to have B after that is 1 because it's just one because the count of B is one so number of ways to grab a B is nothing but three into one it's the reason I just grab the count at every index whatsoever alphabet character is there I just had and kept its frequency so that I can use the same thing while analyzing my DP because in the DPS itself I showed you I need to get the count of this incoming character of what of Target cool no worries then for sure uh my actual DP uh condition starts that okay I'll just go on from left to right it was second version from left to right which means increasing the size of this sub problem I have this a uh C what was the condition is c yeah a c a b c a so I'm just going from left right okay I just analyzed first only this then I analyze only this then I'll analyze only this it is how I'm and I'm just increasing my portion part which I need to analyze cool uh after that you will see I now okay my I'm just iterating on my words but what I have to think of is of my DP condition DP of what DP off as I said I need to check for the first check characters offer of Target that's the reason I have to iterate on my Target also for that particular reason because I need to get my dpfj but you will see that I iterated backwards rather than forwards he will ask why I did it from M minus 1 because I need to trade on my target itself for every small sub problem you will see I just iterated from backwards rather than forwards is the reason because as I told you if I am standing here for this particular eye then I will just check Okay add this I just check for this particular let's say a so I am actually analyzing my ap of 3 because it does the first three character which I'm analyzing right now for which I would need my DP of to which means the previous result of a b but that previous result of a b should be as of before not this I as of before which means when I would have been here it should have been in the last Loop in the last iteration of I whatsoever DP of 2 would have been there it should be coming which means as of I minus 1 if I'm standing at I so as of I minus 1 I want the DP of 2. thus if I just iterate on from 0 to 3 which means from 0 to M minus 1 then my DP of 2 will actually update as of I but I want my DP of 2 for my DP of 3 as of I minus 1 I want this as of I minus 1 not as of I because I want that when I am actually seeing this particular element right here I should only consider the element which means a b part if I'm c a right here I have to consider the a b part as of before as I showed you this condition it was marked as of before we need to analyze that's the reason I just iterated it backwards rather than forwards I hope that you guys got it and it is the exact same deep condition which we actually saw above that our DP of J plus 1 is nothing but DB of J into the count of that incoming character so it is the same way it is gone yeah DP of J plus 1 is nothing but DB of J into the count of that incoming character and it is just mod and I as I just added so I have to do a mod again because so that it doesn't overflow ultimately I have to return the DP of M why dpfm because it is the final a b A's C we need to analyze the first J characters so first three characters which means the string size is itself three which is M string size itself M Target is M so I need to analyze the first n characters and it is done so I have to return a DP of M that's pretty much it I know it had been a pretty complex problem but I hope that I was able to make it understand now time capacity is pretty simple as you look at the code we'll just get to know that we are just iterating on those words and for every word I'm just going on to every word length so it is if number of words are W word length are n so it is uh W into n in this particular DP condition loop I am just going on to that word length and for that I'm going on to every Target from reverse so it is M which is n into m that's the condition it is whole n into W plus n into m space is nothing but we are using a DP of size Star Gate which is M and a vector of count which is actually n into 26 which is constant so it is nothing but n into n plus M all the codes for C plus Java python is down below I hope that you guys got it that how I thought okay anyway I just get the small part I just get the number of ways to get a B now I know okay number of A's whatever are there I just multiply the number of ways to get the ABA now I have to think okay how I will actually find the number of ways of that a b so basically I have just I just assumed I have the answer for the smallest problem that I just know okay what condition I should apply okay when I know the condition then I actually get to know okay what DT State I should put on that actually because see although while explaining just people just explain okay you just take a DP State write this but actually how you think of is what is required to actually make your DP State as DP of J and not a UDP or something else by just iterating if you just think okay if I get the biggest sub problem but if you like you will know what is required to have that small problem anyways I just need to have what is the number of ways to get the SE first two characters number of ways then if I have a I just get okay first number of ways to get a b a I hope that you guys got it and then goodbye take care
Number of Ways to Form a Target String Given a Dictionary
friendly-movies-streamed-last-month
You are given a list of strings of the **same length** `words` and a string `target`. Your task is to form `target` using the given `words` under the following rules: * `target` should be formed from left to right. * To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`. * Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string. * Repeat the process until you form the string `target`. **Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met. Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** words = \[ "acca ", "bbbb ", "caca "\], target = "aba " **Output:** 6 **Explanation:** There are 6 ways to form target. "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ") **Example 2:** **Input:** words = \[ "abba ", "baab "\], target = "bab " **Output:** 4 **Explanation:** There are 4 ways to form target. "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ") "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ") "bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ") "bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ") **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * All strings in `words` have the same length. * `1 <= target.length <= 1000` * `words[i]` and `target` contain only lowercase English letters.
null
Database
Easy
null
427
represent in the Daily Challenge constructor and what do we have to do if false if lift if false then the value? We must not be understanding this. Let's go ahead. There was no point in giving it here. Internal loan is four, but what are the attributes? What is said in the factory, does it represent or not? If the value represents grade of zero, explain it in simple language, if whatever happens to the value, if the value of the grade, if there is a mother, means all the value, if there is a van, then the value of the grade will be its van. And if there is zero, then it becomes a matter of zero. False means we represent zero. Constructive mother takes it. This is our great question. What is our saying? Se value is all van and zero if the se value of the current grade will be okay. That means it is the photo of the note. What do you say next, what will be the set value which is the element, inside this I tell that if this is our great, okay this is the note, the meaning of the note is that it is representing the grade, then the note of the note on one note, if all means it has any children like In this, all the values ​​are zero, our van is fine, in this case, what will be our lift, it can be zero too, we will have to see all the deletes inside it, by the way, I will explain in the question, then you will understand, so let's move ahead, now let us try a question. Come on, like what is there in the example, what will we actually do Tell me, what elements are equal in this mode, after that now one thing has happened Top left is representing our top right, now we are top right. But the leaf note is Van and what will be the value. Zero will take a lot of time. D divided into current. Now we will see in the top left if ours is true then Van is done. What will be the value which is above the element. We will see all the ones in the top right. If you don't open it then it means that this is not our leaf note, so the value of this lip is zero value, we can take zero and van anything. Okay, open all the ones in the bottom left, it has become zero, the saree one was equal and it will not have any child. But there was no equal in this. What is equal? If not equal comes here then take it as I have written above that zero van zero. If any one of these goes to grade A zero van zero then we do it again inside it and then our How is the note formed, I come out one more, then this is our problem, now the complete recursive is written, how do we solve it, first of all look at the base condition in the distraction, what can be the base condition, that is, as many small valid cases are required as possible. What will be the smallest validation and which will be the smallest valid? This will come when we have only one element left, no time, what will be the true value equal to date element and the rest of the children etc., whatever means its child etc., whatever means its child etc., whatever means its child when I will be a single element, mother lo if If only one element is given then it is not possible that there is a note and the value is converted, then first in the unit and then we will convert it into 2/2, in the unit and then we will convert it into 2/2, in the unit and then we will convert it into 2/2, meaning by putting a note of 2/2 each, four meaning by putting a note of 2/2 each, four meaning by putting a note of 2/2 each, four children will become 2/2. After that children will become 2/2. After that children will become 2/2. After that our 1 * 1 will come again, in this we will have a single element in action our 1 * 1 will come again, in this we will have a single element in action What has happened to us is true and the rest has come, now tell me when is it possible that there will be no child note, by the way I will show it from the court itself. Let me tell you once that it will be a bit complicated, so let us show it in the court itself, so first of all we will take a function I grade, after that the initial cell of a column means position, whatever it is, we will simply make a note and create a new note structure. Okay, what else is the leaf note? Yes, if it is bullion, then the phone will also work. To present it, we create a parent note. Now we have kept N value in it. Now keep its face. Now we will come to our top left. What? Starting from here, we will convert the top right to top right and what is the length of this top laptop grade, sorry did I do something wrong, have we taken out the top left, have we taken out the top, is the top model, is the bottom left less What will be the value here? 1111 is also from the value above, it means what is it representing, it means it will represent from all the values ​​of this great, it represent from all the values ​​of this great, it represent from all the values ​​of this great, it is recursively broken out and seen later, the top left leaf is required, it means it is its child. There is no child, there is no child, it means all its elements are equal, now all the elements of its elements are equal, so how can it be that it is equal but here zero is zero, okay So this means that then it will become a separate child. Do you understand that a new set will be created because its A value will become zero? No, but if it is so that all the A's are equal, then it means that this is a leaf note and it has no child. It is not a child because all the elements are equal, the value is also from, so we checked that if the leaf is note, then why is it also and if the value is from also, the value is compared, the value is also from, meaning this is the entire top left grid of this. If all the elements are equal, then only one note will be written in it at a time, which means it will be left as a leaf, which means it will be presented as a whole and not sent to me separately. How was it told? What will the value do? Update the value of any one separate item. I am lying, when it is equal, it is ours, but if it is not like this, then what will happen to him in case, this is our single, he will have some children, so this is our time, top left, parent note, bottom right, question mark. And also I didn't make a typing mistake Let's submit
Construct Quad Tree
construct-quad-tree
Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent `grid` with a Quad-Tree. Return _the root of the Quad-Tree representing_ `grid`. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: * `val`: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the `val` to True or False when `isLeaf` is False, and both are accepted in the answer. * `isLeaf`: True if the node is a leaf node on the tree or False if the node has four children. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } We can construct a Quad-Tree from a two-dimensional area using the following steps: 1. If the current grid has the same value (i.e all `1's` or all `0's`) set `isLeaf` True and set `val` to the value of the grid and set the four children to Null and stop. 2. If the current grid has different values, set `isLeaf` to False and set `val` to any value and divide the current grid into four sub-grids as shown in the photo. 3. Recurse for each of the children with the proper sub-grid. If you want to know more about the Quad-Tree, you can refer to the [wiki](https://en.wikipedia.org/wiki/Quadtree). **Quad-Tree format:** You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where `null` signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list `[isLeaf, val]`. If the value of `isLeaf` or `val` is True we represent it as **1** in the list `[isLeaf, val]` and if the value of `isLeaf` or `val` is False we represent it as **0**. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** \[\[0,1\],\[1,0\],\[1,1\],\[1,1\],\[1,0\]\] **Explanation:** The explanation of this example is shown below: Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree. **Example 2:** **Input:** grid = \[\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\]\] **Output:** \[\[0,1\],\[1,1\],\[0,1\],\[1,1\],\[1,0\],null,null,null,null,\[1,0\],\[1,0\],\[1,1\],\[1,1\]\] **Explanation:** All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: **Constraints:** * `n == grid.length == grid[i].length` * `n == 2x` where `0 <= x <= 6`
null
null
Medium
null
485
foreign problem and the problem's name is Max consecutive ones so in this question we're given array nums and we have to return the maximum number of consecutive ones inside the array so in this example there are two consecutive ones but there is also another set of ones which is longer than the previous set having three consecutive ones so we return that as output now let's take a look at this example and see how this can be solved so I've taken the same example they have given us so this is the nums array so we are going to iterate through the nums array from left to right and we'll access each element at a time so inside this for Loop we are accessing one element at a time using a pointer I so if that element at I is 1 we increment the count and we compare it with the variable and store the max of Max and count inside this variable and we finally return Max as the output so we start from I is equal to 0 so the element at 0 is 1 so increment count and we also check Max of Max and count so max of 1 comma 0 is once so set max also to 1 and we go for the next element is also one so increment count will become to Max of count and Max is 2 so max will also become 2. now go for the next element it is 0 so make count 0 and check Max of count and Max is 2 so max will remain 2. go for the next element it is 1 so increment count Max of count and Max is 2 comma one so max will remain two move for the next element is also one so increment count is now to Max of Max and count is 2 comma 2 so max will remain 2 over the next element it is also 1 so increment count Max of Max and count is 2 comma three so maximum 2 comma three is three so change Max to 3 and go for the next element and now we reach the end of the array so we end the iteration and finally return whatever is present inside Max contains three so three is our output so this will be the range where Max is equal to three so if you return 3 as the out now let's code it up in Java so this is the function given to us and this is the input array norms and we need to return our integer variable denoting the maximum number of consecutive ones so let's start off by creating the result variable so max is going to be the output we are going to return which will denote the maximum number of consecutive ones and again I am going to create a variable count which will be used to count the number of ones in each set now let's iterate through the input array nums using a for loop from starting to end now we have to check if the element at the eight pointer is a one or not if that element is 1 we increment the count variable denoting there is a one and we check if it is the maximum streak until now and in the else block it means that number is not a one if it is not a 1 we set back the streak to zero so this for Loop will happen for all the elements inside the nums array and finally we have the result inside the variable Max let's return that now let's try to run the code the test cases are running let's submit the code there you have it a solution has been accepted so the time complexity of this approach is of n where n is the number of elements inside the nums array and the space complexity is above 1 because we are not using any extra data structure to solve this equation that's it guys thank you for watching and I'll see you in the next video foreign
Max Consecutive Ones
max-consecutive-ones
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = \[1,0,1,1,0,1\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
Array
Easy
487,1046,1542,1999
9
That's it, welcome back to my YouTube channel, I am Jyotish and in this video series, we are solving the problems of lift. The format of this video is because today we are going to solve a classical problem which is Calendar. Number So let's see what this problem statement says which is melanin teacher we have to return through if before one romantic but we people say follow the interior only when they reverse then it would be the same number example given 1622 121 which That number is 19 but - not the top number, That number is 19 but - not the top number, That number is 19 but - not the top number, similarly tan and - 101 can also be subscribed to the channel similarly tan and - 101 can also be subscribed to the channel similarly tan and - 101 can also be subscribed to the channel then you can simply reverse the number, in this way you can contact the new number with the number and do the according result if the value ok
Palindrome Number
palindrome-number
Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_. **Example 1:** **Input:** x = 121 **Output:** true **Explanation:** 121 reads as 121 from left to right and from right to left. **Example 2:** **Input:** x = -121 **Output:** false **Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. **Example 3:** **Input:** x = 10 **Output:** false **Explanation:** Reads 01 from right to left. Therefore it is not a palindrome. **Constraints:** * `-231 <= x <= 231 - 1` **Follow up:** Could you solve it without converting the integer to a string?
Beware of overflow when you reverse the integer.
Math
Easy
234,1375
551
hi my name is david today we're going to do number 551 student attendance record one only code this is an easy level problem and we're going to solve it in javascript so this one was kind of like a fun one a simple if else statement while we're looping through so we have a function that takes an s is a string right yeah it's a string that only takes in a l p a signifying the student was absent l signifying student was late and p representing the student was present and they have an attendance word if they meet these criteria and so basically we have to return true or false true if they meet these require both of these criteria is false if they didn't so if they were absent if the student was absent for fewer than two days and then the student was never late more than three consecutive days so that is how we're gonna solve this problem so for this example we return true because the student has fewer than two absences we look at the a's they only been absent ones and they're never late more than three times so they only relate twice consecutively so how we're going to solve this problem is that first we have to look at we're going to loop through this and we're going to return false if they doesn't meet one of these criterias and if they if we can loop through this without returning false we return true so the first criteria they look at is the absent so we have to create a absent variable and that's just going to be a number that we're going to keep count of how many times they were absent in total and next we want to create a rate variable but consecutive so i'm going to say late consec rate variable okay so these are two layer variables we're going to use to keep track of everything and now we're going to loop through s and inside this loop we have to create a condition if the student was if there was an a condition if value is a and what we want to do if this happens is increment a increment the absent and then we want to create a condition if absent is 2 or greater and then we just return false if this happens and now we look at the other variable was never laid three more consecutive days so we have to create a condition if it's a l and then we want to increment consec late and then once we got that we have to create an else statement because we need a consecutive to reset the variable else set contact date to zero and then lastly we return false if it's three or more so condition if contact rate is three or more and then we just return false and if we make it through this without returning fast will be returned true great so first we create the variables that absent equals zero that consec rate equals zero now we loop through s4 that i equals zero i is less than s dot length i plus and instead of this little loop we have to do each case if current index value as index i is equals to a we increment absent and then we create the condition to return false if it's two or greater if absent is greater than or equal to two return loss so that deals with this one and now we have to do the other condition if it's a late current index value equals l we do consec wait plus else we set this equal to zero and now we return false if consec rate equals is greater than or equal to three return false and we if you make it through this without returning false we return true great we got it so the complexity the time complexity we know that we're doing a loop do s so it's going to be of n and then the space complexity we are taking the constant variables here so it's going to be o one and that's it that's how you solve this problem thank you
Student Attendance Record I
student-attendance-record-i
You are given a string `s` representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: * `'A'`: Absent. * `'L'`: Late. * `'P'`: Present. The student is eligible for an attendance award if they meet **both** of the following criteria: * The student was absent (`'A'`) for **strictly** fewer than 2 days **total**. * The student was **never** late (`'L'`) for 3 or more **consecutive** days. Return `true` _if the student is eligible for an attendance award, or_ `false` _otherwise_. **Example 1:** **Input:** s = "PPALLP " **Output:** true **Explanation:** The student has fewer than 2 absences and was never late 3 or more consecutive days. **Example 2:** **Input:** s = "PPALLL " **Output:** false **Explanation:** The student was late 3 consecutive days in the last 3 days, so is not eligible for the award. **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'A'`, `'L'`, or `'P'`.
null
String
Easy
552
124
hey guys welcome or welcome back to my channel so today we are going to discuss another problem is binary tree maximum path sum very easy problem in this problem we have to find a path in the binary tree and uh so each node can only appear at most once path does not need to pass through the root so it's not necessary that the path should be passing through the root of a path is the sum of all the node values in that path so whatever path is all the values or sum of all the values in the of nodes in that path will be the path sum so we have two we have we are given the root of the binary tree and we need to find the maximum path sum of non-empty find the maximum path sum of non-empty find the maximum path sum of non-empty bath maximum path sum so let's take this test case here uh basically what we have to find is we have to find the path sum what is Pat sum basically this can be one path okay or this could be one path like from here to here like this so path sum is the sum of all nodes which are in their all nodes which is in that path so for example if we take this blue path 9 minus 10 plus 20 plus 7 this will be the sum of this path okay if you take the path of this yellow uh some of this yellow path so it will be 15 plus 20 plus 7 which is 42. and this will be uh 26. okay so obviously we have to find the maximum path sum so here the maximum path sum will be 42. that is this path so output will be 42. okay it will be 42. so basically what they are trying to say is we have to find any path and it's not uh it's not mandatory that the path should pass from root path should not like it's not mandatory so he path could be this one also it's not like it has to pass through the root this is the root right okay so either your so there are two cases either your uh path can pass through root or it does not pass does through root or it does not pass okay so pause the video and try to think uh how you can solve this problem see the problem understand it and see what is given so minus 10 trees binary minus 10 9 20. 15 and 7. right 20 15 and 7. so whenever we have t right we visualize it like this that we visualize it like we'll be given the root of the binary and we have some left sub tree we have some right sub tree we will work on the root and the rest of the work recursion will do right so here what is the thing we have to return the maximum path sum we have to turn the maximum path sum this is a work so one thing is that the path can pass through the root like this right so if the path is passing through the root so what will be the sum that case sum of the path will be whatever the sum of left sub tree the left sub tree plus sum of the right sub tree Plus sum of root that is root value so this could be one sum other sum could be like uh the sum is not passing through the this like the sum is not passing through the root so if sum is not passing through the root this could be the maximum some left sub tree or right some somewhere in the left subtree or somewhere in the right subtree you will get the maximum paths so there are two cases right so what we will do right base case is we all know what will be the base case is if root is null so what will be the sum if root is null sum will be what 0 so return 0. this is your base case okay now let's say we are here we are at this position our root is here so there are two things one can be this is your sum this is your maximum path sum like passing from this value right something like this so if this is the case when you are here so what you will do 20 plus whatever is coming from the left sub tree whatever is coming from the right subtree this will be your sum this could be one case right other case could be that you have to pass the maximum sum from this node to the parent node because it might happen that from this path you get the this is a part of that path right for example let's say from here to here something like this from here to 20 so which is more beneficial from this 20 either you go to 15 or you go to 7. so obviously 15 1 is more beneficial so it might happen this is the path right so to this minus 10 what you should return to this minus 10 you should return the most optimal sum right most optimal part sum which is 20 what is the current value root plus maximum which you are getting from left or right subtree what is the maximum you are getting from the left to right subtree that is maximum of whatever you are going getting from left and whatever you are getting from right subtree that this value you will return to the parent node because minus 10 should know right whatever what is the maximum path sum maximum sum in its like subtree child subtree so we'll have two cases right let me draw 3 again so minus 10 9 20 15 and 7. right you will have a global variable sum initialize to 0 when you are let's say you are at this node right this is your root so first you go to the left you make the recall left you go to right first of all you go to Left subtree DFS basic DFS we have basic DFS you go to left you are your root is here right now okay not here so your root is here from left you get 0 base case from right you get 0 so 9 plus if the path is like this only so 9 plus 0 will be 9. so this is greater than some ninth and to the parent root parent uh node you will return 9 plus what is the whatever is the maximum of left or right because one path will be there right if you either left path will be there or right path will be there both cannot be there obviously because if both is there then it will be something like this right so whatever is the maximum so 9 or plus maximum of left is zero right is also zero so it will be 9 plus 0 which is 9. so 9 will be returned from here okay so from here 9 will be returned to the parent node 9 is returned okay now you are here now you'll make the right call it will go to right so 20 here root will be 20. okay so first you go to Left 15 plus 0 and all that so 15 will be the sum then you go to the right you go here root will become 7 so 7 is not greater than 15 so it will not be updated but from here you will get 15 as a return value and from here you will get 7. okay so now your root is here you from here you get 15 from here you get 7. now see what you will do now there are two cases either your path could be this one that is this passing from this root like basically this path Okay so 15 whatever you get from the sum is equal to will be maximum of the whatever the current sum is comma the current root value Plus whatever you get from the left subtree left sub 3 plus whatever you get from the right subtree because that could be one path right so here maximum of current sum is what 15 comma root value is 20 plus left you are getting 15 right you are getting 7. so here your sum will become 42. here it will get 42. okay so here we have done this root work now we have to return now what we will return from to the parent node now there can be two cases either this could be the maximum path for this parent like it can go from 10 to 20 and 15 like this or it can go to minus 10 20 and 7 like this so obviously you will return the beneficial one which whatever is beneficial so that would be you will return what you will return to the parent node you will return root value plus maximum of whatever you get from the left and right whatever is maximum so 15 and 7 you're getting from left sub 3 and right sub 3 so 15 is greater so 20 plus 15 that is 35 we will return that maximum if you go from minus 10 you want to go you this will you will get the max path so from minus 10 plus 9 you are getting from here 35 you're getting from the right sub tree either this could be the sum right maximum but this will give you um 34. right this is not the optimal one so 42 is the maximum which you can get so output will be 42. so I hope you understood the approach uh let's see the code once it will become more clear dry run the code once yourself so we have taken this Global variable in initialize it with minimum value because we'll be storing the maximum value inside it then we have we are calling this function DFS and we'll return this maximum sum in this DFS we will populate this value so this is the base case that if root is null just return 0 otherwise you are making the left call you get some and you'll be storing the back like the maximum value if you get Negative from here so guys see if any time you're getting negative value there is no benefit of considering that right because negative will only reduce your sum so but we want maximum sum right so if it we are getting negative we will just get take 0 only will not go that path only for example let's say this is your root and this is a left subtree this is your right sub tree from this left subtree you are getting some negative sum so there is no benefit of considering this negative path just take this only because negative will only reduce your some value we want to maximum sum okay so 0 taking 0 here means that we will not consider this only write also same thing now the sum could be the root Value Plus whatever you get from left whatever you get from right this is what we were doing here right whatever you get from the root Value Plus whatever you get from the left whatever you get from the right maximum sum get the maximum sum and when you are returning so return the root Value Plus maximum of left and right because you have to give to the parent so whatever is the maximum sum in the subtree child subtree give that right so I hope you understood the problem uh o of n is the time complexity we are doing a single traversal okay and yeah if you found the video helpful please like the video subscribe to my channel if you have any doubts let me know in the comments and thanks for watching bye
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root. The **path sum** of a path is the sum of the node's values in the path. Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 6 **Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. **Example 2:** **Input:** root = \[-10,9,20,null,null,15,7\] **Output:** 42 **Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. **Constraints:** * The number of nodes in the tree is in the range `[1, 3 * 104]`. * `-1000 <= Node.val <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
112,129,666,687,1492
3
I will come in this edition they appeal to discuss about one of the common interview questions friends this question bill out at least five times and top-10 interview given input times and top-10 interview given input times and top-10 interview given input singh identified length of the longest subscribe according to must be without any rippling character zara cloth examples For example the reader in here a b c swaroop shivling without any characters similarly bca like subscribe along it's something rank spent in this example the longest serving intestine repeated with example person and longest subscribe i saudi answer woman or me to identify the like this problem substance solution Stuart Broad This Problem But Will Discuss Various Liquid Sliding Window Based Approach Paris Of Inputs And Jerry Index Is Mask Andar Top 10 Will Have Two Point Five Because I Will Be Representing 10 Top 10 Sliding Window And Jet Will Be Representing Ten Sliding Window Will Points Subscribe Without Any Repeated Characters Subscribe Window Will Be Subscribing Link Initially Both IS And Will Be Point *Indicates 0f That In Iteration Will Increase The Valid Notes Will Keep Adding One Character Internet Sliding Window In Which Direction Which Will Form A Sub Strength Will Fight for elections and in such a situation even encounter animated character I will be changed only when contacted animated character interest sliding window will be amazed and index of repeated character list a distinct and experiment and logic will be taking a map for the character that scene In which all say will declare available for the length of the thing in which direction software name is science an initial 1200 initially both in the appointing 201 depression like this point mintu character subscribe and not present computer era of your is aa j value se 0512 Size Want That Boat Store Character Interment Razor Storing Index 1208 Will Toe Current In Na Exclusive Way Will Strive Doing This Little Letter Internet Station J One Point * Little Letter Internet Station J One Point * Little Letter Internet Station J One Point * Indicates Character Same Process Vidmate App Will Reach Computers Want Na Sliding Window Character Subscribe Chief Tom Subscribe 108 102 Subscribe Should Be Updating Computer And That In Front Value Will Update With Maximum Benefit Saw This A Mac One Earning ₹2 Chu Boat Will Update Inter Mac One Earning ₹2 Chu Boat Will Update Inter Mac One Earning ₹2 Chu Boat Will Update Inter Map With Special Needs In Its Current Inductive Will Give Which Actions In Nation Will Be Two Characters Paper Edison President 610 Sitam App not installed Subscribe And Will Se Max To VIP End Finally Bigg Boss Left CA Inter Map Current Industry Situation Different Subscribe Cr Reddy Inter Map Depend Value Will Be Co Electrician Job Will Appoint Leaders Not Exist Hair Kind Clear Buffett will to enter into the next generation Will be appointed to intense pain Already present its time to update your value on and initial discussion Will receive new updates Will be equal to a maximum of current well Wishes for 100 I will be updated Vaikunth point with oo I Just Before Adding Inter Map In Such Cases Will Be Appointed To Character C Which Will Result In Duplicate Character Industry Leaders In The Year In Preventing Bike 150 Wedding Inter Map Justice That Duplicate Character Late Computer Science Jewelry Phase 351 Stree Is 111 Quality Maximum Of Five Thama 3225 Noticed Sliding Window Have Only Three Characters But Subscribe 500 Fuel Subscribe Last Wicket Next Subscribe Now Will See Inter Element Peeth President And Different Activities In The World Will Be Updated With Sticks That Internet Station JV Point *Indicates That Internet Station JV Point *Indicates That Internet Station JV Point *Indicates Character See Next Stitch Already Present in the map Vittori Computer Value Is Equal To A Maximum Of Its Current Value Which Is The Best App 200 Districts Minute Update I Pointer Share Subscribe And The Appointing 60 Plus One White Maximum Of 0535 Exclusive Five Eighth August Inter May Free Computers Pay Subscribe Button Anil Jain Riches And You Will Notice All The Best All Created Things Which Will Return In Which Is The Largest Subscribe Button Click Ho Ki Main A Character In Teaser A Map Quarter New Face Man E Will Declare Aware Total 10 Science And Final Result Quarter Heroes And Will return the value of a literate and processes character int i quarters amazon half aa j electronic input blank co z plus abs cars in the map and note input well half withdrawal equal dot maximum current input well half withdrawal equal dot maximum current input well half withdrawal equal dot maximum current actor will oo will get in do subscribe the Final Result A Rebound Method 8 Maths 8th Previous Value Final Result Kya Maje - Festivals and Maje - Festivals and Maje - Festivals and Main Finally Add Character Inter Map Duck Points Input Director Know Z Plus One Middling Notification Avoid Subscribe Rang Jhala Ne Virat Ka Output End Brothers Saeed Akhtar Lajjit Stuff But after defeating characters in inch input thanks for watching please do you like the video and subscribe to
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,684
let's solve lead code 16864 count the number of consistent strings so the question gives you two inputs first is allowed which is a string so allowed for example could be something like ab and it will be a string of unique characters so there won't be any repeats on this something like a b c d there cannot be another A or B or C or D so it will be a string with unique characters and then there are there is a array that they providing a list and this list includes several other words something like AB or A B C D or B C D A or h g j a so something like this right so you need to return the number of return the count of words within this right so these words can have duplicates as well something like this right this can have duplicates like this and you all you need to check is how many words out of this in this list are such that which are made up of these Char some are all of this character remember some or all of these characters which means that this is a valid string that is that I'm comparing so I'll consider this as one because it is using A and B out of these a b c d this is a valid string it's using all of it this is a valid string also it need not be in the same order so this is also valid string it is made up of only these characters this is not a valid string h g j are not part of this a is part of it so this is not and G is not again because there's no G in this so I'll add a top so it gives me three so I'll return three okay so that's what the question says now how will I enable this let me comment this out and write the code so I'll do the same so what I was doing is I was checking with each one of them and giving it a count of one or zero right and if it is not matching than zero if it is matching than one and if and finally sum it all up and return it right so the same I can do so first thing first what I'll do is I'll change allow is a string so I'll convert that into a set okay so that I can easily do operations on it you can look up into a set in order of one you know in a constant order so that's why it's important to convert it into a set if I don't convert it into a set and look up the characters directly in the string that will be order of n every time for each character it would be order of then what will I do I'll create a variable count set it to zero okay and I could do for word in word words for each word okay what I'll do I'll create a set of it set of word okay I'll take this word and create a set of it so it will create an uh create a set uh like this it will create a set of a comma B right for the second one it will create a set of a comma B comma C comma D for the third one again it will create a set of ab C for the fourth one it will create a set of hedge a h g j and for the fifth it will create a set of just one character which is so it will take unique characters and create set is nothing but a set collection of unique characters Al so it will take the unique characters and then I can compare this with it should be less than or equal to allowed which is also a set okay so this operation what it does is it checks if all the characters in this are a subset of this right it may not be exactly if I do dou equal to that will say that they should be they should have all those characters that are there in this not even one character extra or less but if I do this which means that this is this has all the characters from this are part of this and may not necessarily be entire so and so here when this is a set of a comma B comma C comma D so which means that this is less than this AP is less than this right and this is equal to this right so I'm doing here is using less than or equal to but this example h g j a this set ah GJ this is not a this is neither less than or equal to this because it has cut characters which are not in this set okay so if this condition holds true then I'll increment count and finally return it right let's run this and see it worked 175 milliseconds let's look at the best solution here they are using the same methodology in the other way around they are basically finding all those which do not which are not part of a which have some letters which are not part of alloud and they're taking that count and then finally subtracting it from the length of words so that gives them all the words which are part of alloud okay I could simplify this code in this example that we saw so what I could do is I could say if set of word is less than equal to allowed then I'll return one else I'll return zero and I could remove all of this I could remove the count and take a sum of it okay and return the Su simple as that so this entire discussion that we had so it will go through each word return the word will be compared with allowed and if it is less than or equal to it will return one else it will return zero and finally I'm taking a sum of all the ones and zeros and returning it let's run and see and that worked let's submit it and that work 167 millisecond better than 80% of sub
Count the Number of Consistent Strings
find-latest-group-of-size-m
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\] **Output:** 2 **Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'. **Example 2:** **Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\] **Output:** 7 **Explanation:** All strings are consistent. **Example 3:** **Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\] **Output:** 4 **Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent. **Constraints:** * `1 <= words.length <= 104` * `1 <= allowed.length <= 26` * `1 <= words[i].length <= 10` * The characters in `allowed` are **distinct**. * `words[i]` and `allowed` contain only lowercase English letters.
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Array,Binary Search,Simulation
Medium
null
1,003
hey what's up guys so let's one over three check if a word is valid after substitutions so given string s determine if it's valid so string s is valid if you're starting with empty string and you can form a t into s after performing following operations so basically you will have the string called abc and you can add any uh left and right and compose it with abc okay uh properties is hard runners that baby see example so aabc a bcbc right so you can take abc and you see abc all right so you can take this and use abc and for this one you can say bc abc so these are all okay and then for this one right you get the same thing right you can you once you take abc out and you see another abc and it is impossible because if you take one abc out then cba cannot force babc also uh there's no if you take abc out you get cib okay so you get the answer right basically uh whenever you see abc you just mod up right so while abc s you just mod up and uh finally if there's some remaining that means they're on our way bc i know if you see that means you don't you can know you don't you cannot do anything right so you should return to false if it's empty that means you can keep using abc so return true okay so that's it so this is a very simple question okay see you guys next video
Check If Word Is Valid After Substitutions
minimum-area-rectangle-ii
Given a string `s`, determine if it is **valid**. A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**: * Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**. Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`. **Example 1:** **Input:** s = "aabcbc " **Output:** true **Explanation:** " " -> "abc " -> "aabcbc " Thus, "aabcbc " is valid. **Example 2:** **Input:** s = "abcabcababcc " **Output:** true **Explanation:** " " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc " Thus, "abcabcababcc " is valid. **Example 3:** **Input:** s = "abccba " **Output:** false **Explanation:** It is impossible to get "abccba " using the operation. **Constraints:** * `1 <= s.length <= 2 * 104` * `s` consists of letters `'a'`, `'b'`, and `'c'`
null
Array,Math,Geometry
Medium
null
17
hello everyone welcome back here is vanamsen today we have an exciting problem to solve it's called letter combination of phone number and guess what we will not only write the solution in Python but also share implementation in various languages in the description below so let's Dive Right In imagine you have a old-fashioned telephone keypad have a old-fashioned telephone keypad have a old-fashioned telephone keypad and you want to find all the possible letter combination for a given number just like texting with an old-fashioned just like texting with an old-fashioned just like texting with an old-fashioned phone so we will be using python to solve this problem and I will be guiding you through step by step so for example given digits two and three we need to Output all combination of letters so first uh think we will need a mapping between the digits and corresponding letters just like on the telephone button that's where our phone map comes in and then we will use technique called recursive effect tracking to explore all possible combinations so sounds fun all right so let's code first let's handle the base case if the input string digits is empty we will simply return an empty list and then we'll create our phone map and this will map each digits to its corresponding letter for example two maps to ABC three maps to DF and so on so if not digits return empty and phone map will be 2. 3 DF or and five six seven eight nine and yes so uh next we will Define a recursive function called backtrack and this where the magic happen we will explore each digit corresponding letter and recursively build the combination so now let's look at the heart of our function so the backtrack function and this recursive function is where the real magic happen so I want to spend some time breaking it down so why recursive backtracking well recursive allow us to explore all possible combination by dividing into each level of choice and it's like navigating a tree where each node represents a choice and we want to explore every possible branch and backtracking on the other hand allow us to go back and explore different path when we hit a dead end so let's implement it Dev back track combination next digits and if Len next digit equals zero output append combination else or letter in phone map next digit zero backtrack .com plus letter next digit one so this part checks so length 0 and this part checks if there are no more digits left to explore and if we reach the end of the digits it means we have a complete combination so we append it to Output think of this as reaching a leaf in our tree of choice and then we have a backtrack combination plus letter next digit from one so now here's where things get interesting if there are more digits to explore we look at the first digit in next digit and find its corresponding letter from our phone map imagine the current digit is 2 that means we have three choices a b and c and we will explore each choice one by one so we add a to our current combination and call backtrack with the new combination and the remaining digits so we backtrack all right b instead and again call backtrack so finally we backtrack once more time and add C and call backtrack again so this Loop continue recursively exploring every possible combination for each digit it's like navigating through every branch of the tree ensuring we don't miss any possibility and finally we call our backtrack function with empty combination and the given digit and return the output so output will be this backtrack empty digits and return output and recursive backtracking is a powerful and elegant way to solve this problem and by understanding the logic behind the backtrack uh function we can appreciate the depth and efficiency of the solution so let's uh run it so for given test cases to free all looks perfect so we can also run it for and syntest cases so let's see and yeah so our implementation bit 68 with respect to uh runtime I think if we rerun it might be a bit different so let's see so yeah now it's uh 81 uh milliseconds and I have even 34 with the same implementation so probably the test cases are quite different so I reach even 96 of bidding at 34 milliseconds but the logic is the same and that's it we have uh implemented recursive back tracking solution to find all possible letters combination of a phone number and you can find the codes in other languages like C plus Java rust and more in the description below and I hope you found this tutorial and lightning and if you enjoy it don't forget to hit the like button subscribe uh ring the notification Bell for more exciting cutting content tutorials and much more and leave a comment if you have any question or suggestion for next uh video until next time keep coding keep exploring happy layering
Letter Combinations of a Phone Number
letter-combinations-of-a-phone-number
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. **Example 1:** **Input:** digits = "23 " **Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\] **Example 2:** **Input:** digits = " " **Output:** \[\] **Example 3:** **Input:** digits = "2 " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `0 <= digits.length <= 4` * `digits[i]` is a digit in the range `['2', '9']`.
null
Hash Table,String,Backtracking
Medium
22,39,401
17
hello guys now I would solve the letter combinations of a phone number let's do the problem statement first given a string containing digits from 2 to 9 inclusive return all possible letter combinations that the number could represent a mapping of digits are two letters are like under telephone patent city even below not that one turn on map to end letters they see the example input her two three I will return the ad a EF V D and so on so forth we are given two and three and there is the three choices of the two and there is spiritual all the three so we come every I will choose one from this is three there is an N choose one from there it can letters so basically we see the backtracking program because we should exhaust all the possible combinations let's do it so basically the time complexity will be the expec exponential because we for further lands of their time complexity will be the three chooser last older serve letters I have three choices and time so for chooser numbers of their better the number could have four choices because they're seven and nine may have four choices of the best suit in either the least solution without our result release a register and to educate track is the given T treats dollars equal to zero or some countries there we have cat the mapping of their number to their letters maybe zero mega to empathise 3 and warm air to emphasis tree under to metro ABC 3 mm to t EF and the form M 2 gh I unify map to j ka oh and there are six map to M and oi7 map to PQRS 8 am actually tu v 9 X to W X Y Z again we will use a help function because then I can carry more parameters finally we return the result I will kill the pyramids afterwards okay that's the first serve right to the help function let's think what appearance do we need the first we need our string next I wish the result now also we needed a current street and there we also needed the string ages of course so we need other mapping and we also need an index because we want to know where we are in the digit string and is the okay then best case basically if for we reach the Ender which means we have chose older choices we should have added a culture stirring our result list so index is equal to the teaches tolerance where is either the current string will return and there else that will be our recursive situation well first get cancels our number because we are given a digit that is drink right so we get it out to a character and a convert out treat digits charge adds her index and their - 0 then we can in integer and their - 0 then we can in integer and their - 0 then we can in integer and also we will get their candidates which means water the representation of data number mm camera present oh yeah repeat what letters can this number represent there will be mapping position there now we will try every possibility for into I go to 0 I left it can be the starless and I plus I use the help function and a result curl with class that can be sitt substrate I then digits and mapping index that's all the reason out iostream because if I a stringbuilder oh sorry I forgot to fill this parameters without her curries empathy and the third victory and real that I use the string no distributor because if I use string builder I should have first appendix Eric tenders yeah I should have said to the lens 2-1 so is a should have said to the lens 2-1 so is a should have said to the lens 2-1 so is a little bit of annoying so adjuster as data in the function data I will not have to choose untruth it's a will be much easier so okay happy coding thank you for watching
Letter Combinations of a Phone Number
letter-combinations-of-a-phone-number
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. **Example 1:** **Input:** digits = "23 " **Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\] **Example 2:** **Input:** digits = " " **Output:** \[\] **Example 3:** **Input:** digits = "2 " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `0 <= digits.length <= 4` * `digits[i]` is a digit in the range `['2', '9']`.
null
Hash Table,String,Backtracking
Medium
22,39,401
1,704
hey everybody this is Larry this is it the first day it is of the December the code day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's bomb we'll be doing the December things or month because I don't know we've we have a big street going so it's not gonna stop here uh yeah uh today's part I miss 1704 determined with string halves are alike so basically you have a string as of evenings but this string into two halves of equal lengths a they're like if they're the same number of valves uh AIU and okay we don't shoot their like what does that mean uh or like is it just wow it's like it doesn't matter which one right so a and okay not just oh all right well uh I mean I think you just count the number of aeio's right so um as lower uh for I don't know I mean we could probably do in a better way but if x is in aiou um count increment by one and then return count to zero right I think that's pretty much it you're probably right in a better way like some if or something like that um oh snap did I messed it up oh they have to be gig of links okay so I must read this one whoops um that's what I get for being too fast and it happened to work on the tax cases now because uh when I thought I missed the two halves or I missed the equal length spot so um the reason why then that's why I wrote it this way right because um if there was no if the link doesn't have to be equal then you could do a pigeonhole thing where if it's odd number of um odd number of vowels then you can't do it if it's even then you can always there's always a point in the middle but I think I just missed what the equal length support this is why don't they just give you two uh two strings this is kind of weird but okay fine um I don't know so yeah so you can do something like cam Wells um s right something like this um and then just do something like return cameras um s um plus one or minus one I don't know is it always even length it is even like okay so I don't have to worry about it um foreign this is what I get for not reading no problem I guess uh yeah just right let me oh it's just being too fast to be honest uh if I could have done it uh all right let's give it some it yeah okay it won't answer last time too or two times ago what did I do hmm oh I didn't do the lower no I did oh I put n is equal to oh because I didn't set S as you go to lower so again and maybe this one is a little bit deceptive and that I apparently I made two silly mistakes in the three times I've tried this even though it is a very easy problem I hope no one else have trouble with it if you do have trouble with this let me know um but yeah I mean I think I just missed oh I miss we I missed the part about Jacob length so I just thought that you know and I did a reduction in my head and I was gonna explain it but well I'll explain it for another one um this is gonna be linear time constant space obvious reasons I don't know if I have to explain this one so yeah let me know what you think um like I said would be to here all month so stay good stay healthy take your mental health I'll see y'all later and take care bye
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
724
hey what's up guys think whitey already you're talking coding stuff on twitching YouTube check the description for all my information I do the premium problems on my patreon for two bucks and you can join my discord I'm building a community here if you message me I try to respond to everyone this is fine pivot Index this is an easy problem very easy one of the easiest on leak code I think given an array of integers nums write a method that returns the pivot index of this array you might have heard of pivot if you know a quicksort is if you don't they give you a definition of what pivot is in this case here we define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right if no index exists we should return negative 1 and there's multiple pivots we should return the leftmost one okay great so what this is telling us is let's look at an example we give it an array of numbers in this method that we're implementing we're trying to find the pivot where the pivot is you know in this case it says index 3 it's an index so 0 1 2 3 this is the pivot in this case and they're saying the pivot is the index where the numbers to the left all these numbers summed add it up is equal to the numbers to the right summed and add it up so we could see the numbers to the left 7 plus 3 plus 1 is 11 in 6 plus 5 is 11 so that is correct okay in this case there's nothing there's no pivot so negative 1 now how do we do this well you should think it's pretty easy honestly it's not too bad like let's think about this like if you look at these numbers like how are we gonna if just looping through like you can't just go ok 1 plus a is a how and then you can't just check if that's equal to this right we don't know anything about these numbers so I mean you could do a double for loop so you could like loop the reach number and then like loop through the array again and check but like that's pretty stupid when you the obvious thing is probably just get a sum first right so you want to sell them all the elements so you loop through once that's just a linear loop so you loop through and you go ok 1 plus 7 is 8 plus 3 is 11 plus 6 is 17 plus 5 22 plus 6 20 boom not 28 you know the some of it now okay let's loop through it again now we already have the sum is 28 let's keep a left cell now left on the zero and let's check the current element if total sum minus left's on - current element is minus left's on - current element is minus left's on - current element is equal to left sum and then that will give us the answer so we just do ok let's check this nut let's check we have zero this is the main condition right here I don't know if I have to explain this to you but total sum - left explain this to you but total sum - left explain this to you but total sum - left some - nomes of I equals left sum if some - nomes of I equals left sum if some - nomes of I equals left sum if this happens we found the right index because if 28-0 because if 28-0 because if 28-0 which is the sum right now - 1 so 27 if which is the sum right now - 1 so 27 if which is the sum right now - 1 so 27 if 27 is equal to 0 well then that means that all of the numbers to the right are equal to the numbers to the left but that's not true that would mean there is nothing here right if we saw this one and there was a zero here then that would make sense because the left sum is zero the numbers to the left of 1 equal to the number of the right you know like in this case right you know like whatever but I don't know that was a bad example but what am I talking about here whatever dude basically what you're gonna do is you're gonna check the current number isn't a part of the left or the right some so you're gonna check the current number first and you're gonna say if the left and right aren't equal then you're going to add it on so you're gonna say 1 and then you're gonna say 8 and you're gonna check this condition every time and you're gonna say ok then you're gonna say 11 and then you're gonna say okay total sum minus 11 minus 6 so 28 minus 11 is equal to what is equal to 19 or someone like that maybe no 17 right 17 okay and then 17 minus 6 is equal to 11 is that is equal you know and if 11 is equal to than the left and right or equal because we know the total we subtract what we've seen and we subtract the current number isn't part of the sum that we've seen and then we know what's on the right it's pretty straight forward I'm not sure if I'm the best at explaining it but I mean it's pretty straightforward now we'll coat it I should've made this video this long either way anyways I already messed up a few times I always mess up I know I got a stop I gotta get over it I feel like everyone you know let me know below if other people don't mess up at all I mean it might am I just in the worst likely coder or whatever but so just get the total sum not too difficult right you've all done a for loop where you add to a sum get the left some so you go to zero I lost them not once again the same loop we have to check first so we're not adding it on we don't add it on right away because we have to do a check first to make sure that the left and right are not the same already so we have to do okay if you know what are we even saying if total sum minus the left sum that would be the right sum right but we need to exclude the pivot so minus nums of I because it doesn't count for either is equal to the left sum that means they're the same if right sum is equal if right this is the formula for right sum is equal to left sum and we exclude the pivot then we return the index we're at because we found the pivot that was a good explanation there at the end so if you watched this whole long video you know and now you finally get it so sorry I took me that long to finally articulate it correctly and then we return negative one if we don't find anything thank you guys for watching sorry it took so long I know at the end I kind of said that correctly what the help numbers of I minus one oh my god okay you have to add the previous elements sorry dang dude I am The King of mistakes there you go that's you have to do numbers of eyeness one because we skip over it at first so that we could do the check so we add it previously after we already checked it for pivot then we can add it on there you go you should understand now I think I explained it's an easy problem you can look at it and figure it out anyway I'm getting frustrated I'm moving my mic around and stuff please just respect me and you know respect your community and respect your environment so thank you for watching see you in the next one
Find Pivot Index
find-pivot-index
Given an array of integers `nums`, calculate the **pivot index** of this array. The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right. If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array. Return _the **leftmost pivot index**_. If no such index exists, return `-1`. **Example 1:** **Input:** nums = \[1,7,3,6,5,6\] **Output:** 3 **Explanation:** The pivot index is 3. Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11 Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11 **Example 2:** **Input:** nums = \[1,2,3\] **Output:** -1 **Explanation:** There is no index that satisfies the conditions in the problem statement. **Example 3:** **Input:** nums = \[2,1,-1\] **Output:** 0 **Explanation:** The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0 **Constraints:** * `1 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1]. Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
Array,Prefix Sum
Easy
560,2102,2369
371
So hello friends, new day of Blind 75 and today is our 69th day Sam of Tu Inteasers question is easy type medium type but it will be easy because I will explain the logic so it is going to happen so in this we have given two interiors A and B, they have to be solved. Without using Sam, it is okay, so one has two joined three, two have three joined punch, so here Sam has to be done, but this plus and minus operation is not to be done, so what are we going to do and I have talked about it earlier. I have explained it well today, let me explain it again a little, so let's go to the notebook, first offer, so in this question, we have to find the sum of Van and Tu, which is 3. If we cannot get through addition, then we know bitmapulation. If we do the same then what we can do is that we can see the observation that if we sum zero then the answer comes zero, if we sum van and van then the answer comes zero and above if we sum van and zero then it comes different. -If it is a different number then the answer is A. different. -If it is a different number then the answer is A. different. -If it is a different number then the answer is A. If it is a different number then the answer is zero. In which case does this happen? You must remember that it is in the case of tide, first thing, what are you going to reduce, second thing, how to handle the scary thing, this carry also. We have to handle it and why is it not that we are adding to it, we are doing one shift ahead of it i.e. we are doing it on the left side, shift ahead of it i.e. we are doing it on the left side, one thing you are looking at is that 'A' is being added only in the case of Van and Van, one thing you are looking at is that 'A' is being added only in the case of Van and Van, one thing you are looking at is that 'A' is being added only in the case of Van and Van, not in all the others. So, which is such a table? Do you remember that if both of ours are van then we can make it only because of the end, then it means end operation, we will do it in seconds If we If we If we shift to the left side, then one We have understood the thing. Example So, if N is added to the eighth, then what can we do for 1000, 8 will be 123 8910, it is from zero to zero, so what is our answer Correct. So what will we do, now I will see both of them and will continue to do such operation till our carry becomes zero. Okay, let's save it for the last one and shift together. Stop these two. Neither of these two have a carry, see in which car they are coming, just by looking here it is clear that the carry is coming because of the van and the van, if you had put a carry here, then this would have been the case. I wrote ka di and there are two zeros in front of it, there are two zeros behind it, so put carry, zero , different is made again, CMS is zero, 16 8 4 2 1, so 16 + 4, how much is it is 20, 16 8 4 2 1, so 16 + 4, how much is it is 20, 16 8 4 2 1, so 16 + 4, how much is it is 20, if Looking at us here, again the answer code is there, so what will we do, we will make the key in C plus, which will be ours too, so it will be evening, now we have to remove the carry also, so carry is written here, so now I am going to return here. This loop will continue to run and will fix the return for Sam and Carry. If I also tell you what to do, then what will be our base case of initial K for return, if our carry which is or B which is becomes zero, what will be the return. If this happens then a similar case will happen that if the person is busy then the returns will not be given because I had shown you how by doing this, we are doing zero in The Carry, so just run it and submit it and see, you can do it directly from there. Just for today, see you in the next class.
Sum of Two Integers
sum-of-two-integers
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`. **Example 1:** **Input:** a = 1, b = 2 **Output:** 3 **Example 2:** **Input:** a = 2, b = 3 **Output:** 5 **Constraints:** * `-1000 <= a, b <= 1000`
null
Math,Bit Manipulation
Medium
2
35
okay 35th task of flip code to search insert position okay we have sorted array in the new element and we should either find it or we should give a position in which we would insert it so that we can keep the sortedness of the array so this time would use std lower bound okay so sorry the lower bound will give us the position of the first element that is not less than the current target so if it is not less than it means either we have already found it so that is going to be the position itself because we found the target or it is the law the location after which we have to insert it so in both of the cases the returning value is numbers that begin in the same location as such so let's run oops not equal minus okay submit okay and we're done
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
1,884
A Azam is going to call list d4 extra bittu is a st andrews questions statement you are you want to identical addition you have access to now building with and plural form 121 that vinod were juice of lower left strong 90 slide and drop test very Beneficial That An Alarm Clock Set And Billu Slow App Will Not Take Any Movement And Broken And Dropped From Any Elections When Someone To Admire You Can Not Love You Can Avoid However When Did Not Being Human Resource Center Forum Us Written On Winning Numbers Of Units To determine the wishes when the value of our subscriptions, we have to tell the minimum number of which it is, that is, we have to point out that the DMK plot number is to send the minimum number of movements so that both of us remove our egg and mine is the one. That explanation and they have to dorm us this if we had testis given to us number of loss to change then in this we have to take at least two tons to treat that which flourished eye drop back Siddhant Sharma is the worst thing from Unknown number one and all half inch so that we first of all from you people jo point se prince vinod episode 202 ruk agar save my number we need to bring it down us ghr me a b c baat hai otherwise Bebo surviving terrorist To make a prostitute who was followed by which both of them are the most minutes on the same from the same both of them Pune otherwise 0 4 but the cervical friend is a similar abstinence has happened now we understand it through a sketch and do something like if we have that this plot Given minutes, we have given employees and we have to tell which buffaloes, how much minimum number of moons we should take so that the increase in this will be known which red chilli I have given it, if we will not do it on both Androids then like we are here if my The value of these is one, if I have one and we have to find out, you used to try Domax on all the fruits, Kunwar, now these people do business that first from their side, they try it on this fruit with Striker, now it is like this. Isn't it that we are some ware trend, you vote and there is a front part on it, there is nothing like this, you are a network, there is gourd in the market, wed 21 subscribe, this is the noose which is here, if it swells from here, then I am going to subscribe, if I had it, I would Subscribe that my don't do that if I have 2 eggs and to support I have and key value to so thank you to so support I am trying with decisions right now so if I am trying with this loan So I can have only two options here, if I have a particular item, either that exam duck will not break after falling, or it will fly away, if one of mine bursts, to support it, in this case, I only dropped that one and my If one broke, I needed to check for the other welding machine. Solid and on top of that, there is no need to check. Firstly, how did this happen? Secondly, if one of mine did not break, then we know that there will be no break below it. Now we need to check on this, then we must have seen that it is possible that it is a fraud and if I don't have a break, then I will get bigger by adding my answer once, because I took a chance here or click on it with fiber. Even if I try it, we will have to make it, so we are taking a chance on it, only after seeing our size 11, the out will be less but we will take one from me to do this vitamin, please submit your note here. You see in the time manner, hey, if you drop two exams from the floor, if you drop one from any explorer, then you should get Amazon My and Twitter, if my means will be less than 11, then here is a two-man promise. Kaya and support here is a two-man promise. Kaya and support here is a two-man promise. Kaya and support in explorer, if it agrees, I will have to put down The fold is just my is not fair subscribe on top of that and this which after we do this let me take you one step so subscribe me on this side of yours and make it under your control so first of all we always have to think like this It is not that I am first class 10, my one month may be broken, maybe my class is very bad, I have to fry all the rolls, so how in this situation, we have to minimize our max, so basically there is one problem or two in this. So I have a great tax and my A is not making a break. Now please tell me that tomorrow I need the account statement but the culprit is important - attention - please but the culprit is important - attention - please but the culprit is important - attention - please call. How am I depositing both of them right now ? In that we have to take one strip, ? In that we have to take one strip, ? In that we have to take one strip, because we are taking one strip, that's why I am checking on it that the illusion is breaking below, we have to go up, so we will add one on this side in our step, we will see it as body part. We will do it in the same manner by taking the land and then we will mash it, then first of all we pick up a return phone and in it the number of players and the number of unity are two, then we pass it to him, after that we take leave and permission. Let's define it and loot it in front of the country. First of all, we will understand that if we are troubled at home, then we are one because I have saffron in it, so I would have taken it last but I will try to ignore it. I will find out that Must be that one of my pistols and is selecting on this Lokesh Bhai is not doing you direct oil riders function and country but if my Android does not do it Ameer did the same then I add a reminder to take meaning - 102 and table recipe The number is A and while doing this we have to think about the maximum of his account that maybe my condition is bad and we have to check all the plants and after doing this we will add it to A. Because we are taking a chance to check that the withdrawal business and whatever answer is coming after maximizing them, it is clear to us that it is minimized, this is my phone that whatever my dominance we have to remind him of that. After we will return to our dream answer the complaint of this constipation we told that hey I have one leg only one till it thinks that whatever number of mp from plants I have if that then I always and if As for me, I have given as many as two or as many three processors as 321, we will have to take ads on all of them and try to try, if this goes, then if I have one end left, then I need to try all the remaining clothes because in the awards case, we may have All the remixes have to be checked. Let's see the syllabus on the address which is saying that the time limit is exceeded, which side is brother, which picture is sex, then they have seen 220 kiss wrong, e Agri Gyanpeeth type will go to the end that yes, this is correct. Is that hindi mistress is in vitamin c turmeric red chilli a table was fifth floor manager happened i just with sexual force again mesh mean that this i india made in this which request closed organization that and guy a folder answer After all, this pattern mobile religious and 350 Bluetooth on week shoulder 1108 song that this return gift heroic arrangement sentence white laker to half hour time solid to memory soft quarter inch 100 latest quality went back yes I am 100 number of 1200 engineer and Security cutting tax dip length the ripper edifice and definition of birth - but edifice and definition of birth - but edifice and definition of birth - but that you are scientific and after this we have to decide which free computer stage we have avoided then we have to decide if I have answered any other floor worthy already If you have kept it out, then the answer is A, we will return it, there is no need to go ahead and check, you finally give me whatever my DP and deposit will be, now I will match it in my 162 league, on both sides of the road Tags English Meaning of Romance But it is heard that Haridev Shastri had a hint, I am typing in a person after seeing your every day or culture, tomorrow morning I will reply to it as a friend, thank you very much for watching.
Egg Drop With 2 Eggs and N Floors
minimum-changes-to-make-alternating-binary-string
You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. In each move, you may take an **unbroken** egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** We can drop the first egg from floor 1 and the second egg from floor 2. If the first egg breaks, we know that f = 0. If the second egg breaks but the first egg didn't, we know that f = 1. Otherwise, if both eggs survive, we know that f = 2. **Example 2:** **Input:** n = 100 **Output:** 14 **Explanation:** One optimal strategy is: - Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9. - If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14. - If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100. Regardless of the outcome, it takes at most 14 drops to determine f. **Constraints:** * `1 <= n <= 1000`
Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways.
String
Easy
null
42
hi everyone welcome to sudokoda my name is raveena and today we are going to solve lead code problem number 42 which is trapping rainwater so let's start by reading the question it says that uh given non-negative integers representing given non-negative integers representing given non-negative integers representing an elevation map where the width of each bar is 1 compute how much water it can trap after raining so let's see an example here we have been given a list of height where there are all non-negative integers in there and uh non-negative integers in there and uh non-negative integers in there and uh let's look at this height list as you know the height of the buildings okay and then here if you look at this graph you'll see that all these black box uh are the buildings and if it rains heavily uh you know how much water can the can be trapped between these buildings so that's the question so if you see the between these two buildings this uh blue thing here is the water that has been trapped uh between these two there is water trapped in this t-shape and there's trapped in this t-shape and there's trapped in this t-shape and there's a small petal here okay so how do we actually uh you know count the number of units that have been stored right so uh you'll see that each building is of one unit and if you look at it you know uh between these and this building there is one unit of water stored because it's off with one and then the height of it is one so it's actually one if you come here if you drop boxes around this T you'll know that you'll understand that there are actually Four units of water here one two three and then the bottom one which is four and then there's one right here so how many it is one four and then one which is six and that is our output so this is I hope this question was clear and let's move on to the notepad and see how we can solve this okay so I have taken an example the same example where I have the height right here and then I have drawn the graph okay so uh how I'm gonna solve this problem is by having two arrows with me a left Max array and a right Max array now what are these arrays so the left Max array is going to determine how much maximum water can I store when I go from left to right and the right Max either denotes how much maximum water can I store when I go from right to left okay and then once I have those values what I'm going to do is I'm going to take the minimum of the 2 and then you know uh subtract the height from it now what does that mean so for example so when you come from right to left suppose your maximum height is here and when you go from left to right the maximum height is somewhere here and if we want to calculate the amount of water that has been stored right here in this particular unit so what's going to happen is you're gonna be subtract you're going to be taking the minimum of the two because the amount of water that is that will be stored will be based or if there is a building that is you know that is smaller than the bigger building then the water store will be dependent on the smaller one and that is why we are going to take the minimum of it and then if that's true then we take the minimum fit minimum of it and we see that there is water stored here but you will see that there's a building right here so we have to subtract the building as well so that's an overview of the problem let's really see how we can solve this so the first thing I have I need is my left Max array okay and how I'm gonna calculate it the first thing I need to do is initialize it with 0 so I'm going to initialize my whole thing with 0 and then I am going to have the first element of my array as the first element of my height so I'm going to take the first element as 0 why because there is nothing on the left hand side so ah for the margin I need to have something solid on my left where I have to start from and so I'm going to take the first element of my height now I'm gonna calculate it I'm gonna calculate the left Max area is by taking the maximum of the current height of the building and the previous height of the building so since I am calculating the heights as I'm moving forward from left to right the previous height will be from my left Max array and then I am going to take the maximum of my left Max arrays previous height and my current height so let's see so I'm going to take maximum of 0 and 1. so maximum of 0 and 1 is 1 so it becomes 1. now I take a maximum of 0 and 1 again the maximum is 1. I take maximum of 2 and 1 which is 2 so it becomes 2 maximum of 0 and sorry 1 and 2 is 2 then I again take maximum of my previous uh building and then my current so 0 and 2 is 2. now 2 and 1 is 2 maximum of 3 and 2 is 3 2 and 3 is 3 and then 3 and 1 maximum is again 3 and 2 maximum is 3 and then 1 and 3 maximum is 3. so I've calculate my left Max array it's basically maximum of what is the current height and the previous building based on the maximum array that I'm calculating so that is my left array now let's talk about my right array so I am going to initialize my right array and what I'm gonna do I'm for my right area I'm gonna move from right to the left and for the right hand side I'm going to initialize it with the last element of the height similar thing that we did with the left array since we did not have anything on the left we took the first building now since we don't have anything on the right we will take the first value from the right now I'm gonna do a similar thing I'm going to take the maximum of the building on my right and the current building so let me get rid of these markers here okay so I'm going to take maximum of 1 and 2. what is that is 2. now I'm going to take maximum of 1 and 2 which is 2 maximum of 2 and 2 is again 2 maximum of 3n is going to be 3 maximum of 1 and 3 is going to be 3 0 and 3 is going to be 3 maximum of 1 and 3 is again 3 2 and 3 maximum is 3 0 and 3 is maximum 3 1 and 3 is maximum 3 and lastly 0 and 3. the maximum here is 3. so now I have my left and right array what I need to do next is to calculate my answer now let I'm gonna quickly draw and show you what the left and Max left Max and right Max is really okay so uh let's draw the left Max array first it's starting at 0 okay it's going to one cool it's staying to one okay and then it's going to 2 and then it's staying two for four blocks and then again it goes to three and then stage 3 till the end so this is what the left Max array looks like now let's draw on the right Max array actually starts at three oh sorry my right my side actually starts at one so one and then it goes to two so it goes to 2 and then stays for two for three instances and then it goes to three and then it stays three till the end so it stays three till here okay so let's see what's happening my left Max is the one in purple my right Max is the one in Orange now if I have to calculate how much water is stored what do you think I have to do uh if you'll see that sometimes the orange marking is the one that is closest sometimes the purple marking is the one that is closest so what do we take the minimum of the two when we take the minimum of 2 we will be able to get to the lowest line and in order to calculate the water so for example let me do this let me draw it out so this is my or the orange part is my uh left may I write Max and my left Max if I take minimum of the two I end up with my purple line okay so I end up with this particular block here okay I'm getting very bad at this I'm getting this particular block here does that mean that this is all water um no why because this there is a building here it's right here this is the building so what we have to do is we have to take minimum of my right and left and then we have to subtract the height of the building so if we do that then we'll see that there's water here which is actually the correct thing did you saw that t thing in the example below that's the left part of it so this is going to be the water and that's how the formula works so what's the formula initially my formula is going to be my minimum of left and right and then I'm going to subtract my height so initially my answer is going to be 0 and my answer is going to be 0. and now let's work through it so it's going to be minimum of left and right so minimum of 0 and 3 which is 0 minus the height which is 0 minus 0 minimum is 0 and 0 minus zero is zero so it's gonna be zero okay so minimum of 1 and 3 is 1 and the height of the building is also 1 so 1 minus 1 0 okay now minimum of 1 and 3 is again 1 but this time the height of the building is zero so one minus zero one so I'm gonna add one now minimum of two and three is two and then minus two so two minus 2 is 0. okay so minimum of 2 and 3 is 2 minus 1 so it becomes one okay plus minimum of two and three two again and then minus 0 so it becomes 2. minimum of 2 and 3 is 2 minus 1 which becomes 1 so this becomes 1. minimum of three and three is three minus 3 0 so it's becomes zero now minimum of 3 and 2 is 2 minus 2 0 minimum of 3 and 2. is 2 minus 1 is actually one so one now minimum of 3 and 2 is 2 minus 2 is 0 and the minimum of 3 and 1 is actually 1 and minus the height which is 1 so 0. so let's see what our answer is it's one plus one two plus two four plus one five and then six so our answer comes out to be 6 and that is what we are expecting that is the solution so I hope this explanation was clear let's see how we can convert this into code first things first though we have to look for any edge cases now this problem did not talk about the constraints where you know length of the height cannot be zero so first thing that we have to think is if my height list is 0 then what do I have to return 0 because there will be no water okay so that's what I'm going to do first I'm going to uh actually store my length of height in a variable because I'm going to use it multiple times that is a very good practice that you can do oops I think I'm doing something wrong yeah so there is a best practice that you can do if you are using a variable again if you're calculating something again and again store it in a variable so I have my length n now I'm going to check if n is less than 1 then I am going to return 0. now I have to for uh how many things do I need three things I need my answer I need my left Max array I need my right Max array so I'm going to initialize my answer to 0. my left Max array is going to be initialize to 0 with length n similarly my right Max array is going to be initialized to 0 with length n now I have this I have now I will start calculating my left Max array for starting for starters I have to initialize the first element of a left Max with the first element of my height so I am going to do that I'm going to do left Max of 0 is going to be my height of 0. and then I write a for Loop starting from the first element from the first index going to the end so I do for I in range starting from 1 going till n minus 1 and since it is python it's going to exclude that last part so it's gonna even if I'm writing n it's n minus 1 and then I am going to calculate my left Max of I is nothing but left Max of my left Max of I minus 1 this is the previous building minus my current height okay now that's all my left Max is done let's try it and do it the right part of it so my right Max is uh my right Max's last element is going to be my Height's last element and in Python you can write just minus 1 to get the last element so that's that and then I'm going to write my for Loop ranging from so I have to start with my second last item similarly how for the left array I started with my second item right so I'm gonna start with my second last item here so it's going to be n minus 2. I have to go till zero and since the last thing is excluded last index is excluded I'm going to write minus 1 and for every iteration I have to subtract minus one so that's how you write for Loop in Python and then I am going to do write Max of my I is going to be really Max of my right Max of I plus 1 so maximum of the building on the right and then my height so that's all my right Max is calculated now so now finally I have to calculate my answer so for that I have my I in range going from 0 to n I am going to calculate my answer is going to be answer plus my minimum of my left Max of I my right Max of I minus my height okay in the end I'll return the answer let's see if we can run it okay let's submit okay yeah so you see this solution was accepted now let's talk about the space and time complexity of this problem so uh if you talk about the space complexity you can see that we are using three for Loops here which are not nested they are independent so each time the space complexity is n plus n which is 3n and then we drop the constant so the time complexity of this is O of n now let's talk about the space complexity how much space are we using we have a variable here which is which stores constant and then my left and right Max which is actually an array of size n and what is this n is the length of the height so it's going to be o of 1 plus o of n which is going to be 1 plus 2 N and uh if you know that you know in time and space complexity we actually drop the constants so the space complexity of this becomes o of n if you don't know how to calculate space and time complexity I have created a video on it uh I think two weeks before I will include the link in the description below and you can refer that it will be much easier to calculate space and time complexity if you watch that video so uh to conclude it the space and time complexity of this particular algorithm is O of n if you like my videos give it a thumbs up comment below if you want me to solve any additional problems of your choice please let me know in the comments below you can also connect with me on my Discord and let me know there you want to see similar videos from me please subscribe to my channel uh so that it can give you a notification every time I upload a new view I upload videos every week so have a nice day and I will see you next time thank you bye
Trapping Rain Water
trapping-rain-water
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining. **Example 1:** **Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\] **Output:** 6 **Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped. **Example 2:** **Input:** height = \[4,2,0,3,2,5\] **Output:** 9 **Constraints:** * `n == height.length` * `1 <= n <= 2 * 104` * `0 <= height[i] <= 105`
null
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
11,238,407,756
47
hello everyone welcome to the backtracking series of videos so in the previous video i have explained the permutation 1 problem so in this video i will explain permutation 2 problem and the problem number is 47 so the problem statement is saying given a collection of numbers norms that might contain duplicates return all possible unique permutations in any order so suppose one array is given to you that has duplicate numbers one two you have to find all the permutations like 1 2 will be a result then 1 2 1 and 2 1 so uh in some examples maybe there is no repetitive numbers so that case also 1 2 3 has this many combinations so how is this problem is different from permutation one problem that is in permutation one problem there were no duplicates that's why it was easy to handle but in this case you have to handle the duplicate case also because 1 2 1 all are different combinations how to solve that thing now we'll check but before that i will highly recommend you to go to the video permutation one because that logic is almost similar we will use here let's take one example numbers array which has duplicate numbers like one two three and we have to create all the permutations of this numbers array before that we will do a quick recap like what we did for permutation one so in permutation one we have one array where only distinct values are there like 1 2 3 and we draw one decision tree out of it and this was looking like this so what we are doing for this decision tree so basically what we are doing is first we are starting with one number then that number we are keeping in a list and that list will have three as a length then only we can collect that as a result next time if we have to choose anything then we have to make choice apart from one because one is already taken so that's why we choose between two and three but first time we went with two now we fill the second position also for third position what are the choice left for us that is three because three don't contains in this list but two and one already contents so that's why three was left as a choice for us so every time when we are going forward we are checking that in the list this item which i am going to include is already present or not if it is not present then i will make use of it as a choice so as only distinct numbers was there that's why it was easy for permutation one because in the growing list we were just checking if the current number is already included or not by doing a list dot contents right but the same logic we can't apply here for duplicate case because ultimately we have to make use of all the numbers like 2 1 2 3 in this case if we do a list dot contents then what will happen is suppose first value is there and if we check that other values we can include or not this one we will not take because this list already contains one so that time we have to omit this one but that will produce a wrong result instead of that what we have to do is we have to keep count of all the distinct numbers and we have to check like how many time i have used that one if they have still count then i can again make use of that suppose for a growing list i have used one once that means next time again i have choice to use one two and three because one is one time used still i have left one so when that will also be used so after one i have used another one that time one is already fully used so that time i have a choice to use 2 and 3 because they have count still greater than 0. so what kind of data structure will help us to keep the distinct numbers and their count obviously the choice will be a hash map so we will take one hashmap first and we will build this map like what are the distinct numbers are there and how many times they are available then we will do our decision tree and structure it that we will see next so now we will tackle this problem so numbers array from there first i created the map where it is saying what are the distinct elements are there and how it is their count so one is present two times two is present one time and three is present two times so if we start from here the decision is we can use either one two and three so i can start with one or i can start with two or i can start with three let's say first start with one then in the next level what are the elements i can use so if i already used one then that will be reduced by count one so it will be now one now i have to check how many other possibilities are there which is greater than 0 all are possible because everyone is present greater than 0 so from here i have taken decent to use either 1 or 2 or 3. now let's say i started with another one then what are the choice left so this one will become zero because this is fully used so next time i have choice only to use 2 and 3 because they are greater than 0 so i can use 2 or 3 let's say if we started with 2 then what will happen 2 also i have to reduce so it will become 0 now what choice i have only i can use 3 so i have to use 3 here then 3 will be reduced to 1 now next what choice i have which one is greater than 0 only 3 so i have to take another 3. and as the count is now five so we collected one result and that will be one two three right now how i'll get the other combinations so now we have to check that from here we don't have anywhere to go so we have to backtrack here also no other junctions created so we have to backtrack to here till and while we are doing backtracking from here onwards i have to go to the other part so this two three and three will be again available so i have to like put it back right so this is where backtracking work also so now i have like three two three is there and we have one available two also but one is completely used because one and 1 is already there so second time i can use 2 and 3 again but 2 is already used in this path so i can use 3 here and then as 3 is used so it will be 1. now from here what are the choice left so i can use either 2 or 3. cool if i go with 2 then 2 is used and it will become 0 so after this i have only choice to make as 3. so if you look at now 1 3 2 3 this is also a permutation similar way in this case after 3 only 2 will be remaining so that i can use if you do continuously for the other cases also you will get all the combinations so this is the way we have to use map and we have to decrease or increase the ground to make all the possible permutations while going deep as a dfs if i am going deep that time we have to reduce the counts from the map while coming back or while doing a back tracking so whatever things is again available we have to like increase the count for that i hope you understood this one now we'll see the coding so now here we will talk about the solution is simple maybe it is looking longer code but it is very simple so first what we have to do is this method will be provided to us and we have to additionally write one method for doing the dfs call so first what we will do is we have to define a list of integer result because that is our return type and then we have to define a map as i told and in the map we have to take all the distinct numbers and their count so this is a very common code used in every program right to take the number and its count now we have to do a dfs call where i have to pass the numbers array then the result and the new error list and map so if we look here uh this numbers array only we are using to take its length so you can directly pass the length also no need to pass the whole number sorry now what we have to do is in the dfs call what we are doing is the best condition to stop it is if my list size is equal to the numbers.length numbers.length numbers.length that means we completely grown one result then we have to collect that as a result and as a new error list and we have to destroy the like link or reference because java is passed by reference now what you have to do is we have to iterate over every key so we are iterating on the map for every key so we are getting the key and value out of the set entry set and you are checking if the value is greater than 0 or not that means for this particular number is there any count left or not if it is there then we are adding it to the list which is my running list where we are collecting the current result and then we are doing a map dot put the value minus 1 that means we are reducing that as a count because just now we use that one and we are doing again a dfs call to go to the next level and passing the same things after finishing the dfs call when we are coming back or doing a backtracking that time we are removing that element means the last element from the list and as well as we are increasing the count also because now that particular number is again available in the map so for that key we have to increase the count also by 1 and then if we do this thing repeatedly or recursively we will get all the combinations that we have to written as a result now if we submit it is working thanks for watching
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
901
hello there so let's look at the today's legal in China question it's called online stock span we need to implement a class stock spanner which will be updated with daily stock prices and after the update you will be able to return the span of the stock's price of the current day the definition for the span is as follows the maximum number of consecutive days starting from today and going backwards for which the price of the stock was less than or equal to today's price but that's quite a mouthful so let's actually just maybe draw a picture about actual changes in the stock price to work on a few example to see what you get and what you can actually it's mean what actually means so we're gonna use the horizontal line to indicating the phase so they want a two days three something like this maybe the stock price is rising in the beginning and until day four is also it's always increasing then maybe they find it starts the job to a sudden job to some lower number than day six it's kind of stabilized and day seven is on the rise again now let's think about if we just update it at a seven we want to calculate this span it's basically if we put a vertical line here ignore the stuff on the right that's not counted because we haven't see the new days yet that's in the future we're just looking the left and we want to also pretty much draw horizontal line that's separating this today's price with the price that's larger than today's price just go towards the left and count how many of those little bars we can have before we find a price that's a higher than this horizontal line so we find that we can count three so we turn three for this given day so then let's just looking at another example maybe we continue on this stock monitoring the price of the stock for the 1/10 date night where the price just the 1/10 date night where the price just the 1/10 date night where the price just keep rising so for day eight the vertical line and the horizontal line would look like this so if we call into the number of little bars before we find something that's above the line will be four so if it has the span of the price for the day eight the span will be four let's just look at one last example let's say that we have really good quarterly reports the price on day nine goes very high and so for that reason the bar would be even above this that means it's pretty much above anything then we count the number of bars towards the beginning so it's a one two three four five six seven eight nine so then we return nine so that's what the spamming it's basically having today's price as a cut off and looking towards the left until we find something that's higher than the cutoff we count the number of days in between that's the definition for spam so we have a little bit understanding about this if we look at pictures this is a little bit mouthful the example we have 180 60 70 60s 75 80 85 so it's decreasing going up so we can actually have something that's interesting on the day for here and going down again the pretty much resets because 70 there's nothing because we have something that's above the line on was settled by 70 so this resets to 175 the bar rised of higher so we can actually take three and if 85 that's higher than the this five so the total is six so the answer for this example is one two one four and six so that's the answer for this example so I guess the book for solution is just going to be keep the whole thing and whenever we insert one thing we just look back until we find some price that's higher than today and just we just returned the number of elements so we look back to two as the spam that's just using the definition it's going to be slow because if we have a lot of stock prices numbers like huge numbers with potentially a lot of abundance every time we have to look back it's going to be worse it's not good so we need to something smarter so let's look at the picture again so if we are at a day nine there's something that the day eight can provide us that can ease our effort into looking back all the way day by day so there is actually something that we can do we can basically and they aid we summarize the despair for day eight and also the price for day eight so that's just because if we ever to have something that were actually used is three days front day six to the eight to form a new span that this price is going to be at least a higher than or equal to day AIDS price so instead of the keeping track of these three values consecutive values for six to eight we can summarize that in two you know dates price let's just say it's sweet and we if you have something that's larger than the sweet price that's coming after the date you can effectively just directly add three days and the Skip list three go back to this day five here so that way we can sort of like doing compression along the way we process remembering this prices so another example would be if a day for instead of keeping track of day one day two day three day four we're gonna keep track of we're gonna compress this upward trend to be the first price which is four and actually also have four days for whenever we have a downward trend then we couldn't really compress any more because those downwards are doing resets so for day 5 we're just gonna put five and one so with this we can instead of storing all the numbers in as it is we're doing a little bit compression so that when we look back the calculation can be much simpler so that's pretty much the idea behind this approach so to maintain this compression we can use a stock whenever we see something that's larger than Pryor's day we can basically compress the two days into one thing so just last example we have a one with price one and day two is price two so once we process the day two so initially when we just have they want we just put instead of only putting the single price there we put one and one that's the current span then when they - comes in which has a value when they - comes in which has a value when they - comes in which has a value of two we will pop this out and store to two in there because on day two and the price is two and the current span for that is two let's actually do some dumb words I guess if we have this way to be one again day to day one stuck at they - one again day to day one stuck at they - one again day to day one stuck at they - is this stuck at day three thinks that we are now having a downward they the span the continuously increasing span just to end it there we have to reset so the stack will be two and online so yeah so the idea is just using a stack to keep track of the price Kasturi and we're going to do compression whenever we can when we do the compression is done when we have the current days price to be larger than or equal to a priors day that means we can expand the previous span to be even longer so let's say that just for the sake of demonstration let's say that on day four we have a price that's three we're going to look at the previous current two striking kind of span values it's one we surprise one so we can the first thing we can do is to of course to expand this span here let's say your picture that we can extend this current to span with one day to be two because we now see a price of three then what we can also do is to check on the priors the span which actually ends on something that's lower than the today's price so we can actually combine those two spans into one then we end up with a span with a 5.3 and the four days under the belt 5.3 and the four days under the belt 5.3 and the four days under the belt after that we can continue to process day 5 if the price drop the to the mystic at the file would be the this and - with the current of Spain strike of - with the current of Spain strike of - with the current of Spain strike of value of 1 so that's the image how we maintain this stock yeah so let's just cut this thing up just further for this context let me just call this the spanner which is a museum vector you will store the pairs integer to integer it's gonna be the horizontal line that the park current days price is gonna set on there and the second element is the number of days that's below that line towards the left before we find something that's even higher so that's what this couple here stores in look at this picture so for example here you will be today's price that's this line and how many days towards left we can include under the line before we find something that's upper higher than this so for this you will be the price and number of days or little bars so that's going to be the stuffily we keep on this stock the constructor and this you could just set this to empty and then when we get the new price we would try to do this compression yeah so in the case of its decreasing or well if it's the first day you're going to have a card to strike value off line so that's the default just the thing we need to do is to look after the stack and on the top that's the previous current of previous expand based on this example we see that we can actually do due to compression along with the current value is the prior span then we find the two current span can be further consolidate so it's not a if condition it's a wire condition here so this means we can do some compression the thing we do is to grab the expander the span and then throw out to this pocket events after this compression we can put the consolidator pass on to the consolidated span information onto the staff for the current price and the conscious man so that's the code yeah submit this yes it's working so yeah picture it basically is maintaining for any given day we draw a horizontal line and looking back try to compress everything that's under this horizontal line into a topo with this today's price and how many of those thoughts so this is the stuff that's we put on the stack because all these little individual details after we are passing today is irrelevant the only thing important is just the price and how many little bars under the horizontal line before we find something that's higher so that's the only thing that's important when we recalculate the new span for the following days so the space complexity for this is I guess in the worst case it's all decreasing we're going to have the prize of is 1 pairs of price and one all the way towards the end so it's a order of N and in terms of time complexity it's a I think amortize that it will be one so on some of the days we would just do constant work but on some time some days with when we need to do the compression we have to go backward and can do some consolidations it will be let's say that the worst case will be going down all the way and in the final day we have something that's really high and then the compression will take order n time that's the worst okay worst single operation case because we have to go back and add one more day to consolidate all this top of us on the understand that single operation will take order of an but throughout the lifetime average uses of this operation I think it's a constant yeah so that's the question today
Online Stock Span
advantage-shuffle
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. * For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days. * Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days. Implement the `StockSpanner` class: * `StockSpanner()` Initializes the object of the class. * `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. **Example 1:** **Input** \[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\] \[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\] **Output** \[null, 1, 1, 1, 2, 1, 4, 6\] **Explanation** StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 **Constraints:** * `1 <= price <= 105` * At most `104` calls will be made to `next`.
null
Array,Greedy,Sorting
Medium
null
101
hi there welcome to my channel i'm here to do some easy and medium legal problems and my goal is finish a hundred of them today we have nico 101 so we're gonna finish this today it's symmetric tree so giving a binary check whether it is a mirror of itself basically is if you see a tree in this uh example is one on the top two in here the two in the left side is equal to the two in the right side and the further left will be the same as further right so basically you think it's a mirror in the middle and then they just copy the left to the right side another example is not true when you see this the left note 2 this 2 left is not equal to the right 2 it's right so it will return false this program will return a boolean the first time you think about this question um you would think if this is a note right here so what i need to check if this notes left is equal to this node's right and in this node um we have to also make sure left node's left equal to right nose right in the same time left nose right have to be equal to right notes left so basically the logic of this question so let's code it out first of thing we will need a helper function and helper so the base case of these questions if the root note is equal to no that will return true so this case will cover if it's no it will return true so after this line we'll see the root note is not no so in here though is not no so uh we don't need to check the root node because this is symmetric you only have one the what's next we have to check is return the helper function did is basically checking if root node.left if root node.left if root node.left and root node.right and root node.right and root node.right is symmetric the helper function is checking that and how to do that is and also have some base case so if sorry no laugh tree no right so if tree node left is equal to no and right equal to no return true and if left is equal to no or write equal to no what this mean what it this means is first they check if left or right is equal to no in the same time so when we check in this left three notes three is right here we need to check threes left is equal to uh three is right so this is a if they all node so return true so when one of the node after this condition is done we would we check this uh second condition so either one of them either left or right write is no so only one of them are no that means they're not symmetric so we have to return false after checking those condition so what we need to do is check um and right and helper laptop right and right dot left and that's it for this question uh to explain how that word is in this after all the conditions met so that will oh sorry this missing of lab dot value is not equal to write dot value so also false also return false so in this case we come to your root node right here and we'll check two and this two right two this is the same so they're both not no or their value is the same not the same so it returned false this condition is not met so i have to return lab dot left and right dot right they will check this three and this three are they the same or not so keep recursive and until they find it all the way to the bottom also i have to check lab dot rise is equal to right dot left so we cover all the condition in this case so let's run the test and it's true and also submit this so yeah that's it the recursion method for this solution if you have any question please leave it in the comment section uh please like and subscribe our channel this is really helpful for our channel otherwise we see you in the next video bye
Symmetric Tree
symmetric-tree
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). **Example 1:** **Input:** root = \[1,2,2,3,4,4,3\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,null,3,null,3\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-100 <= Node.val <= 100` **Follow up:** Could you solve it both recursively and iteratively?
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
959
foreign we're given a grid of intense and squares where each one times one square is either a black space or contains a slash or a backslash these characters divide the scores into different regions and the goal is to counter number of cognitive regions in the grid to solve this question we first divide each one times one square into four regions north east west and south the intuition behind this problem is to achieve slashes as boundaries that separate regions for example if a square contains a slash you can think of it as a boundary that separates a square into two parts one containing the north and west regions and one containing the south and east regions thus we can find and merge the regions together when they are separated by different characters if two horizontally adjacent squares both contain slashes we know that each Square gets separated into two parts and thus the east and south region of the left Square will get merged with the North and west region of the right Square in this case the two squares will have a total of three connected regions to accomplish this the best way is to use the unify method Union fan data structure keeps track of the number of connected regions if you're not familiar with Union fine check out the link in the description to learn about how it works and the standard template to import a union file there are many ways to implement unified data structure so you're free to choose any implementation that you feel comfortable with in our code we will store the roots of each region in a dictionary where the keys are the regions and the values are their roots initially each region is its own route when two regions are unioned together they are used become the same we will denote each version of the Tuple IJ direction for example 0 n represents the North Region of the square on the first row and the first column after that we'll iterate of the squares of the group and use the union operation to merge the regions based on the characters given for each square if the counter is slash we connect the North Region to the west region and connect the sound Fusion to the east region of the square I'll see if the character is Black slash we connect the north version to the east region and connect the South Region to the west region of the square else if the character is blank space we can have four Visions together we know that for two horizontally adjacent squares the east region of the left Square will always be connected to the west region of the right Square no matter what the combination of the character is also for two vertically adjacent squares the south region of the top square will always be connected to the north region of the bottom Square no matter what the combination of the character is to get the answer we can count the number of distinct Roots among all regions in the dictionary this is done by mapping the fine operation to all regions in the union fine data structure selecting their unique items with the set operations and finding the length of the set and that's it this is a simple but effective solution to the routine cuts by Slash's problem I hope you found this video helpful thank you for watching
Regions Cut By Slashes
3sum-with-multiplicity
An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions. Given the grid `grid` represented as a string array, return _the number of regions_. Note that backslash characters are escaped, so a `'\'` is represented as `'\\'`. **Example 1:** **Input:** grid = \[ " / ", "/ "\] **Output:** 2 **Example 2:** **Input:** grid = \[ " / ", " "\] **Output:** 1 **Example 3:** **Input:** grid = \[ "/\\\\ ", "\\/ "\] **Output:** 5 **Explanation:** Recall that because \\ characters are escaped, "\\/ " refers to /, and "/\\\\ " refers to /\\. **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 30` * `grid[i][j]` is either `'/'`, `'\'`, or `' '`.
null
Array,Hash Table,Two Pointers,Sorting,Counting
Medium
null
886
so today's question is possible by partition so in this question we have given the set of n peoples and we have to split them in two groups we have given group of people who dislike each other so we have to do is we have to put them in different groups so that they are known in the same group so what can we do so as we have to divide them in two groups we get to know that this is a standard quotient of graph by partition so for example if this is a graph so how can we divide it in two parts what we can do is we take any element and give it a red color maybe and then all its neighbor blue color then all their neighbors red color so we can do it in this way so here we have all the neighbors alternate colors red and blue so if we have this graph we can give the first element blue color maybe then its neighbor a red color then the third neighbor what will we give it blue or red so the conflict arises so when the conflict arises we can say that it can't be by partition or we can group it into two so for example in this case we have given the group of dislikes so one is related to two one is related to three and two is related to four all have different colors so they are in different growth so this is a valid case in this example one is related to 2 to 3 to 4 to 5 and 1 to 5 but here conflict arises as 1 &amp; 5 are of the same color so we can't &amp; 5 are of the same color so we can't &amp; 5 are of the same color so we can't group it so this is an invalid case and we can't group it into 2 so let's try to write code for this so basically what we have to do is we have to take a graph give it one element any random color like red then its old neighbors blue then all neighbors of neighbors red and earth so on and if at a point we are given a node different color than its previous one then we know that the conflict arises and we can't group it into two so for here I taken vector of vectors as graph and map to store its color now we are firstly forming the graph then we are iterating over all the elements that is not colored previously and using DFS on it in DSS what we are doing is then we are searching in that map and if we have that element previously then we are checking its color if we don't have that element previously then we are giving it the new color and after giving that new color we are saying give all its neighbour animals the different color and return so that's how we are doing our part so let's try to code in Python do so this is that function I am using different dictionary as graph and group is that container that is storing the colors of the graph now we are returning DSS for all that are noting group previously and our Davis is doing it is checking if the element is present previously then we are checking its color if node then we are giving it a color and then we are giving all its neighbor the different color and so on so I hope this is somewhat clear to you can give your suggestions in the comments below thanks for watching and have a nice day
Possible Bipartition
score-of-parentheses
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the person labeled `bi`, return `true` _if it is possible to split everyone into two groups in this way_. **Example 1:** **Input:** n = 4, dislikes = \[\[1,2\],\[1,3\],\[2,4\]\] **Output:** true **Explanation:** The first group has \[1,4\], and the second group has \[2,3\]. **Example 2:** **Input:** n = 3, dislikes = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** false **Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups. **Constraints:** * `1 <= n <= 2000` * `0 <= dislikes.length <= 104` * `dislikes[i].length == 2` * `1 <= ai < bi <= n` * All the pairs of `dislikes` are **unique**.
null
String,Stack
Medium
null
1,887
hello and welcome to today's daily lead code challenge today we'll be solving question 1,887 reduction of operations to make an 1,887 reduction of operations to make an 1,887 reduction of operations to make an array elements equal okay so let's go straight to the question um given an integer array nums uh let's see this integer AR nums your goal is to make all elements in Num equal to complete one operation follow these steps so through n or some number of operations we're going to attempt to make this input array uh equal or have all the elements in the array equal and these are the steps to reproduce one operation find the largest value in nums let that be let that index be I zero index and its value be largest Okay so we uh assuming that the array is sorted we find the largest uh value and have that be uh also equal to largest index sum n um value if there's a if there are multiple elements with the largest value pick the smallest I if there are multiple X's we pick the smallest X right uh if the value largest if there are multiple elements with the larger value pick the smallest I find the next largest value in nums strictly smaller than largest let that value be next largest so there is some x minus uh some number that is going to be next largest okay next largest uh and then we reduce nums I to next largest so we reduce this uh largest value to whatever this was x - one or xus whatever it is x - 2 was x - one or xus whatever it is x - 2 was x - one or xus whatever it is x - 2 3 or whatever um so what it what is this one operation actually doing well if we were to visualize it and I will I like visualizing these things because they uh make the problem more solvable um it kind of seems like assuming that this is a sorted array that once we find we start off with one point right here we look at the next uh we look at the next element and then we see by how much we have to reduce this um this next value now the process of reducing it is just one operation so once we reduce this we move on to the next one and try to reduce this once again I'm wrong though that's not the way to do this because that would mean simply that we look at how many different values there are beside excluding the first one and we just say that the result is nus1 n being the number of elements uh right the result is n minus one if this is the right approach so I'm doing something I'm messing up right I'm messing up I realize why I messing up because I'm going from uh I'm going from bottom to top whereas here the process is actually saying go from top to bottom so first um first look at this largest value find its next largest value subtract this number uh reduce it to what the next largest is pointing to and then go ahead and find the next largest value which would now be this uh reduce all of these so far two operations no so far four operations then find the next largest value this one reduce all of these which would be plus four more operations and then find the next largest and then 1 2 3 4 5 6 7 plus 7 so the result here would be 4 + 4 + 4 the result here would be 4 + 4 + 4 the result here would be 4 + 4 + 4 15 uh 15 am I correct here it seems like uh the process of reducing the array can't start from the initial value because if we start with the first value then we are easing the process of reducing the next values because we can automatically reduce it to the smallest possible value but the reduction here is gradual we first reduce the largest value to what we think could be the next largest value and so on until we um until we get everything equaling one uniform array so how would this work well one approach is to mimic what I just did which is to essentially have a start and a finish and each time I encounter this fluctuation between what is here and what is here each time I encounter that to some result I add um the difference between the start and the end so that would be this first uh plus equals would be a of the difference of uh just one right so it would be plus or equals to one uh and that would essentially me be cutting off these guys then I would push my start to the next possible start and cut off these three values so res plus equals three then I would cut off these guys so that would be res oh I would extend my width to here this was what three this would be 1 two 3 4 five six 7 seven wait why is it seven I messed something up um reduce this one reduce this three reduce this by four sorry I missed this portion when I reduce it first by three and then I reduce It Again by four and then 1 2 3 4 5 6 7 and then by seven so in this case it would be 3 + res + so in this case it would be 3 + res + so in this case it would be 3 + res + seven and here yes 15 right so 15 so that's one way of doing it I and that could be a solution what if we try to implement it maybe a bit faster going from still left to right but looking at let's see there's this notion of a step that I can Implement for example that if I'm looking at oops if I'm still iterating from left to right and I'm looking at uh the current and the previous numbers that are different in value I could indicate that my uh that my change to have all the following guys be changed is being increased by a magnitude of one because it essentially means that in order to get to this value has to be changed once and this value has to be changed once if I'm looking at respect from this one to how many times does this have to change well this has to change twice so what if I do something like this one two this value has to be changed three times because there's three fluctuations this value also has to be changed three times this value has to be changed four times does this also equal uh 15 yes it does 15 and this one is a bit easier to go by because we don't have to keep track of the start and the end we can just keep track of the step that we're um that we're changing so I'm going to try to go ahead and Implement that actually uh let's have the nums sorted let's have res equaling to one let's have the step equaling to zero let's have a while I in range one when nums and here I'll say that if uh nums I is greater than nums ius1 then step plus = 1 and then res ius1 then step plus = 1 and then res ius1 then step plus = 1 and then res plus equal step let's see if uh this works this is a very clean solution let's see if I was correct in picking up that did you mean I oops four for I in range silly there we go okay that worked yeah so very nuanced thing to notice you could characterize the uh the number of steps One of These Bars has to go through in order to get to its final destination through this variable called step and the way to know what that step is equal to for each bar is just uh memorizing how many times that has to be changed to get to this ultimate uh value and for these three since the previous value was the final value then the change is just one if at any point the next value is greater than what this what these guys are right then it simply increases by one because we first need to downgrade it to this value and then we need to downgrade it here so this notion of a step that increments or increases as you go on potentially this way uh let's me keep track of how many times the step is going to be what the step is going to be for each one of these bars and then it's just the sum of all of those steps and you can see that we've completed this successfully let's see if we're doing well we're not doing so well but this is an extremely clean solution and I don't know if there's any better no I'm looking at these right now and it is I like my solution way more additionally these do seem somewhat similar yeah step plus yeah this is oh this is one to one yeah absolutely I like this approach way more and uh yeah please use this um hopefully this was quick and easy and intuitive and that's what I'm really going for in these situations to visualize these things and then be able to apply them in later problems uh with that thanks for watching today's video please like And subscribe helps a lot and I'll see you tomorrow bye
Reduction Operations to Make the Array Elements Equal
minimum-degree-of-a-connected-trio-in-a-graph
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps: 1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`. 2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`. 3. Reduce `nums[i]` to `nextLargest`. Return _the number of operations to make all elements in_ `nums` _equal_. **Example 1:** **Input:** nums = \[5,1,3\] **Output:** 3 **Explanation:** It takes 3 operations to make all elements in nums equal: 1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\]. 2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\]. 3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\]. **Example 2:** **Input:** nums = \[1,1,1\] **Output:** 0 **Explanation:** All elements in nums are already equal. **Example 3:** **Input:** nums = \[1,1,2,2,3\] **Output:** 4 **Explanation:** It takes 4 operations to make all elements in nums equal: 1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\]. 2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\]. 3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\]. 4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\]. **Constraints:** * `1 <= nums.length <= 5 * 104` * `1 <= nums[i] <= 5 * 104`
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
Graph
Hard
null
138
hey everyone welcome back and today we'll be doing another lead code problem one three eight copy list with random pointer this is the medium one so the description is pretty large but what they are saying is we have a normal linked list uh with the next pointer but it does have another pointer name random so what does the render pointer do it points to a random node so the random pointer of 7 is pointing to the end of the linked list and the random pointer the second node points to First node and the random pointer of third node points to fifth node and that's it so what we can do here is just have a hash map so how our map is going to help us so let's say if our map is like this and putting on none as a key and a pair because there can be a none pointer so now let's just make the current for hours reversals so current will be starting from head so while current is not null but I will do is just make a copy node just a note and passing it current dot well so now what they want us to do is just make the copy of the linked list but we cannot just make the linked list and have all the other stuff like connecting them and doing all the other stuff like the normal one because as you can see when we are on pointer one when we are on node one its pointer is going to point to null okay but when we are node 2 its random pointer is going to point at 1 this is also okay we already have a node one but when we are on three the point random pointer of 3 is pointing to five so we do not have a 5 so how we are going to say that it points to five then in this case the map is going to help us because we can just get the values and that's it the next and random values easily and but this Loop we'll be doing here is just making the copies so not connecting the nodes and just making the copies so if it is the linked list is like this then this is just making the nodes but not connecting neither the next pointer or the render pointer these are just separate nodes so now we will say like map at current so current address at map should point to the copy we made okay now we will just update our current so current is equal to current dot next now we will start our current from the head again so while our current is not null we will take the copy we just stored so map at current okay we have the copy and now current dot next should have map at current dot next because obviously we have a reference and its dot next is going to give us its dotnet next the next node and it can be saved to the node we just copied like this node so that's it and its random is also going to be the same so Random map at current dot random okay after that we can just say like increment the current so current is equal to current dot next and just return map add head so why map add because head is going to give us the reference and at that reference we can just return the head which will be the corporate link list so that's it
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
134
Hello viewers welcome to test this pending in this video discuss problem very important interview problem gas station is taken from list code 134 problem and medium level problem is a very interesting problem if you want to watch then in this video we will first understand the problem statement and We will see his different approaches including output Sainik Real Karta Hoon In this video we will also discuss the code and its explanation so let's start the video example. As it is well prepared then let's take this example which has sample input from late code ki reddy this which This is the point, we have gas, withdrawal, I will tell you the status of it. Hey, what have you got from the gas station in this case, there are gas stations from 5825 stations, right circular is definitely ours in the circular route and the amount of gas and is stations gas I Muzaffar. How much gas at a station? At 10 stations all are considered to be zero. One unit of gas is available upon registration. Two your top gassers at the first station are available right near me. Not only the unlimited gas tank of the car we have, no matter how much it is. You can understand the cost that will be incurred and the fuel conservation that will be done in going from fire station to IS one of the sessions. He has kept us in the cords side, meaning if we have reached 100 stations, there is a station, I will make a station here, then I am College Railway. The station is 110, first, second, third, fourth and fifth, then let us start knowing the cost of subscription, then from here, three, this will be done similarly after consuming this corruption time. We have appointed gas consumers at the station and how much gas is available at this station. That is, inside the gas here, gas is available here and if you subscribe, then subscribe and after covering the whole, you will come back to the station road and if you subscribe, then how will it come from here, after subscribing, you will return here circular, you have to do two patterns that starting Index, which stage should you start from, you cannot soften every station here, there is only one station from where you start, you will be able to complete the circular road, here is the giver, united solution, it is a rented war, there is only one station, this is All can fit, if you are not able to chat, if you are not able to complete Qassam We have taken the code of approach so that we can understand the exam a little quickly. Here this is our ghagra, inquiry and here, if we take it, then what will we do here, if I do it in the induction, then if we come after doing it, then first of all we have taken N. Rally of whatever we will get this here of gas and converted it into skimming this and from its side we will ask for each index starting next give and starting in then we will take all these items starting from here can we call this starting index If we can make it, then let me assume here first that I can make it is considered possible to make it, then we will see further whether it can be made or not, and inside the fuel, I will keep the gas high till the current system father that he is in his tank, so my attendant fuel is hit. Otherwise, I represent it as fuel, we have this note, now it's time to fill your legs, now we will start freeing ahead, so the current station, what we will take out will be I+G, pizza what we will take out will be I+G, pizza what we will take out will be I+G, pizza people are feeling to move ahead, till the end station. If we have to reach from zero to the end, then what will be the current session? I want plus, now we are J, I am the first station, so let's go to fashion, we are here for daily life, so we will reach one station ahead of I, J2 will go to village heard from 22nd. Modern because it will be better prepared in some time after using the circular property, so let's see the current session, we have pimples station here, there is a card to take out the next, it has taken question mode, why is the time kept now? So this is a neck station. Hmm, I will differentiate it. Our current is written here. Fuel is written here. Now what will happen that we want to reach the current situation, Irfan, we will have to spend, that is the cost of current station, so do not spend 11km - 11. :00 Will do this will come - Every day - 11. :00 Will do this will come - Every day - 11. :00 Will do this will come - Every day fuel became negative Like Baikunth, it is not possible for negative people to continue. If fat cannot be converted into fruits and vegetables, then from here we will make bread to give our form. Next current starting index will run again. Now one thing is important point from here and it is known that if the master of gas at any station is less and the cost of reaching the next stage is high then one cannot start from there then you will send eight units of but you need 1180 At the beginning, if the tank is white or progressive, then it is important to keep this point in mind, so now it is possible here, we will do that in the future, we check the next station, then all this is over, daily problems are not going on, correct your knowledge. Now we will try to retreat from here, if we go near like this then some Stockholm will come to us. We will go with 6 possible computers. We will close our eyes and say that the current session is ours and this is our extraction. Okay, so from here we fry, if there is work then How much fuel did we have in the beginning? People said that the organization and teacher - Kara 054 said that the organization and teacher - Kara 054 said that the organization and teacher - Kara 054 Not quite united. We reached the tube channel again in Avnesh, so this is the one of it. So six plus one, how much fuel did we have in seven inches? The pass is available again but we need tubeless to reach like this. This is also not possible. We will press ice cream. We will do that next. We will carry a garland of bombs to Karan station. This is also possible. We will give current to myth TV to the crazy people. Once I tell you how and how to make extra money, okay, so what is our reason here today, the contribution of station women is so cute with us, this train is near the starting and we are considering it as Guru and we are saying the current situation as I plus mind, Guruji. I am in the current session and this is our next, this is the loot and ours which is the pipe to reach that mansion. Okay, so - after typing Okay, so - after typing Okay, so - after typing this, we are left with feet of fuel. Anytime on pension, then from there Bigg Boss housemate is here. For unity gas is available, we will fold it will not become important, if it comes to the next station, then the current will be ours, or if the bar increases, then the current system of clans is closed, means three plus 114, now our current station is done, whatever turn you have taken, that Why is there no time, what will be our current situation, frustration, Sona active, that's why we said that i plus job will come modified, zero will be modified, after this they will directly take me to form, there will be no change in the wanted criminals, this is our station, that's why If it is present here, then the current system was found in those actresses, now we have started subscribing Rasool, whatever congestion happened, but there was more in which support - will be but there was more in which support - will be but there was more in which support - will be saved, wife flash lights channel will go to this and in this case, it is fit for you. Such a circuit will be completed, if there is a computer, then you can take a break in between, check it if it is possible, yes, I had done the cutting metro, so we used to spend this amount of ₹ 1 here, no, spend this amount of ₹ 1 here, no, spend this amount of ₹ 1 here, no, here Mittu will return it. This is our answer here, but if you have found it possible at your home and have not searched all over - then possible at your home and have not searched all over - then possible at your home and have not searched all over - then this was our gravy approach which is very suitable for you all to understand. So now we have to do a little bit of optimization in it, we had to do ticket optimization because of the time complexity, so let's see first, so let's talk about the time complexity here. If we have to apply the powder above short and explain, then the network is our intensity. Will take and whatever will go on the channels, the time is running or the advection will run. If suppose we are not able to get it, then the total which will be set on that timer will be the committee with it. Stupid insecure which is very high, so whether we can optimize it remains to be seen. So there are a few points, I am clear to you, see what you do here, let's do some optimization, which is observation, point number one, the first observation that I have is that see, is it possible or not? So how religious in these custody so that I gas rally here, this registration is standard unit of gas available on the waist and the cost is different for everyone, okay, I have come to do a little this site, I have taken an example, quite a good exam, first, now. What I am going to do is I have taken out the blood differential, the difference of what is the amount of gas and copied it, I will take out the difference, add it here, the difference - Pro out the difference, add it here, the difference - Pro out the difference, add it here, the difference - Pro 6's difference is 500 to 1000 and it will come here on 16th - 7th, - 7th, - 7th, all this is 121. Okay, the difference that our colleagues and I have taken out in a loot-loot manner, here, and I have taken out in a loot-loot manner, here, and I have taken out in a loot-loot manner, here, if the difference has been taken out that it is available and how many people are there, where there is depression, they can start the custom, it is clear because brother for - it is clear because brother for - it is clear because brother for - Time's top-10 login protein is happening again and again. To go ahead, you will be Time's top-10 login protein is happening again and again. To go ahead, you will be able to point your finger at the top. If you go circuit, it is a different matter, okay, you can use circular, otherwise you cannot do negative importance, but what? I can find out whether the answer to this is possible or not because if the total gas available is right at every station, then forgive 80 rupees in the total gas cost, it is always great dan and equal to the total cost. If it is not so, then I can answer it anywhere, anytime. I have come in such a way that the total available gas can be so much that it can travel in the vegetables, if this condition is not met then the answer will come - Mother, it is not possible to answer will come - Mother, it is not possible to answer will come - Mother, it is not possible to get up in the circuit, it is good, so you can check it in different sizes. We can convert the difference and go to it, if the difference is less, the question is, the total difference will be and the total gas will be the total difference of the total cost, that if the great daily is 120, done only, our answer will be possible, so this is the first observation given, now where are we? Let me explain to you how we set it, let's discuss the election approach, how we are going to walk on us, so what we will do, we will start from here, okay, so this is our stock index, this is the light above, Sally Ride this. We will keep it here and see if it is possible for you, otherwise the difference that will come here is that we have the net, so for those people like us, we will get one, here we have to reach further, okay, so gas is the tank and expense is fraud, birth is ahead. Reach here, then here we will check. We are accusing I to move ahead, so here we will check the difference, how much is the difference here and - full right, so we have difference here and - full right, so we have difference here and - full right, so we have added it here and are moving forward after calculating our total difference. So if we deduct this from the total difference then it will be ours. Now the flavor of phone of four is in our bank and we would have reached here. Now we have to come and settle from here, the difference is that education means only admission. We will get but it's here, if we do n't do 6 problems then only if we get strength then we will set them tankers will be available for expenses, so enjoy it from here only by adding time, so all this work is done at hand light with the fuel we have. The total difference that is left is that baby tank t-90 total difference that is left is that baby tank t-90 total difference that is left is that baby tank t-90 tanks then we have reached here now here with the difference and is - the now here with the difference and is - the now here with the difference and is - the height of eleven so if you take - seven then the total height of eleven so if you take - seven then the total height of eleven so if you take - seven then the total difference will become - so from here it will not difference will become - so from here it will not difference will become - so from here it will not reach here. I can reach here, I wo n't be able to go further than this. It's not possible to move ahead. Salt, we need to use 11 to move ahead. Tumor plus minus one is on Brahma. 10 is gone. Okay, so I. This is reduced by 1 minute on his age. So what should we do in this case? Now what should we do? This part NFC is closed, it means should we start the starting index from here or not, this is an important question, so inside this we should not start from here, we directly You can start from here, now why am I speaking like this, let me explain it a little, okay, let me clear the intuition, so this one point to overs points, 220 points, this is a station and this station is also ours, okay, so I am here. Kushdhwaj can be shown by clicking on Kushdhwaj have car start from that and that judgment reach b that if from where it starts and Vipin does not reach the fog station that between a n b loot countries on that any station in the uniform of which he Can't even reach to even because it was given in small spoons because we started from A, so what amount of gestures hero was there in our tank, but when we reached to even, we had already got some gas for 8 minutes. So, if we start this saver of zero, despite being from Meerut unit, editing was available here at this time. If we were starting from here, then if it does not reach after that, then how will we be able to reach it? If you understand this, This means that if we are starting a gas like this, it is okay and it is not able to reach B, then any question in between, you guys will also not reach from there till now because here the benefit for you is not less than the loss for them. This means that if you start like this then you will not save anything, it is okay if you do not save anything then it will be zero or you will see some saving, then editing is done there is no further, but whatever benefit you bring here, which is left, will be for your issue. But if you start fresh from here, then your initial which now after the capacity of the tank is 100, cannot reach from here also, if you cannot reach from here, then our theorem of disease and stupid remedies, if we are stupid minimum. Can do because now there will be no going back from here, if we talk from here, then what else will I do with my starting index, I will call the family mercury, now I am my start next, start these taxes, make it full, dip the light pocket total and total from different. The difference will keep going on, then the total has to be withdrawn, my co-worker, my condition, the affair, the withdrawn, my co-worker, my condition, the affair, the withdrawn, my co-worker, my condition, the affair, the market committee, the total difference, the meat, the record, the need, the answer is possible, the total difference is there, it will keep going on - record, the need, the answer is possible, the total difference is there, it will keep going on - record, the need, the answer is possible, the total difference is there, it will keep going on - discharge the difference, I will make the current difference expensive, what is my current difference? The mobile will be switched off, zero, okay, you start from here, how much balance do we have here, favorite, the reason is the difference, and if we add to it, then the total difference will be ours, that's it, God, it's Friday. Here when we are here, which is the difference, the total of 3 minor surgeries has become the total difference, one of the current different has dried up or is still current affairs-politics, here there will be a difference of this, the current affairs-politics, here there will be a difference of this, the current affairs-politics, here there will be a difference of this, the current difference of this has become and this is ours. It is done, we will set the day of intake, here the difference is - ₹ 70, the difference is here the difference is - ₹ 70, the difference is here the difference is - ₹ 70, the difference is done, you are 0f the reason, the difference is done, gote and we have reached the end, date means, if we start from here, then we can cover the whole, I am here. From then till here, we started the history and we reached the end, where is the end and as we will be able to end, this is the answer, apart from this, the answer is not possible, so if you say that it may not have happened, then it is possible here. If you could not reach completely, it is 551 which is old last year, then we will discuss it in a little while, so the app is interesting, what we are doing in it is to take it from here and as it has been said that it is amazing, this is our answer, now you all can also know that From here onwards we did not get the power till we reached here, started again but could not go back but this has never happened, so if it had happened then somewhere Mark, you go first, I will also explain to you why this is so. If he is speaking, then let's assume that if we start it from the point, then let's assume that here we could not reach, okay, here on our jo difference, the current difference and which was correct Surya seller and our zero. Or negative light becomes negative balance, so here I had set that our rotating induction, so from here call this dress Max which I tried and this fresco I call brother and let's name it Mills and Boon of this distance. The Tilak requirement here is that now If we have health or are associated with the campaign, then if we used to sense, it should be positive. After mixing our earlier posting, we started from here. If there are technical tips, then we were torn here for the first time too. We did the valley press then like this. It is okay in between, it is exports, I understood it and change the voice brother, what will happen, that is also posted, sorry brother, it is negative, so I did duty fast during Purnima, so that I could not reach here, it means it was virus, it was found negative, it was ahead of ours. If it is negative, then what should be the broom? It should be on the roads, meaning there will be a plate. If it is quite possible, then only they need positive because it is negative and this negative is not a big thing, that is why we could not reach here. Okay, so it should be of air, it should be positive and Now white bread should be shifted by solid people but if bhaiya chat was positive then we would not have started from here, you understand starting here, we should start here so that Salman's, if this was our positive then shoot me. If you start with understanding then it may seem a little complete to you but I will take so much time from here Amit says this is not possible if you reach WhatsApp then I am from the beginning now I have proved that it is very good to understand you so no problem You will understand the end fast, its intuition, how do we reach to, so you fold it like this and it is very simple, okay, so we move ahead here, so this is the credit for the function input, so this was the first one. Now there is a little lifting, the children become visible, the colors are visible, the list code will be presented later, so what will we do, will we add the looper, so first let us define their value for 1 minute, I am pressed that I have reached India, there will be some entertainment here. Is equal to gas dot 500 I got their value here cyber cafe from beginning to end pocket starting index take strange different but she gasp and same light goes on shift in the meeting so what will we do here which is our fuel ok this fuel Tank is called fuel tank, how much will it be? Earlier, initially 20 inches were calculated from the states and Excel difference was created, so what difference is to be created, it should be coffee, while starting Undhiyu, the fuel tank will take out as much gas as is available at the fire station. - If the owner available at the fire station. - If the owner available at the fire station. - If the owner is okay to free the poster further, then in this way how much of our front time will be saved, we have to chant that the fuel tank is okay, to which I was walking at that time saying that there is a difference due to this. So what should be our current difference? If it is negative and 10:00 then what will we do? If we will 10:00 then what will we do? If we will 10:00 then what will we do? If we will start Dindeshwari then it is if it will be movie time coffee then it will be negative. If we will start advance then we will Those who will start their starting index school, if they are not able to reach the next station then what will we do about the next station, restart from there, did 8, my will be 20, even if they are not able to reach, then the middle question, I have not reached yet, so that further Uttarakhand you I took the garlic as the target and restarted the refueling tank. It works like current affairs. Ok, total difference. Chawla, you will understand in total difference. If we do this work, then let's remove it. Here we make difference. Bulb this which is the front arm hole's this plus equal two differences a and inside the total difference this will be adding that Bluetooth data recovery site will not be there will be a negative of the fuel tank two which is the front arm is the same is settled and the starting indicator is our this much we What has to be done here is this look enzyme will come out of this group then we will check that the total difference which should be gold is positive connected money equal to zero. If it is so then we will return our start index but if it is not so then we What will you return - One who not so then we What will you return - One who not so then we What will you return - One who voted, this is the total, so let's test it, copy it from here, color it here, test cases on Kunjam on all test cases, then submit this and Angara here, it was 101 WhatsApp Twitter has been used very little by me, so come you have enjoyed this complaint tuition example and code in this way, I am here in which way we proof and you just move towards optimizer east, 100-150 and this of this video. in 100-150 and this of this video. in 100-150 and this of this video. in for watching
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
43
welcome back to code Meets World and today we're looking at a leak code problem number 43 which is called multiply strings so if we're given two non-negative so if we're given two non-negative so if we're given two non-negative integers represented as strings we need to return the product of the two of them also represented as a string and we can't use any built-in libraries or just can't use any built-in libraries or just can't use any built-in libraries or just converting the inputs to integer directly so as an example if we're given the number two and the number three is strings we need to return two times three which is six as a string same thing down here if we do 123 multiplied by 456. we should return fifty six thousand eighty eight as a string and what we're not allowed to do is simply convert the string to an integer convert this string to an integer multiply them together and then turn it back into a string that would be way too easy and so they say that we can't do that at the top I'm linking to a video I did recently where I was doing addition with arrays where you had to go through digit by digit and do the actual Edition from scratch so check that video out if you want to see a similar problem to this one so let's go to the Whiteboard and I have the second example pulled up which was 123 times 456. now I'm just going to solve this really quickly using what we learned in school when we learned how to do multiplication for the first time because we're gonna have to write code that can pretty much do that exact same thing so what we do first is we multiply the six times each of the digits in the top number and feel free to follow along if you haven't done this sort of thing in a long time but six times three would be 18 so we would write the eight and then carry the one then we would do 6 times 2 which is 12 plus that one is 13. carry the one six times one is six plus that one is seven and then we can get rid of those values that we carried and now we're going to do the same thing but with five in the top number and you might remember we have to add a zero before we move on to the next digit so 5 times 3 is 15 carry the one five times two is ten plus the one is eleven five times one is five plus one is six and then we can remove those ones that we carried and then finally because we're going to do this a third time with four in all three of these numbers we have to again add zeros but this time we add two we add an extra zero each time and then we do 4 times 3 which is twelve carry the one four times two is eight plus one is nine four times one is four and then we add all of these together at the end it was zero and one that's six one five so we get fifty six thousand and eighty eight which is the exact answer that they told us in the example on the neat code website my plan is to write code that can do this process and so we're going to need to keep track of a lot of different things here and now that we've seen this done by hand I think it's easier to think about what variables we need in what process we need to follow so to start out with I know that we're going to need a carry variable to store whenever we have to carry the one when we're doing the multiplication so I know we'll need a variable for that I know that we're also going to need a way to store the final answer so like I just showed we need to add together each of these numbers that we get at each successive step into the sum so my plan is going to be to have a sum variable and each time I calculate one of these intermediate values I will add it to the sum so at the end we get the correct answer down here another thing we're going to need is a way to keep track of the current number that we're forming and what I mean by that is my plan will be to compute these values one by one so I'll first have to find the eight then the three then the seven I need to store all of those somewhere which I'll do in the current variable and then once I have the full value I will go ahead and add that to the sum and I think how I'm going to keep track of the current is with a Q data structure I'm not sure if we've talked about those yet on the channel but basically it's like an array but you can add easily to both ends and the reason I don't want to use an array here is because I'm going to be kind of working backwards I'm going to add the 8 first then the 3 then the seven so I'm going to be adding to the left hand side of whatever data structure I use which isn't really good for arrays because they append to the right hand side so I'm going to use a Q and I'll show you how to easily make a cue it's actually built in to python which is really nice then there's one more thing I think that I need which is I need a way to handle the fact that I have to add these zeros each time we move on to the next number that we're finding with our multiplication and I'm going to make that a variable called Factor I'll start with it equal to 1. because at the beginning we just multiply whatever we get by one but then after we compute the next value which is 615. we need to then add a zero to the end of it so we can multiply it by 10. same with the next value when we find that it's 492 we need to add two zeros to the end of that so we can multiply by a hundred so basically this Factor variable I'm going to use to keep track of what I need to multiply the value of whatever step online I'll multiply it by factor and that will leave me with the value that I'll actually bring to sub so that was a lot of info let's walk through the problem again for maybe a step using these variables that I just described so we can see how this is going to actually work so I'll write that again and this time I'm not going to do any math over here I'm only going to use the variables that I created to do everything so we'll start out by doing six times three just like last time and that equals eighteen so we know that there's an 8 that we insert into the Q and then we carry the one so next we would do five I'm sorry we would do six times two like this and that equals 12 but we have to remember to add the one from the carry so we actually get 13. meaning we'll put a 3 here and the carry stays is one because it's we're carrying one again now I do six times one which is six but then we need to add the one from the carry so we get seven and we'll just add that in to current and that's all we have to do so now we can clear the carry we can clear current and instead add that value to sum and again because the factor is currently one we don't need to do anything we don't need to add any extra zeros so we're finished with the first step I guess I'll go ahead and do all three so we can see how it works the whole way through so now we're going to start with the five and do five times three which is fifteen so we'll add the 5 to the Q and put the one in the carry then we'll do 5 times 2 which is 10 plus the one from the carry gives us 11. again we keep the one in the carry finally we'll do five times one which is five plus the one gives us 6. and now this time because I forgot to do this before I started this step but we need to increase the factor to 10 for this iteration which will allow us to multiply 615 by the factor so we'll add an extra zero there and then we'll bring that up to the sum and add it so this ends up being plus six one five zero now we can clear the carry clear the queue and what I should have done last time increase the factor by multiplying it by 10. now our final step we are on the four now so we do four times three which is 12. so we'll write down the two carry the one then we'll do 4 times 2 which is 8 plus the carry gives us 9. and finally four times one just gives us four and now because the factor is a hundred we need to multiply current by a hundred which adds the two zeros and now we can add that on to sum and finally we can clear everything and because there are no more steps to process our final answer is going to be the sum of those three numbers and if we look these three are the same as these three so we know that we are indeed going to get the final answer which is the same for both of them so I think this setup is what I'm going to go for and we'll be able to iterate over each of these numbers just using a nested for Loop so now let's jump to the code to see how we're going to do this right so the first thing that we need to do is actually import the Q functionality that I mentioned that we're going to use for the current which I am showing on the Whiteboard so we can do that by saying from collections import DQ is the name in Python and DQ is just the Q functionality and then I'll show you how to append a value to the left to insert something into the queue when we need that so the first thing I need to do is initialize my sum which I can set to zero as well as the factor which I will set as one and these are two of the four variables that I'm going to need the other two I need to reset each time the loop iterates so I'll add those in just a moment so the first thing I'm going to do is just like we showed on the Whiteboard I'm going to Loop over the second number so the bottom one starting at the six and then I'll work my way to the left so we will start by looping over num two so we can say for I and we can say in range and this is going to be looping backwards starting from the end of num2 and going back to the beginning I've talked about this in a previous video but the way we can do that is start at the length of num2 minus one then we're going to go until we reach negative one and we will decrement each time and going until we reach negative one sounds weird but that's because it is exclusive of the end bound so it'll stop at zero so this is how we Loop over num2 backwards and then we have to do the same thing for the first number one so we're going to Loop over num2 and for each value we have to Loop over all of num one so we can pretty much say the same thing for J and range this will be the length of num one minus one and again uh we'll just say minus one and this is also where I can add the other two variables so we need currents and then we also need carry right which I already done on the Whiteboard there so carry we can start out as zero because there won't be any carry at the start current I can just set as DQ and this is how you initialize an empty cue using the DQ library that we imported great so now that we have both of those the first step every time like I showed on the Whiteboard is just to take the first value and multiply them together and we need to add any carry that might be there so we multiplied the two numbers and then add the carry if there is any so I'll say product equals and this is the one time where we have to convert the values into integers because we just simply can't perform multiplication without having integers at some point so this is perfectly allowed and completely following the rules of the problem but we can say product equals int num to a position I and we can say times int ENT num1 position J like that so that's multiplying the two numbers together and then we need to add whatever the carry is now the carry starts at zero but as we go through the problem I'm gonna set the carry based upon what we figure out is the solution to this multiplication problem so then we can say we need to append whatever we get here the current because remember um on the Whiteboard for example say that this results in eight we need to set eight in our current so basically we need to put an 8 here and a one up here so how do we do that so we can say current dot and the syntax here is okay and left which means we're going to place whatever value on the left hand side of the queue and insert it we need to append product which is in this case 18 when we multiply 6 and 3. modular division which is that symbol by 10 because if we take any number and we do modular Division 10 it always leaves us with the ones place so this will just take 18 and give us 8. and we'll append that on to current then the other value which is the carry we can set that equal to again it needs to be the one and we can get that by saying product integer division because if we do 18 integer Division 10 we'll be left with 1.8 we'll drop the we'll be left with 1.8 we'll drop the we'll be left with 1.8 we'll drop the decimals so we're left with one now there is one additional thing we have to consider here which is in the case where for instance we get to four or we get to the end and which is index zero at that point we don't want to append to current whatever the solution is modular Division 10 because if there's a carry we just need to add it what I mean is for instance if this instead of being a one was a nine and so on our last calculation 4 times 9 is 36. we can't just write 6. and carry the 3 because there's nowhere else we're not going to do any more calculations with the three we need to write the 3 with the six so the Q needs to get both 3 and 6. so we don't want to actually do the modular division by 10 in that case so basically if J equals zero meaning we're at the very last case we want to say and again I still want to do this in the other case so I'll just copy and paste that but if J is 0 we just want to append the full product we don't want to cut off any values we just need the whole thing but in the case where we're not on zero we only want the ones and then we will add the carry so that looks good and then once we come out of this we need to do I guess something sort of tricky which is we now have current which is a q of all the values so for instance say we have 36 in there like in the case on the Whiteboard we need to take those values and we need to add them onto the sum the way we can do that is a little bit tedious in Python so we need to convert an array basically because a q is just an array we need to convert that into an integer and then add it to the sum the way we do that is if I'm not mistaken there's a few different ways but we can say sum plus equals and then we can do this trick where we join so basically when we do this step by step in Python a map function takes some function in this case it would be Str which means convert something to a string we want to do that to all the values in the current so this will take every value in current and convert it to a string we want to join that set of strings with just the empty string so we can say empty string dot join this looks funny but this is how you convert a array of something and smush it all together so we're taking every value in current and joining them all together and then we need to of course convert all of that to an integer and add that to some now I think we're missing one component which remember this Factor thing after we calculate current we need to check hey what's the factor and multiply that by current so I can just do that here so what this is saying is after we perform all the calculations for a given subset of the problem we're left with current which is a queue of all of the values we're going to combine that together into a string convert it to an INT because this is how we convert an array of integers into just a single integer and then we'll multiply that by factor and all of that will get added to the sum variable which we're going to keep track of over time finally we cannot forget to make sure that we multiply Factor by 10. so Factor times equals 10. at the very end we can return we just want to return sum but remember the problem once it is a string and we have it as an integer so we need to change this to our string so let's give that a run see if we've solved the first cases which will pop up down here and we have that passes for both of them so let's go ahead and submit yeah and that's working it's good for memory it's not amazing for runtime and I'm not quite sure why there's probably a nicer way to solve this but to me this one made a lot of sense this is what came to mind first and I hope this has been insightful so let me know in the comments if you have any other questions or if you know a better way to figure this out I'd be interested to take a look at it see you in the next video
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
1,029
so hey guys welcome to my channel i am sithis and today we will be doing another very interesting problem from the lead code daily challenge day 25. that is the lead code problem number 1029 two city scheduling in the problem statement we are given a cost array where cost of i is basically a pair of a cost and b cost where the cost of flying the eighth person to the city a is a cost and the cost of flying the eighth person to the city b is b cost basically what we have to do is to return the minimum cost to fly every person to a city such that exactly n people arrive in each city and i believe the question is pretty easy to understand and it will be more clearer when we will discuss the sample test cases so this is our first test case where we are given four pairs of a and b cost array and we have to find the minimum cost to send half of the people to city a and another half to city b for the first pair we see that we are given a value of 10 and 20 out of which we see that 10 is minimum so we decided that the person 0 must go to the city a for the second pair we are given a value of 30 and 200 out of which we see the 30s again minimum as a result we decide that this person must also go to the city a for the next pair also we are given two values that is 450 and out of which we see that 50 is the minimum as a result we decided that this person must go to ctp e and for the next pair as well we are given two values that is 30 and 20 out of which we see 20 is minimum as a result we again decide that this person must also go to the city b as a result our total cost of sending two people to city a and two people to city b comes out to be 110 which is our correct output as well so this is our second sample test case and here also we are given uh six pairs of cost of sending each person to either to city a or city b here we are also given the output 1859 which tells us that the minimum cost of sending these six people to either of the city a or city b is one eight five nine only since the explanation is not given we can't say which people goes to which city and you might say that all we have to do is to traverse the array and find the mean from the pair and sum it that should be our answer will it be let's try so for the first pair minimum is obviously 259 so we would be taking 259 for the second pair minimum is 54 so we'll be taking 54 for the third pair minimum is 667 so we'll be taking 667 for the fourth pair we see that 139 is minimum so we must take that in the fifth pair 118 is the minimum so we must take that also and as for the last two pair we see that 469 is minimum so we must take that and you might say that the sum of all this value will be the minimum possible value to send all the person to either city a or city b but here we are missing a very important point that we have to send and by two people in each of the city so about this distribution where most of the person is going to the ctp is actually not correct so you might say that okay we will try to find the first and by two smallest cause to travel to city a and some with the rest of the cost to travel city bay again we will try to find n by 2 smallest cost to travel to city b and sum with rest to the city a and mean out of both the sum should give us the minimum sum right but this approach also doesn't work so what can be done let's see let us suppose that we have only two person x and person why and for person x the cost to travel city a is 8 and the cost to travel city b is 10 and for person y the cost to travel city a is 15 and the cost to travel city b is 20. now how would you distribute them such that the cost of sending either of them to either of the city is minimum now since we must assign one of them to city a and one of them to city b now in spite of sending person x to city a and person y to city b which nearly gives us 28 the optimal solution would be to send person x to the city b and person y to the city a which will give us the traveling cost of only 25 which is definitely minimum than the previous cost we had found so d2 we find an observation we get three observation the first and most important observation is that the relative difference is more important as compared to choosing the cost greedy in this test case that is 8 minus 10 minus 2 and 15 minus 20 that is minus 5 we see that the relative difference of person y is smaller compared to the relative difference of person x as a result it would be more cheaper to send person x to city a as compared to sending person x to city a and since we are bound to sending only one of them to either of the city we decided that we would send person y to city b and person x to city a which would definitely give us the optimal result our second observation is that regardless of what the individual cost be only the relative difference matters again this is evident from the same test case as well no matter how much the cost of sending person x to city a all the cost of sending person y to city a be it only the absolute difference or the relative difference matters and our third observation is that we have to greedily choose the cost based on the relative difference we will find the relative difference each of the person to travel are in either of the city and sort them after sorting we will greedily choose the first n by 2 is smallest and last n by two values that would give us the optimal solution so our algorithm comes out to be something like this first of all we have to find the relative difference that is the cost of eighth person to travel through city a minus cost of eighth person to travel city b after finding for each of the person we have to sort the relative difference in ascending order if any i th difference is smaller or negative it means that it will be cheaper to travel to city a but if any eighth difference is larger it simply means that it would be cheaper to travel to city b so at the end we will greedily sum the first and by two cost to travel to city b and next n by two travel cost to city that will be our result now let's try to solve our third sample test and see if our algorithm actually works or not so this is our cost for each of the person and as our algorithm say first of all we need to find the relative difference for this the relative difference is minus 54 for this the relative difference is minus 262. for this the relative difference is minus 172 for this the relative difference is minus 476 for this the relative difference is 76 for this the relative difference is 397 for this the relative difference is 291 and for this test the relative difference is 591. now as per our algorithm our second step is to sort the relative order in ascending order so let's do that and this is our sorted relative difference as our n is equal to eight from our algorithm we see that first n by two people must travel to city a and the next n by two people must travel to city b as a result these four people must need to travel to city a and the next four must need to travel to city b so we would sum this values and our sum would come something like 3086 which is actually our correct answer so we can say that our algorithm is absolutely correct now let's see how we implemented this algorithm in our code so here is our code and inside our code and the first thing that we are doing is to find the relative difference for eighth person between the cost to travel to city a and the cost to travel to city b and we are storing it along with the ith index so that in the later value we can retrieve the cheaper cost next we are sorting our relative difference in ascending order and for the last part since our relative difference array has already been sorted we can safely assume that choosing first and by two people to go to the city a and the next and by two people to go to the city b will give us the most optimal result thus we are doing the same and returning our sum let's see if it successfully execute which it does and let's submit to see if our answer is correct or not which is and that is how we solve this very interesting problem to ct scheduling hope you liked my solution we will meet tomorrow again with some new problem until then keep going keep learning so do you
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
124
Hello hello guys welcome back to take two this video will see press entry maximum after we problem system list date one of the dead skin challenge so let's look at problem Thursday maximum can start a node for example you can see some parts of 99 subscribe and subscribe the 1995 me stan at any point but it's always for example service and subscribe and not good quote 20 second example you can directly and get started and does not prevented this not to enter maximum is equal to 50 cases not going through this Root of the tree it and not improved by the third point is that can not minimum set the volume to the value - 151 - 151 - subscribe not to solve this problem subscribe is that we will sleep example you can see the Maximum Edit Starts From This Note 2 End Service Note 3 And Fear And Use Not To Wear Is The Maximum Different From This Note To Do The Root Of The Maximum Subscribe 598 Veer Is Not The Subscribe More than 90 Subscribe Now To Solve This Problem Solving Maintain Via Batuk E Pray For Maxim Switch Is Already Front Should You Will Handle Case Number 39 Minutes To Compare All Other Cases For Each And Every Month The Very Latest Example Will Take Away All Subscribe Number One Is The Maximum Compared With Its SUBSCRIBE 2 AND TAKE CARE OF THE MAXIMUM OF THE THING WHICH WILL TAKE CARE OF ALL THE NUMBER SUBSCRIBE REMEMBER MAXIMUM SUBSCRIBE TO PROCESS DISTRICT UNDERSTAND ALGORITHM SOUNF JUST STARTING AND DRUT NO WILL BE MAKING CALLS AND WILL MAKE IT WILL BASICLY POSTERS FROM SUBSCRIBE WHAT Will be the value from left to right Subscribe nodes in the maximum 100 no which will not be done current note will make the validity equal to what should discuss denotes that will take here life is the meaning of the Word Which Will Be The Name Of The State And Subscribe To The Channel Absolutely Complete The Volume Maximum All The Best Choice Number One Is The Value Of Root Will Be Subscribe Must Subscribe Dahan Disconnect Note Will Fall In The Maximum Pass Pirate's Paradise 98100 Test To You Can See In To The Con Is The Left Side Subscribe Will Compete With Now School subscribe And subscribe The Amazing That Maximum Value Of 21 2008 Will Be 810 Will Sufis To Ring Velvet Navodaya Result Will Actually B Initially Enter Because The Can Be Any Value Soul Valley School Negative They Will Be Replaced With It 21 2012 Subscribe Maximum Which Will Be The Current Arrangement Maximum 8282 Click A Subscribe Button On Left Side Mein Ka Macrame Samay Ajju Can See In This Time The Will Have Been Latest Current Note-2 Will Have Been Latest Current Note-2 Will Have Been Latest Current Note-2 Handsfree Mode Turn On This Nuvea Research That Is Not One Can Get Rid Of Dandruff Russian Its Too Front To The Self Written Notes In Nod For The Only Don't Forget To Subscribe To Divya Channel And Subscribe to alarm set the current note volume which is point well so this is the maximum straight path value sweet will start this eighth included in this way you will know this for this you will compete with karan adhir will not the temperature of this is the Roof Top Rain Water From This Point Subscribe Now to Receive New Updates Comparing with the Guardian Practice of Previously Front Maximum Value with the Best Value Do the Maximum End Subscribe Must Subscribe Know What Will Not Return Face Value Only subscribe to the Page if you liked The Video then subscribe to the Page That SDO of newly formed board soft consider about 2820 plus five plus minus 10 which will be equal to - 500 you can see but clearly equal to - 500 you can see but clearly equal to - 500 you can see but clearly s One is serving maximum value so and value here will be 125 10th 12th result will compete with shyam subscribe check the subscribe button more complain against its value is valued at increase request 231 know what about this m21 Valueless Comparison and K to And S One Should Discuss the Class 12th Part subscribe and subscribe 802 Value Will Compete Against Subscribe Must Visit Will Return Value Which is the Value - 2nd Return Value Which is the Value - 2nd Return Value Which is the Value - 2nd T20 - 132 Subscribe T20 - 132 Subscribe T20 - 132 Subscribe Jhalda Maximum Value from the White Part Plus This Current 100MB Left for Maxim Time Elapsed Plus Puberty Exactly 12th Part Plus Two Plus Minus 181 Switch Off the Face Value - Wave 2K Considered S to the Root of Value - Wave 2K Considered S to the Root of Value - Wave 2K Considered S to the Root of the Subscribe Thank You Will Not The Third Result Will Be Amazed With This To-Do List Processing Notes By the first to 10th result date final maximum first value knowledge center problem and if you are able to understand the running time complexity of algorithm in just three times subscribe the channel please subscribe The Video then subscribe to subscribe quick comparing the maximum of all The Cases To Return Result No Way Can Only Returns The Case One Value Soweer Viewers Problem Side And Solution Different Languages ​​And Placid Like Share And Languages ​​And Placid Like Share And Languages ​​And Placid Like Share And Subscribe
Binary Tree Maximum Path Sum
binary-tree-maximum-path-sum
A **path** in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence **at most once**. Note that the path does not need to pass through the root. The **path sum** of a path is the sum of the node's values in the path. Given the `root` of a binary tree, return _the maximum **path sum** of any **non-empty** path_. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 6 **Explanation:** The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6. **Example 2:** **Input:** root = \[-10,9,20,null,null,15,7\] **Output:** 42 **Explanation:** The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42. **Constraints:** * The number of nodes in the tree is in the range `[1, 3 * 104]`. * `-1000 <= Node.val <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
112,129,666,687,1492
36
hello welcome to my channel i'm here to do my honzolico challenge and today we have leeco 36 valid pseudocode so this question is really classic so we said determine if a nighttime knight pseudocode board is valid so only the fuel cell needs to be validated according to the following rules so first each rows must contain digits 1 to 9 without repetition 2 each column must contain the digit 1 to 9 without repetition 3 each of the 9 3 x 3 sub boxes of the grid must contain the digit one to nine without repetition so like we used to play uh pseudocode before and this is one of the map in here so it said for row right here so we have one two nine there's no duplicate in here so one to nine we all put it in this box and in column same thing we have one two nine filled in this box and they all distinct no duplicate in either row and column and the last is in each box we have one to nine no duplicate in here so in that case then we'll see this uh current pseudocode map is valid so for example if five is here and if i appear either somewhere here or somewhere in here so if it's invalid in this row and invalid in this column same thing is here if any duplicate three in here another three in this grid then is not valid for um the easy way to think about this question we can have an array of set in here for this column array of set of the rows then we if we have five we go to the first index of that array and put five into the first set it puts three in the second set if and we keep looping all the way to the end of this every number in this group the big table if we see five in here and we go up to hit the array and the first hash set in here if you put five again inside that headset already have five which the first five in here then we return false because you can have duplicate same thing in here you can see this headset in this index in the this index for this row so they all co-related and then that's so they all co-related and then that's so they all co-related and then that's one of the way that we can check and also the box to have another headset for this box but overall the code is over complicated and it's just a lot of work and a lot of code it takes a lot of time to code it you might have a lot of bugs so that's one way this really smart way that we discover is so we can think about a case like now we have uh we only need one headset and when we look through every integer in here and we see 5 for example and 5 is located in column 0 and we can see i'll put c which index is c0 so what number is 5 so we put c 0 column 0 and 5 as a string inside that uh headset and also in the same time this is row 0 5 that mean in the headset will contain oh row zero only have one fight so now we have five ready later on the row to traverse this line if you see if for example 7 become 5 if you see duplicate 5 right here and we will keep we will find out it is also in row 0 and if this is 5 it will have row 0 5 again so we bring this inside the headset and it's see that has i already have uh i mean row 0 5 then that's not valid so now we look through everything keep putting those number inside this headset uh for the grid and i will show you in the code and how do we do the grid so basically we use the index divided by 3 then that will be the grid number for example in here is grid 0 and 0 grid 0 1 0 2 here is grid 1 0 how would come up the one i mean how it comes with 0 is in here the row right now is 0 1 2 so all this number divided by 3 we have 0 as this row 0 in here and here also it's just a mathematic calculation so let's take a look at the code now um we will have only one set we have a string so now the set is done then we have to loop through every number just the double for loop for looping all the numbers now this double for loop is looping number from here to here all the way to the last number in here let's see what we're missing so now this is going like this and this okay so we have we get the current charge called current will be i and j so this is current uh character so if oh sorry i didn't show you um this is the input of that array so now if the input is thought we don't need to care about it's just empty in here so we only care about uh number which is a valid for integer so f so we only care when the current character is not dot so that will be an integer and then we will have set at we have um row like what we said we put row plus i is the row and plus current which is the current uh character so now what it means is in here we have okay this is example like in the first integer here we have row zero five so we have row which is zero and five column zero the first call i mean the first column which is indexing zero column zero five so contain all the information so we put that this string inside the set if it doesn't have this the set doesn't have this string it will add it to the set for example if the set already had r05 then it will return uh next i mean if it returns false because it's already contained the set actually contain this string so this is one of the function for headset for set for the add method so you can check and things that have the duplicate inside the set already then this if function will be valid after that will return false right but not only that this is only the roll away we also need to check the set we need to add column plus j is j's column right now plus curve and also we need to check that dot we call grid plus i divided by three plus j di by 3. like what we mentioned about the grid actually this is um like this grid and then this number will be uh the row and this number will be the column and that's it i think that will solve the case it's kind of too long in here f okay after this for loop we see no problem with that we just return true all right let's test out what's going on in here let me double check okay i found out this film may stick right here so we need to add this because we need to check if it's added inside already and another mistake in here so because we need to add the current inside this string so we have grid current number in this column row and column okay i think that should be it cool let's submit it and that's it for this question uh yeah i think it's really clever for this solution and if you still have any question please comment below and i will see you in the next video bye
Valid Sudoku
valid-sudoku
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: 1. Each row must contain the digits `1-9` without repetition. 2. Each column must contain the digits `1-9` without repetition. 3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. **Note:** * A Sudoku board (partially filled) could be valid but is not necessarily solvable. * Only the filled cells need to be validated according to the mentioned rules. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** true **Example 2:** **Input:** board = \[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** false **Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid. **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit `1-9` or `'.'`.
null
Array,Hash Table,Matrix
Medium
37,2254
275
hi guys welcome to algorithms made easy today we will go through the day 18 problem 8 index part 2 please like the video and if you're new don't forget to subscribe to our channel so that you never miss any update given an array of salutation sorted in ascending order where each citation is a non-negative where each citation is a non-negative where each citation is a non-negative integer write a function to compute the researchers edge index a scientist has an index edge if edge of his or her n papers have at least edge citations each and the other n minus H papers have no more than edge citation each for the example given the input means the researcher has 5 papers in total and each of them had received 0 1 3 5 &amp; 6 each of them had received 0 1 3 5 &amp; 6 each of them had received 0 1 3 5 &amp; 6 citations respectively since the researcher had 3 papers with at least three citations each and the remaining two with less than or equal to three citations each her each index is 3 let's see it visually let's take the same example so we can see that there are three values with value greater than or equal to 3 while other n minus H that is 2 less than or equal to 3 if you change a value 3 to 4 we see that it does not have any effect on the edge index it still has 3 values greater than or equal to 3 L 2 values less than equal to 3 if we change 3 to 2 the output changes to 2 as now 2 values are greater than equal to 2 and n minus H that is 3 values are less than or equal to 2 let's see how to solve it let's go through the first approach wherein we will iterate over the citations array of length n for each citation we check the below condition here n minus I will always give you the number of values greater than or equal to the current value if the condition gets satisfied we return the value n minus I if you do not get a value satisfying the condition we return 0 let's see it visually working with the same example at the start n is 5 and I will go through 0 to 4 starting with the index 0 we see by values with the value greater than or equal to zero which fails our condition as five is not less than or equal to zero so we move forward again a condition fails so we move forward this time the condition is satisfied as we have three values with the value greater than or equal to three so we returned three the time complexity for this approach is o of n when the space complexity is o of 1 instead of iterating over the whole array we can use binary search for this we initialize start to 0 and n to n minus 1 while start is less than or equal to end we calculate the mint by using the formula shown and if n minus med is equal to the value of the citation at mid we simply return n minus min else if the value is less than the citation at min we set the end to mid- pun else we set the start to end to mid- pun else we set the start to end to mid- pun else we set the start to mid plus 1 at the end we return the value for n minus start let's see it visually with an example initially start will be 0 and will be n minus 1 and we will calculate the min so the men becomes 2 and the element at mid is 3 now we check our first condition and see that it satisfies so we return in - mid that it satisfies so we return in - mid that it satisfies so we return in - mid that is 3 the time complexity for this approach is o of login well the space complexity is o of 1 here is the code snippet also check out the link to the java code in the description below thanks for watching the video if you liked the video please like share and subscribe to the channel let me know in the comment what do you think about the video
H-Index II
h-index-ii
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper and `citations` is sorted in **ascending order**, return _the researcher's h-index_. According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times. You must write an algorithm that runs in logarithmic time. **Example 1:** **Input:** citations = \[0,1,3,5,6\] **Output:** 3 **Explanation:** \[0,1,3,5,6\] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. **Example 2:** **Input:** citations = \[1,2,100\] **Output:** 2 **Constraints:** * `n == citations.length` * `1 <= n <= 105` * `0 <= citations[i] <= 1000` * `citations` is sorted in **ascending order**.
Expected runtime complexity is in O(log n) and the input is sorted.
Array,Binary Search
Medium
274
1,008
Hai gas welcome to today's video and today we are going to do lead code problem 1008 which is named Construct Binary Search Tree from Prior Order Driver so basically we have a preorder area and we have to construct a binary using this array. And this binary search should be free okay so we will see how we will approach this so first of all we know what is the relief of order care of proorder first comes in proorder then comes the root then comes left and then comes Right, if it was in order from this then I am sure that this is my root. The first element that comes will be my root. Okay, so I know that right now my root is where the element next to it will be. So, first of all, while making the tree, obviously we will travel from here 012345 because by doing these elements we have to make our binary. Okay, so now I have reduced my number by 8, which means it is zero, so I have indexed it, so now my This decision has to be made whether my index will come on the right or on the left, so in binary we already know that all the values ​​that we already know that all the values ​​that we already know that all the values ​​that come on the left side of my root are &lt; roots of the note and &lt; roots of the note and &lt; roots of the note and those on the right side become values. If we have a greater number, if we have a root, then my 5 A will go to the left side. I know it means up to 100, so can I say that all the notes in these are all the 8 notes on the left. When will they come to the left of those values, when the range of those values ​​is between mines to infinity, if you come to any node, any value, in this area, the values ​​is between mines to infinity, if you come to any node, any value, in this area, the values ​​is between mines to infinity, if you come to any node, any value, in this area, the mines that belong to infinity, then it will come to the left side of my 8, okay? So if I zoom in and lay down, then similarly, which values ​​will come on the right side of my 8, will similarly, which values ​​will come on the right side of my 8, will similarly, which values ​​will come on the right side of my 8, will they be my 8 and till infinity or can we say like this? Obviously this is non- till infinity or can we say like this? Obviously this is non- till infinity or can we say like this? Obviously this is non- inclusive because they should be given strictly greater, so we can also say seven like this or Take the meaning that this is 8 and not inclusive, if the note is inclusive then all the values ​​less than 8 till infinity will all the values ​​less than 8 till infinity will all the values ​​less than 8 till infinity will come in my left and then all the values ​​except 8 to 8 till come in my left and then all the values ​​except 8 to 8 till come in my left and then all the values ​​except 8 to 8 till infinity will be in my year, those values ​​will all be on my left. in my year, those values ​​will all be on my left. in my year, those values ​​will all be on my left. Coming to the right side, okay, I have come to know this much, so now I can only do the same, I can directly run the recursive function, I can run the recursive function, what else will I do here, pass it here, I will pass it to me - 8 - Infinity will pass it to me - 8 - Infinity will pass it to me - 8 - Infinity Tu 8 This is mine. Range here, the note that will come and similarly, for this mode, I will pass this range and will also keep building, meaning the note that will be built here, that minus infinity, you will be the value of the note, its left range will be the value of the note and similarly, well, whatever. Note will be here and similarly, what will be on its right, the range of its right child will be this, the value of North and infinity, so we have come to know from them also that if we make a note of a route, then in the route to its left, then note dot left. I go to note dot captures left, we will go to left right, okay so we have come to know about this approach, our approach was that first of all I am this mother let that my note exists mines infinity you Right now on Infinity because my fairy order has been given by driver cell, my current route is 8 but which node of the range to the left of 8 will come, Mines Infinity you come which node comes and similarly 8. What will come on the right side of ' and similarly 8. What will come on the right side of ' and similarly 8. What will come on the right side of ' 8 Tu Infinity', what value 8 Tu Infinity', what value 8 Tu Infinity', what value note will come? Similarly, we will keep making requests like this and we will get our answer. So, okay, our algorithm is like this, first of all we will create note and this will happen. Our root note, what are we going to do after that? Second step, Corresponding left range, Android range, you are left and right recursive, okay tomorrow and then what are we going to do after that, our root note, which has been made of our binary, we are going to return, so step. Three will return r route note and created route Okay, so now let's code it once and see, so first of all I'm here lay down I and what will come in this, our dear order one will come because we should know that What will be the value in our note that is being made, so the free order and these two will be our waiting values, then after that we have to go to the next value every time in ours, so this is to track the values ​​and track these indexes. track the values ​​and track these indexes. track the values ​​and track these indexes. To do this, I am going to make an index which will start from zero because our egg zero is of best indexing, so we take this idea equal to zero. Okay, now first of all I will see what will be our base and then after that. After this, we ignore all the bases and now we directly apply our left and right tomorrow and before that, what are we going to do, our first note will be but in the example, we will create a tree note in the pre-order, then this will tree note in the pre-order, then this will tree note in the pre-order, then this will be My tree note root is equal to you value of Well of range and note, this is going to be our right range, this is going to be the right range, so this is going to be the left range which is passed to us and here this is going to be right and now here what is going to be the left range of this is going to return. Now, what can be our base? So, let's see a little about how our base is, if I have some range, if my current note is on in this range, then obviously I do not want to put that note here. Attack and Example: If my five In the right column, Example: If my five In the right column, Example: If my five In the right column, my IDEX A goes from here, so should my seven be placed on the left of five, so this is the color, what does it mean that the range that has been passed in the range of five, this value should come in the range, only then we can We will create a note and attack him tomorrow, if he is not in the arrangement then we are not going to attack, so we can write like this, first of all give the left range, meaning he is also taken from my left, meaning he is going to come to my left. If there is a note then we will not do anything so we will not do anything anyway we will return and now after that if and one base how or yes ke r jati which is if my index itself went out one you three four five if my index What will I do if it becomes six, so here also we have to return null because no index exists in it, because I have gone directly to A, my index has gone to A, equal to the size of the date, so what will I do here? I will do IF I DS = &lt;ho this note is equal you return then if my idea and what should be our left range then when I have seen this in the constant then the value of fairy order of any note is below one. If it is not going to come, then right now my mines infinity can become -1 and my mines infinity can become -1 and my mines infinity can become -1 and my most right range right note will not be more than 1000, so I can keep ₹ 101, my right range will be kept in 100 one can keep ₹ 101, my right range will be kept in 100 one can keep ₹ 101, my right range will be kept in 100 one and this build is beast. What is going to be done, the route is going to return our butt binary, so I return it to BSP, it gets returned directly, okay, it is being accepted and it is also getting submitted, so now we will do it once. If you write it in CPC, you can also write it like this and if mine comes here, okay, now I will create my new route note free order tree, then this will be Renault route, equal to this, here we will pass the free order Okay, what happens is the value is similarly applied in the root right, build GST and we pass the Priya order and now in its left trench right, what is our left range, infinity which is the right range which is already passed, okay then that After we return our route, then we do this tomorrow here in which we will pass and then something else after that, what is the route, created, increased, attacked in the left range route, well in the right, well of the route in the right and right written. The root done is fine, right now it is going smoothly and it is getting accepted, we will try to submit it once and it is also getting submitted, okay, now we will dry it very well and understand what is actually happening. Here is my new page, this is my tree, this is my code here, there is no problem because this will type the content, then the right range which is passed and note, this is our left range, this is this, so tomorrow we will write here our zero 12345 Then what we do is, first of all and we add Idea Plus, so we made a route note, first of all, train remains -1 for 8 first of all, train remains -1 for 8 first of all, train remains -1 for 8 and right range is 1000, what we did is put left yesterday and passed the left range to left range - 1. And passed the left range to left range - 1. And passed the left range to left range - 1. And passed the right range, the value of the root which was eight, okay, then what happens after that, five itself, left range, left goes tomorrow and then N. First of all, we have created this note for 8 and for five. Also the idea gets flooded with you, here this note is created, the route is then flooded with IDEX, now we move from five to the left, tomorrow and one gets added, what does one do by itself, it creates its own route, here IDEX + creates its own route, here IDEX + creates its own route, here IDEX + makes three. And then what happens after that, if he moves his left kal then the left range for one is near this, we will see first of all that for 1 kal is near his left range which is -1 and the value of the note is fine. So when one moves left then the idea has become 3 and here it is inserted seven and what is the left range of seven put here see this is very important -1 then here see this is very important -1 then here see this is very important -1 then left range remains but right range remains one then what? Look logically now, can I hit seven to the left of one, then obviously I cannot hit seven to the left of one, so what we do is we return to our base, how because our base is hit. Where is the value of note pre order of ID Next is the right turn of five, so what do we do, the value of the root, we pass the left range and we pass the right range, but the right range of one, what a relief, five, otherwise this was the value of the root, here and there, the root The value was the left train which is one and the right range was one's own right hand which is five and we put this tomorrow again for 7 and what happens here is again the same, our 7 is that again. Greater is given from one's right range also, hence this seven is again taken from the tag of one, hence one returns and adds five. The one who moves to the right here adds his left range route. Well, which is five and right range, which was eight and again what do we put on seven tomorrow because our IDEX is still free, so you also see our note right now is between the left and right range. This is my left range 5 My right range is 8 and 7 There are some 7's in between that So this note gets created Here from the free note this gets created 7 And then what does Seven do? Seven is its own. Who walks left, passes his left range which is five and right rank which is his own value and passes that do I belong in this range, returns from here and when how does this buffalo return? This goes again, seven moves its right kal, by moving right kal, it puts its own value to the left range and the right range puts its right range, which is what happens from this also we see that the body is still left. And the right does not come in the middle of the range so we do it again I return from this OK what happens now after that we have done the whole left and right tomorrow for the seven so we add the seven Five goes to the right, okay, and when seven goes, then 5 notices that my left and right have also gone yesterday, so I return myself, okay, what happens now, my right goes tomorrow, jitter that. Its value further passes the left range which is 8 and passes its own right range which is and our no relief here is 10 because our idea is four on time also so now we have seen 10 whether I am this I do the fruits in the range 8 and 10 and so yes I do, hence the time is my own note, it is late here and my own moves, then in the left tomorrow, he puts his own left range and right range, he puts his own value and Tomorrow he does index plus here, do I belong in this range? No, I don't belong in this range, so I reduce one, I do return and it goes 12 from here and here to the left. It doesn't go every time, then after that what does the time do? It moves right tomorrow. By moving right tomorrow, it itself puts its value in the left hand and puts 1001 in the right range and does it again tomorrow on 12. Just saw 12. Hey, I do it in this range, so if I bring it in this range, then what will I do, I will make a new note named Create 12 and then I have gone to my left, I will run it by doing Idea Plus, oh mine, it is already finished. This six index does not exist, so how does this one work and we return it, both the writes are done from yesterday also and we return it, then what do we do after this, so the right one catches the body, so Who catches the 10, it goes through the route and strike and it becomes N like this and then what it does with its eight and again 8 returns its own route in I. So our function is completed in this way. If you are free, then you have come to know what we are doing. Basically, every time we will have left range and right range for the note, so this is 7. Hey, we have to make it is okay Ours is okay here, so this is ours. Let's go, let's go 7, first create our note let's go and then it goes, what it does is put the range, left trench which is minus one and right range, adds its own value and after creating the index plus note and G jati hai kal ki isko this four ko then four moves its own left kal in which it passes the left range same and the right range passes its value and this goes on for three our kal no is already made. There is relief in four and similarly now 3 also does the same. Left creates a note before moving tomorrow because with this every time four also likes in one and seven and three is also in this range and like in 7 and then its After this, what does three do, it moves to its left hand, so that here from left hand and right range, three becomes tomorrow, the index becomes ours, here 3 and the result is G, first of all, let's see whether I like in this range - 3 and like in this range - 3 and like in this range - 3 and -1 and in this case I don't bring it, so it's -1 and in this case I don't bring it, so it's -1 and in this case I don't bring it, so it's okay just return it directly. So we are tapping here so returns and puts the value of our writer here again 5 I think tomorrow brother I have to say again that I don't like in this range so I will return again otherwise so then This goes here, this is 3, gone tax, and it goes to its own range, left, values ​​itself, so it notes itself five here, creates and goes to its left, tomorrow, doing IDEX plus, so this is 01234, so now. We are on top of nine, okay, so right now for 9:00 tomorrow, there is a caste that I do not line in this range, so I return, after that five, I move to the right, in which it gives the range to the left range itself. Value and right range of 7 Its rate range Right range of five So again it seems to be tomorrow for nine But 9 has to say again that I do not belong in this range So I return again and Dangal is in the right of five It also happens that it has already been returned, so I return my note to the right of 4, so it goes here and there is five and five, mine also both have gone yesterday, so I return myself to the right of my parents note. In the left side, that's why it is late by 7, what happens now, 7, its right moves tomorrow, due to which it passes the left train S7 and the right range is 1000. Hey, I do it in this range, I take it, so what will I do, I will create. My tree note, so this becomes tree note create and nine passes its left yesterday nine passes its left range 7 and right range 9 passes its own value and when this nine is divided note then the index is flooded with it. It remains index plus from here and we add it here, to get the note, we have to say add. Yes, I also belong to this range, so I myself also add a note, but what happens here, 7 left range and 8 with the right range and our when it's flooded the index is six and which one is this 10 that I don't do it in this range so I'll do return goes and does it in the left range and right Passes in the range on nine but still has to say 10 that still I am not in this range so I will return again so now it is put to the right of ed also from here and after that ed has to be said so I will return my note to the left of my parent, after which I have to say nine. My right has not been moved yet, so I will move to the right tomorrow, I will pass the range, my own left range, and I will pass mine in the left range. My own value which is 9 and in the right range which is my right range which is 10001 and tomorrow we put 10 to say 10, I belong in this range so I will create a new note that is why it is new. Note like this create then 10 your left kal moves what happens and it makes plus when body itself is created then it index plus but what happens now when left kal moves then index is put seven so we This is the condition of the index, hence we return it because no one with 7 indexes does this. Note exists, hence here we tap the return while moving to the left and we tap the return while moving to the right tomorrow also, both of them yesterday. Then the 10 returns to itself, goes to the right of the nine, then what happens after that, the right and left move, so it returns itself and the nine goes to tax and Then what do we do with intake, we have read both left and right from intake yesterday, hence we call return mother function, so this is complete, let's check our code, have we done it right, then everything is correct. It is 7 3 4 7 4 3 4 5 4 9 then 8 then it is exactly like this and we have executed the code correctly so this was our virus got detected there was a little mistake in the driver I am sorry for that But we too, as human beings, will have time complexity of how we are running, because we are creating each mode and there will be space complexity too, so this is its time and space complexity. I hope guys, you have understood this very well, mother? The approach to the problem was that we were defining the color in it and passing it recursively in the range, so that we could know that the node that is my created, then whether the next note will come on my left or right, all this can be determined. We were talking about ranges, that's why when we build binary, we mostly pass ranges only. If we have to create this then I hope guys, you have understood this problem very well and you will definitely solve this problem by yourself. You must also try to run this problem yourself and after solving it and submitting it, do tell in the comments whether I have solved it on my own or have submitted it and do like this video and that's all, we will see you in the next video. Recording of mole length in and
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,743
uh hey everybody this is larry this is me going with q2 of the lego contest 226. we stored it away from adjacent pairs so the key note for this problem is hit the like button hit the subscribe button join me on discord let me know what you think about this form and so forth um but yeah for the key note for this problem is um there are a couple of things one is that making sure that it's unique otherwise if it's not unique then you have to figure out some sort of or lydian path or loneliness psycho depending on how they phrase the rest of it which is not hard per se but it depends on the constraints so constraints are that you know n is 10 to the fifth so you need a linear algorithm but again because this is unique um if there's a solution and i guess they didn't guarantee that there's a solution i was actually looking for that um or just some numbers that has uh yeah so that means there's a path from the beginning to the end so what does that mean right that means that every number will appear in this edge list if you call it that um twice because it has an in degree and an out degree if you want to call it that so then there's only two possible answers really um where you know you have which is just you know going from backwards or from the beginning to the end or the end to the beginning um so the two answers are just kind of like this or the reverse of this but basically what the idea is um well for me what i did is that i put everything in an edge list um i think i do something funky but yeah i put everything in an etch list so that this is much easier to kind of go through um and then i just you know one of these so unless it's a cycle which there are no cycles there's at least there's one place where um well actually decide the two places where a node which is a number has only one edge which is the beginning and the end or you know whichever one you use can be the beginning or the end so i just take the first one and i click i label this start and then that's pretty much the idea is that okay greedily okay i started with to start um and then i removed you know i just removed the previous edge so that we know that the second edge is going to be the next edge and then i add it to the list and i just kind of go in a greedy kind of way because once you choose the first node the rest of the nodes are forced um and what i mean by that is that you have no choice this will always contain only one node always um if you do it correctly by removing the previous node uh from the edge list so once you do that uh there's only two possible answers depending which um which node you pick to start so yeah so what is the complexity of this well it's going to be linear time uh because you know um redefining the edge list is going to be linear uh in terms of the um yeah it's linear this is a linear uh um loop and this is a linear loop so everything is going to be linear and all these takes over one so uh so yeah um so overall this is linear time all together in terms of space because we kind of put the list in a better easier place to look up um this is going to be um of n space as well so and in this case there is a distinction between edge edges when we say linear there's edges and vertexes but because this is um a linked list or if you want to call it that um there's um the number of edges is going to be n minus 1 or the number of nodes minus one so in here o if n is you know so there's gonna be o n nodes and edges so when we talk about linear time and linear space even though technically if you want to be specific they're referring to two different things uh it's fine it's linear time linear space uh that's all i have for this problem you can watch me solve it during the contest next you there c you uh yeah thanks everybody for watching uh let me know what you think about this problem i didn't do that well on this contest just based on some things that if you watch the contest video hopefully you'll see but yeah um hit the like button again hit the subscribe button again join me on discord again um and hope y'all have a good day take care of yourself if you have the fortune you know take care of others um to good health stay good stay well you know and pass it forward and you know treat people around you well um and to good mental health and i will see you next problem bye-bye
Restore the Array From Adjacent Pairs
count-substrings-that-differ-by-one-character
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Hash Table,String,Dynamic Programming
Medium
2256
1,646
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video this time guys we are going to solve question number 1646 get maximum in generated array which is a dynamic programming question before i started the video guys just want to request you that if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications a more such programming and coding related videos let's get started with the problem statement now so basically guys we are given an integer n and we are going to generate an array with this integer n it is a zero indexed array that means if we are given an integer n the r is going to have a size of n plus 1 and the way we are going to generate this array is that the 0th element that means num 0 is going to be 0 the first element the index 1 element is going to be 1 but after that if the index is even that means 2 into i so that means if the index is even then uh the nums 2 into i will becomes equals to nums i so basically if it's even you just have to uh half that value the half the index and that will become the value of that even index and if it is an odd index so if it's 2 into i plus 1 then in that case it will become equals to nums i plus nums of i plus 1 that means if it's an odd uh odd index then you just have to find out the value of the nums array at its middle element and its midi plus one element and just add them up and that will become the value of the odd index of that particular array okay uh and after that once we have created this array we have to return the maximum integer in the array numbers uh so here you can see in the example guys when n is equals to 7 obviously num 0 and 1 are 0 1 but for n equals 2 of for i equals to 2 the value becomes equals to nums 1 so obviously if it's an even index then you just have to half the index and that value will become that value of that half index array will become the result so in this case for 2 if you have 2 you will get 1 so that's when nums 1 is actually equal to nums 2 which is 1 and if it's odds for example if it's nums 3 the index is three so in that case we have to find out the middle element and the mid plus one element so for index three the middle element will be the index one element and the mid plus one element will be the index two element so we have just summing those two and then we get one plus one becomes equal to two and so on and so forth uh you will keep on doing this thing and finally we have to find out the maximum value so obviously the error is this uh this array and the maximum value is three so that's what we have written um all the other examples are also similar guys this constraints are very straightforward uh the value of n ranges from 0 to 100 that's the only constraint now let's jump to the solution part guys so the first thing which we have to do in this solution is to check if n is equal to 0 or if n equals to 1 because if it's 0 or 1 then it is pretty straightforward then in last case the maximum value we already know right so if it's 0 then we just have to return 0 but if it's 1 we just have to return 1 because that becomes our maximum value if that's not the case then we will just declare max variable and i am going to by default it to 1 right because if n is equal equals to if n is greater than 1 then the minimum value which we can have is one so that's where default the max value to the uh one value and then i'm going to create the nums array so this nums array is going to be declared as a n plus one um size array because uh we have a zero index static right now in this num sorry guys num zero will becomes equals to zero and then nums one will sorry nums 1 will becomes equal to 1 because that's given to us in the description as well now we are going to start our for loop and this for loop is going to get started from 2 to i less than equals to n i plus okay now as i stated to you guys if i mod 2 is equal to 0 sorry if i mod 2 is equals to 0 that means it's an even element so if it's an even element or if it's an even index then nums i will become equals to you half the index and you find out the value of that half index so nums i divided by 2 and that will actually becomes equals to your num's value okay in the second case when we have got our odd value right so if we have got an odd value then we have to find out the middle element and the middle plus one at the element so middle element is i plus two right and what is the mid plus one element that is i divided by two plus one so that will becomes equals to mid uh plus one at element you just sum both these values and that will become equal to your num side and finally guys once this if else is over we are going to check the maximum value so the maximum value is going to be either the existing maximum value or the num sayeth value whichever is greater and finally when this for loop is over we just have to return max so let's run this code guys let's see if this works for our example cases and i'm just going to submit it as it has worked for one of examples yes and there you go guys you can see that it is submitted successfully talking about the time complexity now so the time complexity for this solution is going to be order of n guys because we are going to have a forum which is running from 2 to n so approximately n times and that's why the time complexity is order of n space complexity is also order of n guys because we are creating an array of n plus one element okay so that's why in big notation you can say that space complexity is also order of n because we are storing an elements in a error okay so that was the video guys and that was the solution i hope you guys like the solution and i hope it was clear to you if you did like it guys and please do not forget to like this video and share this video with your friends if you have any questions comments suggestions feedback if you have any better solutions please post them in the comment section below i would be happy to address your comments and guys india please do not forget to subscribe to my channel and hit the bell icon for future notifications of more such programming uh videos thank you so much for watching i'll see you guys in the next video until then take care and bye
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
693
Hello everyone welcome, today's problem is alternating bits, so in the problem statement we are given a positive expectation and we have to tell whether alternating beats are present in it or not, like mother, take the first example, N = 5. So mother, take the first example, N = 5. So mother, take the first example, N = 5. So if we represent it in binary, it will be 101. So in this we can see that there is a gent on the alternating beat, like there is a zero after the van and then a van, so how will we solve it, so let us see that to solve it. How can we do this? So mother, we have a number three, okay, so if we do it in binary, it becomes 101, so this is the alternating beat, after van, zero comes after that van, after that, zero is okay, so in this if Let us see one thing that if we shift it to the right or if we shift it from van then it will come zero van is fine and after that if we push it hard then you will see the result that it will come 1111 meaning. In this, all the van numbers of vans will be presented. It is okay that it has been changed in both of them, like these equals were 10, earlier it was 1010, okay, now if we change it with right shift van, then the beat which is 101A means it is gone. Which was earlier the zero, now it has become one, then one has become one, then zero has become zero, so after emphasizing this, if there is opposite in both the numbers, then one will go to one, okay, so now we have to check it, one will go to one, then one will go to one, okay, so now we have to check it, I will write because our Also, the numbers with alternating beats will be present. If we shift one of them to the right and push them together, then all the Vansh will always be present in it. Apart from that, nothing can be present. Zero will not be present, so we have to check it manually. That if after our emphasis and after applying this formula, if all those numbers of One See are present, all One See are present in it, then our number with alternating beat will be there, then to check this, we will look at the concept of Power of Tu. So, what should we see in Power of Tu, like anyone, like Power of Tu, it was in the boundary of $100, okay, so was in the boundary of $100, okay, so was in the boundary of $100, okay, so see the one before that, in which there was seven, only van was present, okay, see van zero in 16. Zero and the one before that then there was 1%, so then there was 1%, so then there was 1%, so here what we have to check is that it is only van, we can do this by saying that if we add van in 15 then it will be 15 in decimal. There will be 16 and after that if we take the end of 16 and 15, if zero is taken then we will be able to approve that only one is present in all the lineage, like here we take the end of 8 and 7. If given then it goes to zero, here also we end it, so we have seen it, so now let us see the time complexity of it, time complexity is done, so now let us port it and see, after coding, understand it well. We will come to know whether only Vansh is present in it or not, then almost what will we do? We push N after shifting right from the van, it is fine and after that we just have to return it. What was the next step, we should check whether you are power off or not, if it is okay then return it all once is ours and end it so if we see here which is ours this is all once and all once plus one if this is ours If zero comes then it means we have alternating beat and if zero does not come then there is no alternating beat. It will return false. Now let us run it and see. After running, all the tests have been passed and now the final submission. Even after doing this, our code has been finally accepted, ok then thank you, see you in the next video
Binary Number with Alternating Bits
binary-number-with-alternating-bits
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. **Example 1:** **Input:** n = 5 **Output:** true **Explanation:** The binary representation of 5 is: 101 **Example 2:** **Input:** n = 7 **Output:** false **Explanation:** The binary representation of 7 is: 111. **Example 3:** **Input:** n = 11 **Output:** false **Explanation:** The binary representation of 11 is: 1011. **Constraints:** * `1 <= n <= 231 - 1`
null
Bit Manipulation
Easy
191
106
Wedding Welcome To My Channel Today 2070 Problems Constructive Manner Retreat From India And Posters Given In Adhir Veervati History And Subscribe Button More Benefits Loot That Similarly In Post Operative Ward Process Factory 's Combustion Lights Of Tree 's Combustion Lights Of Tree 's Combustion Lights Of Tree That And Followed By Root Not Show In Poster Traversal Also process route Hindi and in order to make subscribe The Channel receiver and after the poster of the year poster and ministry of railways etc that divide is in ordinary from into to subscribe will look like this president in the subscribe The Channel subscribe this Video give blocked and are no Hindi meanings for the 207 Similarly su in the processes of trees will provide you first will divide factory se gas leakage the poster pair to initially started one intake which is the largest value of To Three Idiots I Will Reach The Chapter Note Subscribe Must Subscribe The Look Into This Part Of The Thursday Subscribe 20000 Subscribe A For Solving This Will Use This Start The Start And Index For The Immortals Are And Even In The World Which Will Keep Trek didn't want to process for the post Amazon is the root of the water subscribe and subscribe the entry loot new of a tree node a half bureau ninn postering posts the order turn off index this lineage foreign nominated to right poetry first loot dot right you All to call the same method constructive and investment also a brief and dispassionate call receive judge in axis in root index is lineage what do you live say stop this rights act which come under root x plus one correct on the road end x plus one end Will be the same The volunteers of left parties Will become start SMS Start editing and destroyed and will come in Noida Route The Index - 1972 Calculator index for Index - 1972 Calculator index for Index - 1972 Calculator index for the white part among simply Index - 1st the white part among simply Index - 1st the white part among simply Index - 1st in the same and following a sister pimples and poster of fate all this Tree so how will get this indicates a first for the first life itself so isi VPN axis hair second and routine and width and minus root that induces will get the number of notes in our life history Danveer Sector-21 from life history Danveer Sector-21 from life history Danveer Sector-21 from the power index we will get This point which here and after doing to subjective which will give the indexes assembly will solve error code for the same approach should be constructed from do subscribe my channel and will not mean that will win from the poster subscribe The Amazing The value of the not from Do you will find a co stop this loop and recorded in order to take back after doing all the rights of vs subscribe to that filmi ki accepted software at the same time complexity software running open request solve every time she these findings in the case of subscribe and 30 Boys Poster 12345 I will withdraw subscribe that Mahesh map and write the indices of between note value in to our map new house map 200 hair for per in ICC Twenty20 violence in order dot length that i plus that that that is an inverter of I Co My Life Very We App Software Institute Of Checking For Daru Vijay Best All Check Dam Bay Index Problem Map Don't Get We Poster Turn Off Indus Valley Number Oven Thanks And This Algorithm Is Used In It Equal We Folding Bed Time Complexity Of This Approach Will be the work and some descent user time festival videos to off wild space complexity will increase to go for a jewel I am safe so second advisors for it is a defined the global time app you can create a local copy and pass uniform reaction calls In every day this method call 100 thank you left me solution satellite button and subscribe my channel thanks for watching see you again
Construct Binary Tree from Inorder and Postorder Traversal
construct-binary-tree-from-inorder-and-postorder-traversal
Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** inorder = \[9,3,15,20,7\], postorder = \[9,15,7,20,3\] **Output:** \[3,9,20,null,null,15,7\] **Example 2:** **Input:** inorder = \[-1\], postorder = \[-1\] **Output:** \[-1\] **Constraints:** * `1 <= inorder.length <= 3000` * `postorder.length == inorder.length` * `-3000 <= inorder[i], postorder[i] <= 3000` * `inorder` and `postorder` consist of **unique** values. * Each value of `postorder` also appears in `inorder`. * `inorder` is **guaranteed** to be the inorder traversal of the tree. * `postorder` is **guaranteed** to be the postorder traversal of the tree.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
105
1,802
so hello everyone welcome to this new video and i will be explaining the problem maximum value at a given index in bounded area so this problem is exactly medium one and you know this kind of problems uh are become i have realized that they are asked regularly these are binary search problems so in this video first i will be explaining this problem through an example and then i will code it so what the problem is basically saying is that i have been given an array okay and i have been given a particular index and i have been given a particular sum the sum of the array has to be in the limit of this maximum sum and i have to increase maximize that particular index okay keeping these conditions in mind so these conditions are that the sum of adjacent numbers should be different should be less than equal to one and basically the sum of the entire area should be less than the maximum sum so let's understand this problem more clearly from this example so in this example let's see this is a let's see this example so this in this example n is equal to 6 and index is equal to 1 so and the maximum sum is 10 so what i have to do is that i have been given an array of 6 and i have to maximize the index that is present at 10 uh sorry at 1 and the entire sum of the array should be less than what it should be less than 10 okay so let's see so what i will do that i will just do it by fixing instead of thinking that what i have to do on the left side and do what i have to do on the right side what i will do is that i will fix this number and then calculate that okay what can be my possible left side and right side okay so for example if i say that okay let's fix my number to 10 then to minimize the sum of this entire array what i will do and keeping in the condition that the difference between adjacent should be less than equal to one so what i will do is that i will write this as 9876 and in the left side i will go nine so the entire sum here is going to be i think somewhere around 30 or 45 30 i guess so in this is not satisfying this condition now what i will do is that i will uh go for say nine in case of nine these things are happening uh the sum is still going to be uh more than ten okay so now uh and so on uh i will commit four uh at four what i do is that okay to keep the conditions valid i will write this three this two this one and after that after one i can't go below one because it is given that all the elements in the array should be greater than 1 so in that case i will write 1 only so here the sum is going to be what it is still going to be less than 10 uh greater than 10 it is i think 14 but in this case 3 2 1 so it is what 5 8 7 so in this case the sum is 7 so this is a valid case and everything is being satisfied so my answer will be 3 because so that's the thing so to do this there can be two ways so either i can go from 10 all the way down here so this will give me a time limit exceeded or another thing is that i can use binary search okay so what i will do is that first my maximum sum is 10 and the minimum sum that i can reach here a minimum target value i can reach here is one okay so the first one let's say first i will take something as five okay i will explore five and see okay the five sum is some let's say it is one thousand and i will realize okay it is one thousand now i have to go down so then i will go to 2 at 2 i see that it is its sum is less than 10 so i will go up so you know in this way i will arrive at my solution more quickly so this is the idea so now let's code it i will it will become more clear as i code it so let's begin let's go full screen please subscribe to my channel a lot of my viewers are not subscribed so if you are a regular person here please consider subscribing okay so first of all for what i will do is that i will make a few integers variables in r is equal to n minus index minus 1 so what r is basically just let me clear this so r is basically the number of empty spaces in the right side and i will make another variable l that is going to be the number of empty spaces in the left so in this case it is 4 r is 4 so and then i will i'm using long because there is a integer overflow if i use int okay so l is equal to what index means it means that uh basically one is on the left one only one empty space is on the left now i will make uh more variables long high is equal to what max sum maximum and long low is equal to one so these are going to be my initial high and low for the binary search and i will make another variable called long res is equal to zero this is going to be my maximized value okay now what i will do is that i will write a binary search so while low is less than equal to high what i will do is that i will take long mid is equal to what high minus low by 2 plus low so this is also done to avoid integer overflow but in i have tested it you can also write high plus low by two so and now i will make another variable called long sum so sum is equal to initially mid initially it will be mid uh you know why because so suppose uh after doing this i arrive at six so i will have my sum some will initially be six then i will calculate this thing and this thing okay so initially the long sum is mid and long ls is equal to 0 i will explain it what this means long rs is equal to 0 and long m is equal to mid minus 1 so just so l s is basically the sum on left and r s is sum on right for that particular so for example in this case ls is what five plus four nine plus three twelve fourteen ls is fourteen and rs is five and m is m i will use it to calculate this uh sum so m is basically a five and will be five uh as it is clear m is mid minus one so i will have to calculate the sum now from two to five so that is why uh not six so that is why i have just made it m it is just for convenience so now there can be two possibilities so the first possibility is as you can see uh you will see here that in this case let's see this case so in this case this sum is going from 9 to 6 okay so it is fine i can do there is a formula to calculate sum of n natural numbers i hope you will be aware of it n is equal to n plus 1 by 2 so in this case what i can do is that i will calculate the sum of 1 to 9 and then i will subtract the sum of 1 to 5 to get this particular sum okay i hope it is clear to you uh so it is fine but in this case say see this case in this case my 2 1 is going to get over here and i will have to add extra ones to fill this array so this will be a different case this will arrive when uh what my m is the number of spaces here is uh more than m so m is 2 but the number of spaces here are 4 so in this case i will have to add extra ones so these are some things that i will write and i will explain it so if r is less than equal to m right side then what i will do is that rs will become what m into m plus 1 by 2 subtracted by what m minus r into m minus r plus 1 by 2. so i hope you are understanding this is just what uh to calculate this sum from uh 9 to 6 what i will do is that i will uh just from i will calculate the entire sum from 1 to 9 and subtract the sum from 1 to 5 natural numbers to get this particular range so this is what i am then done else for else condition i am going uh looking for this kind of situation where i have to fill extra once to complete my array so in this case my rs will be what m this thing will be same control c control v and i will add some extra ones one into what how many extra ones i will add that will basically be r minus m so you know i strongly suggest you that please pause the video and let this thing sink in that what this max of match formula means okay then you can move forward so in this way i have calculated the right side now i will calculate the left side so in left side also they are going is going to be a similar condition if l is less than equal to m actually this is all going to be same control c control v so instead of l i am rs i am going to write l s and instead of m minus r i am going to write m minus l and here also it will be l so it is just a replacement uh just a second now what i will do is that i will calculate my sum so what sum i have arrived so far so the sum will be what some sum plus equals to ls plus rs okay now i have arrived the sum at this particular say at this particular what case i was at i at this particular case what is the time it is 11 minutes okay so now what i will do is that if the sum is less than equal to max sum then i will simply res is my update my result is equal to mid and i will increase my low is equal to mid plus 1 and if else if the sum is exceeding the maximum sum that means that i will have to reduce my high so my high will become mid minus 1 and that's the problem it is done and in the end i will return res so let's decrease the font 12 pixels so i think that is done let's run this code to check if there is any error it is running fine now let's submit it is 100 faster in both time and space so it's a pretty good thing so you know if the problem is clear to you please consider subscribing my channel and have a nice day good bye
Maximum Value at a Given Index in a Bounded Array
number-of-students-unable-to-eat-lunch
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of all the elements of `nums` does not exceed `maxSum`. * `nums[index]` is **maximized**. Return `nums[index]` _of the constructed array_. Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. **Example 1:** **Input:** n = 4, index = 2, maxSum = 6 **Output:** 2 **Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\]. **Example 2:** **Input:** n = 6, index = 1, maxSum = 10 **Output:** 3 **Constraints:** * `1 <= n <= maxSum <= 109` * `0 <= index < n`
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Array,Stack,Queue,Simulation
Easy
2195
73
hello everyone welcome to day 13 the focus liquid challenge and today's question is set matrix zeros in this question we are given a matrix of size m cross n where each element is kind of an integer and we need to set the complete row and column if this current element happens to be 0 let's talk about it by an example in this matrix this element is 0 as soon as we find the 0 we need to mark all the elements in that entire row and column as 0 and this is what we need to do let's talk about this example as well these two are 0s in this matrix that means this complete column this complete row and this complete column should be marked as zero we need to update the matrix and return it in the answer the question says you must do it in place so we will go step by step we will use some space and then we will try to optimize it uh so that we don't have to use any extra space for it so without much to do let's look at the solution set matrix 0 lead code 73 so let's talk about the same example that was specified in the question the matrix that we have is something like this 0 1 2 0 3 4 5 2 1 3 1 5 and what we can do in the first approach the naive approach uh we can store the indexes of all those rows slash columns which needs to be turned off or set to zero so you start the iteration and let me just write the column index and the row index zero one two and you start you then you start the iteration the first element that you see is zero that means you need to mark the row starting with the zeroth index the zeroth row to zero and zeroth column to zero and you continue the process next we have one next we have two next again we have a zero that means you need to mark the complete column the third column as zero so you add it to the column list and obviously you add again the zero back so let's add the zero back you can create a set for it you can create a list for it set would be optimal then a list then you go under the iteration you have three four five two one three one five let's hypothetically assume instead of this one we had zero then we would have added the second row and the second column to our list so 2 gets added to get started now what you are going to do you will iterate over these row indexes pull out elements one by one and mark the complete row to zero so uh the first row that get two index that could pull out is zero so you mark the complete row as zero then again we can create a set for it instead of a list so it won't be repeated then we have two so this complete row will be marked as zero is zero similarly for the column part the zeroth column is three mark zero so this is gone the third column is to be mark zero this is gone the second column has to be marked as zero this is gone what is left is only four which is the answer assuming we had a zero here not a one i hope you got the context i hope you got how it is to be done and let's talk about the optimized solution now let's hypothetically assume that this is a matrix that is given to us 1 2 3 4 32 1 0 5 7 0 10 14 0 1 8 also i forgot to mention the space complexity here would be equal to order of row count plus column count row count because at max these sub arrays these arrays can have n number of rows and this array can have a size of m columns row count plus column count and can we optimize it further the answer is yes let's go ahead with the optimization instead of using extra space we will do it in place as soon as we find the 0 what we are going to do we will mark the starting of the row as 0 as well as the starting of that column as zero so let's assume this is the first zero that you encountered by light returning to the matrix and you simply update the first element at the at this particular row to zero similarly the first element in this particular column 2 0. now let's continue the process the next leader that we see is in the third row so you update this to 0 as well as this element to 0 next we have is this 0 you update this 0 to 0 this element to 0 and this element to 0 you are basically updating the first element in that particular row to 0 as well as first element in that particular column to zero and now the matrix is something like this one zero what you're going to do the first thing that i have done here is to uh define two areas that will store the indexes of those rows that are to be marked zero the indexes of those columns that are doing marked zero i start iterating through the complete matrix one by one and as soon as i find an element that is to be marked that is currently zero i update the row zero array uh to add the i gith row into it similarly i update the column 0 variable to add the jth column in it and then i start iterating uh through the these arrays row 0 and column 0 and for each row index that is retrieved from the row 0 i mark it as 0 make row 0 i have to find another method that accepts two variables the matrix and the row that is to row index that is mark 0 similarly for the column part and once i'm done with this i simply return back the question reduces to defining and writing this these helper methods appropriately so i have the matrix and the row index i start iterating in a column wise fashion j equals to zero j is less than matrix at the zero index dot length the number of columns that i have j plus i mark the r index row to zero similarly i have defined a private method make column zero i go uh start i go from i equals to zero i is less than the number of rows that i have and i update matrix of i comma the c index the column index that is we mark zero as zero and simply return back let me just submit this solution accepted the time complexity of this approach is order of m into n the space complexity of this solution is again order of m plus n where m n stands m and n stands for number of rows and columns that we have let's talk about the other approach where we are not using any extra space it's a slightly lengthier method but it's very simple so uh i have extract i've checked whether the matrix is not null extract those them and two variables the number of rows and number of columns that i have i'll talk about this later on uh but let's look at the com the actual logic first as soon as i uh find a 0 in the matrix i update the starting element of that row and starting element of that column to zero and i reiterate uh through uh the complete first row and first column and check if my element happens to be the first element happens to be zero i nullify the column as similarly if my first uh element happens to be zero i nullify the complete row this is what i explained in the presentation as well this slide kva to it you need to also check if my first row and first column has already has a zero in it or not if that is the case then we explicitly need to handle it in the end we need to mark the first row as well as the first column as zero explicitly so i've defined two variables here first row has zero first column are zero i start out rating through the matrix only in the first row and if there is a zero in it i update this variable similarly for the first column has zero and once i have those values i simply nullify the zero way through and the zeroth column to zero using nullify row and nullify column i hope you got the context uh we are doing it in place the time complexity is order of m into n and the space complexity is constant space i hope you enjoyed today's session if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more update from coding decoded see you tomorrow with another fresh question on lead code good bye
Set Matrix Zeroes
set-matrix-zeroes
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm). **Example 1:** **Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\] **Example 2:** **Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\] **Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\] **Constraints:** * `m == matrix.length` * `n == matrix[0].length` * `1 <= m, n <= 200` * `-231 <= matrix[i][j] <= 231 - 1` **Follow up:** * A straightforward solution using `O(mn)` space is probably a bad idea. * A simple improvement uses `O(m + n)` space, but still not the best solution. * Could you devise a constant space solution?
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
Array,Hash Table,Matrix
Medium
289,2244,2259,2314
21
welcome to january's lego challenge today's problem is merge two sorted lists merge two sorted linked lists and return it as a sorted list the list should be made by splicing together the nodes of the first two lists we're given two linked lists here and they're going to be sorted and we want to merge them together to return a single sorted linked list now the way that we solve this is by having two pointers and basically creating a new linked list by traveling down both of these two lists and whenever we find that one is less than the other one we add that to the output array and then move the pointer ahead and then continue that loop to compare which one is less than the other once we reach the end of one we just add the remainder of the other list into that output array and that's it so to do this what i'm going to do is create a dummy node and the output and we're just going to make this a list node that's empty and the reason we need two is this dummy node is going to point to the head while the output is going to be like the current node that we're pointed on so while there's both the l1 and l2 we want to check to see which one is greater right so or which one is less rather so if l1 dot value is less than l2 that value then we want to add this l1 uh to our output so what we'll do is say okay output.next is equal to okay output.next is equal to okay output.next is equal to l1 and then we move ahead our l1 to the next one l1.next l1 to the next one l1.next l1 to the next one l1.next now otherwise we're going to add l2 to the next so open next equals l2 and then we move ahead our l2 to the next and make sure we move ahead our current pointer output is now equal to output.next now output is now equal to output.next now output is now equal to output.next now once we're out of this loop we just need to add the remainder of what remains to our output so if l1 remains then we'll add that to output.next up index equals l1 to output.next up index equals l1 to output.next up index equals l1 otherwise if l2 then output.next equals otherwise if l2 then output.next equals otherwise if l2 then output.next equals l2 finally we just return the dummy.next which is the head so let's go dummy.next which is the head so let's go dummy.next which is the head so let's go ahead and submit that um see if this works looks like it did all right and accepted so this uh is going to be a o of n time complexity and i believe it's the optimal one uh there are other ways you could do it but you know this is kind of the generally accepted way so all right thanks for watching my channel and remember do not trust me i know nothing
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists `list1` and `list2`. Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists. Return _the head of the merged linked list_. **Example 1:** **Input:** list1 = \[1,2,4\], list2 = \[1,3,4\] **Output:** \[1,1,2,3,4,4\] **Example 2:** **Input:** list1 = \[\], list2 = \[\] **Output:** \[\] **Example 3:** **Input:** list1 = \[\], list2 = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in both lists is in the range `[0, 50]`. * `-100 <= Node.val <= 100` * Both `list1` and `list2` are sorted in **non-decreasing** order.
null
Linked List,Recursion
Easy
23,88,148,244,1774,2071
96
Hello friends welcome to my channel let's have a look at another unique binary search trees problem 96 in this video we are going to continue the video on problem 95. in problem 95 we explained how to build all the unique Banner searches by recursion so this problem here concerns the number of unique banners to trees in other words content so first I'll read through the statement to recall the requirement and then we analyze the problem and finally we share the code uh here given that integer M we are required to return the number of structurally unique bsts which has exactly nodes of unique values from 1 to m so here are two examples with the corresponding ends and corresponding outputs so before we do the analysis let's look at the constants so here n is bonded below by 1 and upon it above by 19 right so this number in itself is not a large number so with that said we have a feeling about the problem size so now let's look at the analysis so in this problem so if we understand the construction of unique Banner searches actually it's straightforward to do the counting I would see actually this two problems are sort of the same just one cons on the specific trees and the other here counts the numbers so here are several points first if we have no nodes or just one node so the number is one right there's only one Banner search tree secondly if we have n nodes with distinct values let's take one two up to n for example then we could choose any one of the nodes as root and then let's assume that we choose a number I it could be the node value as a root so then we need to use 1 2 up to I minus 1 to build the left subtree and we use I plus 1 to n to build the red sub tree so due to the binary search property so when we build the search phase so this procedure recursively continue so that's the main idea now let's look at the numbers assume that we have a function f which if we give a number of nodes we're going to compute the number of unique balancer trees so here are the actually the recursion relation so FN is nothing but the summation of the different summation of the product of different level trees and different respiratory lastly choose we have chosen a node with value I so here um there are I minus 1 numbers less than I so we have I minus 1 nodes for level super 3 that is F A minus one so this is the number of different left slip binary search trees so similarly if we look at the red sub tree so there are n minus I knows so all n i minus I values greater than I so this F in minus I is the number of different red sub Banner searches so here I runs from 1 to n so this actually is the recursion relation or a DP updated rule if we want to use dynamic programming the next line actually is a change of variable so if we change the summation with respect to I to be with respect to G so we'll let g equals I minus 1. so then this summation is nothing but FG times F and minus 1 minus G so previously I runs from 1 to M now G runs from 0 to n minus 1. so this second equality it means to make or establish a connection with the constant number CM so if we look at the second equality this number is nothing but the constant number cm so therefore to get the number of unique balancer cheese here we could do either of the two following statements first we use DP so this is natural and actually routine if we do not know the cutting numbers secondly so we can use the continent number recursion formula so the recursion relation for cutting a number let's use C from an N to demonstrate the N some calcium number so this rating is just for communist of ready right so here and if we initialize a start so at zero it's one and one out actually is also one then this is the recursion relation so with that side now we can look at the code actually for the code it's actually very standard a routine so here first I'm going to write a DP solution for the DP solution so I'm going to um because it means count so I'm going to use cons so 0 times um M plus one so in other words count I means that if we have I and distinct values how many distinct beneficially right so we're going to return count M right so notice that in this initialization we used a list of length n plus one right so in this case the last element has index in right so const zero should be one right so if we have no nodes so this is what so now we just need to use the recursion RDP updated row here so now let's do this basically it's a um DP update rule or relation so this is a for Loop for I in range um well up to M plus one it means that we choose value I as the root value and then we are going to add the scenes together for J here range 0 to I so let's emphasize zero right so because left symmetry can be empty tree so here are counts I can incremented by this case right in other words if we have G nodes in the left subtree and then we have um count Pi minus G minus one knows in the rest of the tree right so this actually this updates um is doing the update according to the scene here right so here you can understand that for this all right fixed for fixed I we determine how many different um unique balance of cheese if we have in total I know right so what we're going to do to return actually is can't pin rate so let's directly return this so with that said I guess that's about it for this specific version so let's do a check yeah it passes the first example so now let's look at the generic case it passes the generic case so with that done so let's copy this function signature and then let's use the cotton number so I'm going to call this first version will be one so now let's use a couple in number so I'm going to use a recursion relation in a sense of mathematics so we are going to use this formula right so here let me initialize a result variable so initially what then we are going to iterate intense right so for I in range n right and then the result equals the first result times the factor here the factor so it's 2 times I plus 1 and the integer division by I Plus 2. so lastly finish this um iteration or for Loop so we can return the result stage so actually if we like actually there is a formula for this content number in terms of factorials like here so you can do this directly so you can get more information on categy number in this Wikipedia page so with that said let's do a check it passes the first example now let's look at the generic case that's about it for the second solution so I guess that's about it for this specific problem so um here actually the version V1 as more natural so if we do not know the counting number right in mathematics so with that said I guess that's it for this video thank you
Unique Binary Search Trees
unique-binary-search-trees
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. **Example 1:** **Input:** n = 3 **Output:** 5 **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 19`
null
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
95
279
Perfect square which is here, we have given, so our people solve it, let's see how our people will do this, first of all we read the question problem statement, what do we have, then inside the question we have a wait and given, we have to return. List number of perfect square number tu dat sam tu n ok hai as here I am our people can take it as an example in a way let's suppose for example date is given tu as sam this is an example with this we all can understand the question as a Let us understand what is actually said in the question, okay, inside the question we have basically said that let's suppose for example, we have the value of n given, okay and given is our own, we have the value of n. If we are given 12 then other equals are equal to 12. Here we have basically got 12. Now what we have to do is we will read to find the numbers which we have which are perfect square and whose sum we get equal to 12 like. Let's assume for example four plus four, what will be its value here, what will we get here will be equal to 12, okay can we have any other thing, see here it is said that the perfect Is it a square or not, that van is also there, starting from van, okay 149, all these are examples of your perfect square, so from four we have a perfect square, so I will sum it, then we will have the answer which is basically, will anyone else come out? We all can do this. For Sam of Han 12, the second approach is basically that I select nine once and then select Van three times, this also we will have basically equal to 12 but the number of coins here. But how many will we have here? If you see, the number is looking like three. We will do the number of time. They are also picking three times from us. Okay, and from the number of time, I will do the combination of 91 here. So here we will have. Basically there is 4A and what combinations can there be or look at the combination box, okay here the solution that we can have is what do I do 12 times take 1 okay so this is what we have basically The problem is given to us, which is basically the minimum number of times that we have to perfect, the sum of which will be equal to the given number and end, as if we have given one more example, it is in the test case itself, as if we have given 13. So, what can we pick for 13? Okay, either what do I do, I take the phone four times, three times and I take the man once, so here we basically have four times four, we will have the answer or what? You guys can take one, okay, we have the minimum which will be there, so we will have to return only that, okay, so this is the basically given problem we had, right, now look at one thing, is this the problem which we have discussed in the old topics? I am reading some link from any of them, I am getting it. Okay, look here what combinations we have. Look, first of all, what have we all done till 12th, we have given. What if I basically first collect Let me take all those numbers which are perfect squares which are less than n like 12. Okay, I will rub all of them once. 10 minutes is okay. Here's what you have to do. First of all let's suppose for example, what dreams do we have ? We are doing the trick for this, ? We are doing the trick for this, ? We are doing the trick for this, people think that how can it be possible, there will be 12, then whatever square number we have, which will be a perfect square, we all write those numbers which are less than 12 in Eric first. Okay, like, and the value we have is date, this given date is 12, what do I have to do, I will basically pick any one number as the true date, we will have its value, we will basically get it, so this is the given problem, this is our Looks like it happened somewhere nearby, okay, this is the problem, basically we have one coin change problem number 2 coin change tu hai, two hai apke coin change tu hai, okay so this is the question, if I am like this So, basically, whatever perfect square we have which is less than n, I will make it, I will find it and fit it inside the circle, then we will have the question which will be exactly like the coin exchange problem because look, we have one four nine. It is given that basically we will have coins in one way. Okay, we will have coins in one way. If you have problem of coin change then okay, I am going to give you the link. Okay, I will tell you if you do not understand. When it comes, you should watch the rest of the video because I am going to complete it, so here we will have coins given. I am telling the coin change problem here, basically the total amount of value that we have will be given. Okay, now what do you want? We will have to give the minimum number of coins. We will have to tell the true date. Whatever sum we have, we will have it equal to 12. Okay, so this is what we have here, whatever is 9 and 4. Sorry, whatever is here, we will have the answer. 44. It will be okay, so let's go to the problem, so friend, I have understood the perfect square, we all have to basically pick the numbers from it, of the true date, we have selected the minimum number of numbers which is this same. Let's get equal to the record, we will focus on the approach. What is approach in open hockey? Okay, first of all, our people understand, so what do we have, 149 is given, brother, I give the team to everyone, what do we do? First of all, we will do the bottom approach. If we say in the bottom then we will go from bottom to top, so first of all we come to nine, I have fixed the index here, okay, I have fixed the index here, if it is big, then only here I will be able to select it, okay. What is meant by not selecting is that if its value would be bigger if we have it, see like if we had 16 here, 16 would not come. The first thing is fine, then putting a condition on it is a different matter because we Whichever number has been allotted by all the people earlier will not be less than these, nor will it give you a billion, nor will you have a number less than N. Whichever number you have will be a perfect square, like if it was 149, then all of these will be less than 12th. People will create the functions in such a way that they will give less value than it takes, so in this case we will basically have a choice either you include it or you don't include it, okay here we will reduce one variable. We will create it, there will be two choices inside it, either include or not, if I include, what will I do, I will subtract from the value, whatever we have is the value of the index, I have included, so what will happen here, once with this Added it and here we have the value, in this case, 12th minus three, okay, I will show you, okay, before that let us look at the code once, as much as I have done, this is basically the code for starting. Whatever I have told you, let me tell you what the people of Apple have done, what all of us have done in the beginning, within that we all have checked whether any number is a perfect square or not. Here is the function of is not doing anything. In the perfect square function, one will come to us as a number, its square root has been done, okay, as if it has become four, what will be the square root of four, you will come, okay, so you who is here will come to us. Then we will multiply it later and see if it will be equal, then don't be true, wonder false, like in the example, if you have four, then let's see the square of four, like we have. 8 is done, okay, I will convert it to DJ, otherwise it will be return false here, that is, the number which we have is not a perfect square, okay, so this is the whole thing we were getting, then we What did all the people do that whatever we had in the list became a perfect square, I basically divided it. Now from here we all see the code, our record is only the code, how will our people solve it? Okay, remember one thing. Here we have the value of index and you know value which is changing, okay let's start with nine, first of all I will create the tech one inside which I will include the numbers okay initially I will put the value of this, you guys will enter the maximum of the interior. I can also enter the value but I will tell you why I have not put the maximum of the interior. Okay, first of all, what is the condition that whatever value we have, like 12, if its value is basically big then only I will be able to include it. Like, for example, our people will do news after DP. Okay, so this was the thing, now let's all do this, so value the value of the bull, if we have a good idea of ​​their value, of the bull, if we have a good idea of ​​their value, then basically we will have the choice. Whether I will include this one or not, okay take care, either I will include it or not, if I will include it, then we did a step, okay if I include this one, I am including this one inside this one, I will include it inside this one, so here we have The value of the pass index will not increase because I can select its previous value also, like in the example, it is 12, so people are also using us by selecting four thrice. Okay, so if I select it once, then Then the second time I can select it, okay, first of all, we have one, I am selecting its value, okay, here we have the index and here we have the date, this is the value, I subtracted it from this. I will give whatever value of index we have, we will write it, we will not select it, meaning what we will do is move ahead and see that something is happening by selecting on four and here the value will be basically because we have not done anything here, okay now our What do people want? Both of them want a minimum. We have the condition that I have given. Whose will we have? They will select from us and they will not select the number. It's okay. Why haven't people taken the value of take as infinity from us too? It's okay. Or why didn't you take zero? See, first of all I tell you because we find the minimum value, hence only zero will be the answer to the questions. Friend, for your 1000 i.e. questions. Friend, for your 1000 i.e. questions. Friend, for your 1000 i.e. 10000, you will take some more value. Wait, what will happen? I will do anything plus van in the maxi of the interior. If you find the minimum value, then the same number is returned. There is no value more than this. Okay, so for this one, I have made it constunt, after seeing it, there is no value more than constunt. If it comes then I have selected the same. Ok, it was about tech. Now let's talk about not tech. Reduce it because we are in water. Projector needs minimum. Out of both, I have made two calls. Out of both, I need minimum out of tech. Need more notes, okay, what will we do, like I have subtracted nine from 12, okay, so only one call will be made here because we all have put a condition here, right here we have, like what will I do from that? Here A will go to us, we will have three A will go to us, will we keep it fixed, will I be able to select it back, we will not be able to do this because this condition has failed, then we will not take only our people, in this case we will have, will we have people directly select four from us? Now, if you come on four, then the value of three is bigger than four. Okay, so in this case too, what will we all do? We will go ahead by one more. Okay, now let me tell you one thing for the base case condition. The base case condition that I want to tell in the last season is the date that we have made, whatever is the last index that we have, the van inside it will always be fixed. Okay, so the last is whatever you have, you can make it from any number. Van will be less inside it, so you will have certain things included, okay, so if I have that nearby here, okay, if you divide anything by van, the number will be the same, so if I basically remove this here, right? So it won't make that much difference, okay, but it looks good, okay, so let's run it and see Its a request, let me tell you one more thing, what will be the time frame that we have, see what I can do here. If we look at its time, then how can we look at it as a time complex? It is a simple thing, I have a given, let's assume that what is inside it, I have given elements A, so inside that we will have options that I can select or If I do n't select then I will have so many options from the element, they will be N on 2 rest, the option is fine but its the time which we are black city, those 2 races are more than you par N, the reason is know what if you second if you coin There will be a change van, what was there inside that you will select and by selecting you will reach further, it is okay as if the number is given like this then here you will select but even after not selecting here, you still have the option, do you? You can also put it there like I have become two, I can select two any number of times, so 2 * K is the number of times, so 2 * K is the number of times, so 2 * K is the number of times you will select it and the value of K is not fixed, you can select it any number of times. Its time is also exponential, so then friend, this is a bad thing, you will have to miss it, if your people are okay, then your people will put DP, here, your people will put DP for you, okay then we will do memorization, what will we do first, we will make DPR. Okay, now here we have, first of all tell me okay second thing here I will do, you are DP so what will we do here is memorization so first of all here we all will fill -1 inside all nine from here What will I do, I will call the DP, okay and here the DP went, okay, we had Van Four Nine at that time. Okay, 100, now what do I do here? Science, later you guys will tell me the tabulation, so I reduce it, make some changes inside the court, here, I index it as van tu three, its ok. The game that follows is basically one and only three, but here I will do one thing due to which it will seem as if it is going on as it is, okay, so let's see how our people will write it, right here, call in advance. Okay, if the value of the index here is basically one, then what will I do in this case I will make the I will make the I will make the index - 1, make it simple and here we will do the index wherever it is. I have just made it empty, the rest of the things are going to come from what we have, okay here you have to put that DP widgetized DP off index A will go here, if you want to reduce it, okay Soran keep doing it. Then the size of the perfect square has been made, now what do we reduce here, which is the code for memorization, we all will do the same code for memorization. Sorry, I have written only one condition here, friend, one condition. It is okay to write it here, without that, here we start from zero one three, this is basically the index that we have, whatever we have, people had created from the you know natural numbers, this is what we have, basically the values ​​will come out right here. But values ​​will come out right here. But values ​​will come out right here. But I have definitely forgotten to write the condition, but you have to remember that if I have the value of the index here, then if the value of the index here comes to us as zero, then what will I do in this case, here we will return What will happen because if you have zero in your index then it means that we have zero index. Okay, let me tell you that it is given that we have the value of N which will be more than Van, then there is no point in getting zero index. If one WAN number is created then one N one WAN number will come to you every time, so write the condition we have or not, it does n't matter, it's okay, but it doesn't matter, there is a concept of one thing, so then we will try to understand it a little. Also, let's try to link, okay, so wherever the value of the index here, we will get zero, there, I will make 10 rest tu power four. What is the meaning of 10 raw power four, no you have u. What does no zero mean, you have it is given, I am carrying one index here, okay, now here it is a simple thing, you have zero index, meaning we you, we have not even a single you no number has come out. That's right, even one of us has turned out to be a perfect square. It's okay, so the van will always come to us, so write it or not, there is no problem, but to understand, we are doing this on this in a group of four. I will give you all this, basically the team will have done it, okay nine, what will happen if we have the value of the index in one place, then if the value of the index comes to me in one place, then I will return it or what can you do here. Pay return value or the meaning of return is that you will get only one, that is, you will get any number divided by one, that is the same number, fill zero, one, three, it is right, so basically you fill the numbers in such a place. Okay, now what do we have with our people, now here we all will have to take the complete conventional method which we have all these methods. Okay, here what will you have to do, let me complete it. Okay, by doing this first, we will do this. First let's do the code, whatever we have is the establishment code, we have created it, we have the value, it will go up to N brother, then what do you have to do, here you don't have to do anything, you have to pick up whatever we had, so this. Our people will pick up the entire code. Well, the concept will be the same, okay, you can do it. So, if you have the value of the index, then what will you have to do. What will be the value of the DPO of the index? You will have to enter one more condition. I had forgotten to put the value of index, if index and will be solved then ok good ok do n't return, you will have to do it from this, you will have to return and at the same time put equal tu sign because it will work for zero so that these are not executed. After this, I will explain to you the code once, how it is going to happen, we will give it in less page, it was here that we will give the statement, okay, now here we have the first time which comes out, you have to fill the value. If it is then here you will have a take whose value is 4 groups. Okay and along with that you will have a nonte. Right now look here you will have to see the minimum value, I have forgotten to tell you here, you have to do it, the logic is like this. According to the calculation, the same will come but also see one thing that if you have zero values then you will not use it for anyone else, here you will get only zero coins, there is no need to do it, so here we have Similarly, we will fill its value which is zero, now let's talk about this thing by name, take date, we will see it as 2.1, here till here, van tu will be three, so I will be able to do it with only 11 coins, okay. Because all these problems are divided into four, so what will we do here, one coin will be selected, right four will come, you have got one point and together, what will come out here If we have here the value means four minus zero, okay, now we have to compare that value between the minimum, we have to find the four between van and four, that is, the date which was above it is van, then we only have van. It will come, it's okay whether you include it or not, that's the same thing because you have included it after yourself in the index, so whether you include it or not, it doesn't matter, even if you don't include it won't make that much difference, right. This will work for us and what will we do here, if you get this, then you will date as a friend, you will get the answer, you will have the answer, which is the actual answer, okay, I told you, friend, whether to include it or not is up to you, okay? I see here, even if I show it to you, if I do n't include it will still be submitted to us. I was linking the problem with coin change, that's why I was doing that is why I said what is already written. See, it is being accepted, please submit and show it will also be included, okay, so the video is very long, I am sorry for that, I hope you have understood something from this video, the problem is okay, then do like it.
Perfect Squares
perfect-squares
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`. A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not. **Example 1:** **Input:** n = 12 **Output:** 3 **Explanation:** 12 = 4 + 4 + 4. **Example 2:** **Input:** n = 13 **Output:** 2 **Explanation:** 13 = 4 + 9. **Constraints:** * `1 <= n <= 104`
null
Math,Dynamic Programming,Breadth-First Search
Medium
204,264
123
hi guys welcome to algorithms made easy my name is khushpu and in this video we'll see the question best time to buy and sell stock part three you are given an array prices where prices of i is the price of the given stock on ith day we need to find the maximum profit that we can achieve given that you may complete at most two transactions you may not engage in multiple transactions simultaneously that is you must sell the stock before you buy again let's see the example number one wherein we are given the prices and the explanation states that buy on day four at price zero and sell on day six at price 3 which is this transaction and then buy on day 7 at price 1 and sell on day 8 at price 4. so this is this transaction if you do a total you get 3 plus 3 which is 6 that is the output so in example one we did two transactions let's see the example number two in the example number two the array is given in an increasing order so we can just buy this stock at one rupee and sell it at five which gives us the highest profit which is of four rupee the example number three has a decreasing array which means that no transaction will give us a profit so we are not going to buy or sell the stock and our profit remains zero so now with the examples it is clear that we can have either zero one or at most two transactions to find the maximum profit that we can achieve so let's go ahead and see how we can solve this question when there was a single transaction allowed which was in the part 1 of the question what we did was we found out the minimum and stored it and then at each step we used to find the maximum profit that we could achieve by considering the minimum that was the buying point and maximizing the profit by finding the maximum value at which we can sell the stock with this approach our output would have considered this particular transaction now when we say that we can make at most two transactions it means we can either have zero one or two transactions so looking at this graph we can make one transaction for this particular range and the second transaction in this particular days this will maximize our profit and that's what we want to achieve in this question if we see here we have two transactions transaction one and transaction two which is dividing our sequence into two parts and these transactions are the transaction that are giving maximum output in these two different parts so we can consider these parts as left and right so for a given point if i am considering or if i am dividing my sequence on day three then i need to find out the maximum profit i can achieve from day zero to day three and the maximum profit that i can achieve from day 3 to d6 combining these two will give me the answer for this particular question wherein i am making at most two transactions for that what we are going to use is bi-directional dynamic programming as bi-directional dynamic programming as bi-directional dynamic programming as the name suggests it is going to have iterations in two directions one being from left to right and the other being from right to left and since it is dp we are going to store intermediate results of the maximum profit we can achieve till that particular date so let's take this example which is the prices array and we will take a left array which is our intermediate result to store the profit that we are achieving when we are iterating from left to right over here we are also going to have a variable which will store the minimum price that is the minimum buying price initially at zeroth index the profit will be zero because the most you can do is buy it three rupees and sell at three rupees and our minimum gets updated to three moving ahead when we come to this particular index now we are going to see if my minimum is changing or not if my minimum changes i'll update that minimum buying price in my min variable and i can find out the profit that is the maximum profit till the current index so that maximum profit can either be the profit that i have already observed previously or the profit that i will make by selling the stock on the current price which will give me the profit of prices of i minus min which is the buying price currently for this particular index since this particular price is equivalent to the minimum price this is going to be 0 because it will be maximum of either 0 or 3 minus 3 0 which gives us 0 moving ahead now i have a higher price my previous profit was 0 and my current profit now becomes 5 minus 3 which is 2. if i see the maximum profit it will be either the max of 0 or 2 which gives us 2. similarly i'll go ahead and check for this particular index now since my buy price is 0 which is lesser than the previous buy price which was three i'll update the minimum variable that is i can buy lowest at zero rupees considering this the profit becomes zero for the current transaction and the profit that i have already seen previously was 2 so i just take the same value and put it in the current index for profit if you do continue this till the end of the array you will get the profit that you can achieve by traveling from left to right on each and every day now we have the left array we need to find out the same thing while starting from right to left so we'll take a right array and we'll start from the end of the array since we are starting from the end of the array we will now have the selling price that is going to be the maximum price at which i can sell the stock which is currently 4 that is value in my prices array and now as i move ahead i need to find the maximum profit that i can achieve by saying that this is the maximum value at which i could have sold the stock and the current prices of i being the buying price so when we go over here my sell price is 4 my buy price is 1 and my profit would become either the maximum profit i have seen previously or the profit from the current transaction that is from buying at this particular price which will give me 4 minus 1 that is 3 as the profit moving ahead if my buy price now becomes 3 my profit is reduced to 1 which i don't want to take because i already made a profit of three rupees from the previous transaction so the maximum profit was already three so i just added three over here in this particular index similarly when you do this for all the other indexes you will see the right array filled in this particular way now let's see what all these components define if i take this particular index this 2 is telling me that the maximum profit that i can achieve till this point when i am starting from day 0 is 2 rupees or 2 units while this 4 corresponding to the same index in right array will say that the maximum profit i can achieve in the future starting from this point till the end is 4. so at this particular point if i see the maximum profit in this area and the maximum profit in this area is nothing but this two and four so from the two transactions i can maximize the profit up to six rupees which is the maximum that we can achieve so this is one of the way of solving this question now i would like you guys to pause the video and try coding this approach by yourself if you get stuck refer to the coding part that i'll be showing now so let's go ahead and code this approach out and then we'll see another interesting approach to solve this question let us take a few variables that we will keep handy and will also have a base condition that is if n is 0 return 0 and now let's write down the bi-directional dp logic over here bi-directional dp logic over here bi-directional dp logic over here first one is from left to right and second would be from right to left traversal let's write the left to right one first initially we'll need a variable min which will hold the minimum buying price and that price is going to be nothing but the price on day zero after that we will start looping and we'll start our loop from index one in this loop the first step is going to be update by price second is calculate current profit third is fill the left array so let's start with step one which will be if the current price is lower we update the min the profit will be selling price minus buying price sell prices the price for current index and buy prices min so over here the profit at current index would become the maximum profit that i can obtain till now so that can be either the previous profit or the current profit the same thing we need to do for right as well but for right we'll take a max which is equal to the selling price and that would be initially equal to the value at last index of the prices array and we'll take a for loop starting from second last index over here again we are going to have three steps the first is update sell price second is calculate current profit and third is update the right iron so let's start with the first step if prices of i is greater than max update max now current profit is nothing but the sell price which is max minus buy price which is prices of i and third is the array which will be maximizing either the profit that we have seen earlier that is right of i plus 1 or the current profit now that we are done with this we need to iterate over both these arrays and find out the maximum profit from two transactions for that let's take a variable max profit which is initially zero and max profit will become the maximum of either the max profit or leftify plus right of i that's it return max profit and we are done let's hope we haven't made any mistakes and we have let's run it again it's giving a perfect answer let's submit this and it got submitted the time complexity for this approach would be o of 3n which is equivalent to often because we are having three for loops 1 2 and 3. the space complexity is going to be o of 2n or which is equivalent to o of n for these two arrays so that's about this approach now how can you find this in only one pass so let's see that approach so in this approach we are going to see the one pass simulation we can see that this particular question can have four different actions buy off transaction one sell of transaction one buy of transaction two and sell off transaction two let's keep this points handy that is buy sell and profit by selling profit and let's take an example suppose i am giving two coins to buy one stock which is the buy of transaction 1 at cost c1 now when i'm selling the stock i am getting an additional three coins so these three coins are nothing but profit and my sell price becomes c1 plus p1 now let's see the transaction 2. when i'm doing the second transaction for say some amount x the amount that i am actually paying from my own pocket is one coin over here for buying it at cost four why only one coin because these three coins were from the previous profit i used the same profit and gave one more extra coin to buy the share so this effective price for me that i had to pay from my own pocket was nothing but the cost of the second transaction minus the profit that i got from the previous transaction so this was x minus p1 now when i sell the share i am getting some more profit right and then the entire profit of this transaction if you see is nothing but this transaction that is the sell price minus the effective cost of buying this particular share which was nothing but x minus p1 so my entire profit after both the transaction becomes y minus x minus p1 so now at every given point in time we are going to maintain four variables which is the buy price of first transaction which would be the minimum buy price the profit from the first transaction the buy price or the effective buy price for the second transaction which is nothing but the number of coins that i have spent from my pocket to buy that share not including the profit from previous transaction and lastly we'll have the profit which is nothing but this that is the profit from both the transactions together so now my buy price for first transaction is always going to be the minimum price at which i can buy a stock so for that we can have a formula which is nothing but either the previous buy price that is already there with me or the current price on which i am there second thing the profit this profit is the maximum of either the profit that i have seen earlier or the current profit which is nothing but the sell price minus buy price considering that i am selling the stock at current price third thing is the buy price for second transaction which is nothing but my effective buy price or this x minus p1 so that is going to be equal to the minimum of either the buy price that i have seen earlier or the current one which is nothing but price of i minus this profit of transaction 1 that is x minus p1 this is the formula that we have written over here the last thing is profit 2 which is the profit from both the transactions this is going to be the maximum of the profit that we have seen earlier or the profit when we are doing the current transaction so the current transaction profit will be nothing but the sell price at the current price minus the buy price which was my effective buy price for the second transaction that is y minus x minus 1 so y is my sell price x minus p 1 was this that we calculated already so that is by price 2. so now we know from where we are getting this formula let's see one example with this approach so let us take this particular array and this is the table that we have initially the buy prices would be maxed out and the profits would be 0. now starting from index 0 my buy price 1 is minimum of either my buy price or the price of i initially it was max so minimum of both this is 3 profit over here is 0 because if i do the cell transaction at this current price it will be three minus three which is zero by price for second transaction now becomes three again because it is either max or three minus zero and profit of 2 is also 0 with this particular formula because we have either maximum that is 0 or 3 minus 3 that is prices of minus by price of second transaction now let's take the previous values handy with us going to the next iteration or next index now the buy price of the first transaction stays same because we have again the price of 3 which is still the same as the previous one profit is still zero because we bought it three maximum what we can do is selling at this particular price which is three so it becomes zero by four second is also three and profit for 2 is 0. now let's come to this wherein the current price is 5. now we can see from here that we have a profit my buy price is still going to be 3 which is the minimum that i have seen till now profit becomes 2 which is 5 minus 3 by price of 2 is the buy price that i have seen or the effective buy price that i will see the previous buy price was three units and the current effective buy price can be prices of i minus the profit that i have seen from transaction one which also gives us three so this remains unchanged profit of 2 now becomes 2 which is 5-3 profit of 2 now becomes 2 which is 5-3 profit of 2 now becomes 2 which is 5-3 moving on to the next index this now becomes my minimum buy price for the first transaction because it is the lowest we have observed my profit becomes 2 which is the previous max profit because if i sell at 0 and i bought at 0 that would give me 0 as profit maximum of 2 and 0 is 2. interesting part over here is the buy price for the second transaction which is the effective buy price what happens over here is that previous buy price for second transaction was three and for the current transaction since the stock is at cost of 0 units and i already have a profit of 2 units so what i am spending is minus 2 rupees because i have extra 2 rupees with me or extra 2 units with me as a profit from the previous transaction now the profit 2 becomes maximum of this 2 or maximum of the profit that i have after buying at this particular buy price which is 2 itself continuing with the same now this by price 2 has changed to minus 2 rest everything is same since we have the cost as 0 unit over here our table is going to stay the same and not change this time let's move ahead when we come to this three our buy price one is still zero maximum profit will now be buying at zero selling at three which is 3 units now i had 2 rupees profit from earlier i need to buy this particular share at 3 rupees so what i am spending now is 1 rupee for my site in this particular transaction so the minimum buy price will be either the previous by price or the current one which still stays minus 2 profit now becomes maximum of either 2 or this 3 minus of minus 2 which now gives me a profit of 5 because this by price that i had earlier was minus 2 current sale price is 3 i had a profit of 2 i am now making a profit of 3 from this transaction and total profit becomes 3 plus 2 which is 5 which is the profit from 2 transactions let's move ahead over here our minimum buy price remains the same and all these tables remain the same when we come to 4 the minimum price over here does not change the profit of buying year and selling here in this transaction becomes 4 my defective buy price 2 is still minus 2 and my profit now becomes maximum of either the previous transaction or the profit from current transaction that is 4 minus of minus 2 which is 6. so what this particular transaction means is that i did a transaction that is buying at this three or this three whichever you want to consider and selling it at five which gave me a profit of two and the second transaction was buying at zero and selling at full which is this profit adding this to we get 6 which is the total profit that we can get so that was the dry run of this particular approach wherein we have the formulas with us and the profit 2 gives us the entire profit from at most two transactions so that's all for this approach i want you guys to try to code this particular approach by yourself before going into the coding part with me so now let's go and code this particular approach out first and the foremost thing that we need to do is take all the four variables so we'll take c1 c2 p1 and p2 c1 c2 will be dot maxwell and p1 p2 will initially be zero now we'll iterate over the array now what we are going to do is just update all these four variables and finally return p2 which is going to hold the cumulative profit for two transactions now let's see what c1 has c1 is the minimum price at which we can buy so it takes math dot minimum of either the price that we have seen or the current price what about profit is going to be the maximum profit that i have already seen or the profit from the current transaction now the current transaction is selling at this price and buying at c1 what about c2 is the effective buying price which is also going to be the minimum effective buying price was calculated using a formula if you remember which was nothing but paying with the profit we have got from the first transaction so that is nothing but cost of current share minus the profit that i have made from previous transaction this is the effective buy price p2 now becomes the maximum profit that we have seen in both the transactions so that is nothing but either p2 or sell price minus by price that's it let's try to run this code and it runs perfectly let's submit it and it got submitted the time complexity over here is o of n that is same the only thing is that it is a one pass solution the space complexity if you see over here is o of one because we are only taking four variables that's it so that's it for this question guys i hope you like the solutions please like share and subscribe to our channel and drop your thoughts in the comments and i'll see you in the next one you
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete **at most two transactions**. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[3,3,5,0,0,3,1,4\] **Output:** 6 **Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transaction is done, i.e. max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 105`
null
Array,Dynamic Programming
Hard
121,122,188,689
1,870
hello everyone welcome to my your programming Club today we will be solving another daily code Challenge and the challenge name is minimum speed to arrive on time so the channel statement is like this you are given a floating Point number or representing the amount of time you have to reach the office to commute to the office you must take entrance in a sequential order uh so till now what's the problem statement is saying is uh you are given total let's say t number of hours to reach office and then uh what is it's saying is we and there are n number of trains to reach the office you must take these entrains in a sequential order it means that if you decide to First Take the let's say first train you will go in the like this is the first second and third and fourth Trend available you uh basically they are whatever these you have to take this is compulsive to take each strain but you cannot take trends like this you first you take the first string and then you take the third one and then you take the let's say fifth one uh it's not the sequential order uh so this is the wrong order of taking the trains you should take in this order only one two three four and five I hope till now it's clear and you are also given an integer array distance of length n Athan and the element each element in the distance array represents the distance in kilometers that a particular train ride will take so what is further given is a train can only depart at an integer R so you may need to wait between each train right what it's saying is let's say first train taking the first train at a particular speed to Q uh 0.3333 hours 0.3333 hours 0.3333 hours okay and now when you will take the second trade let me quickly change the color you will take the second train if they if there is a other train to be taken at all you have to take the ceiling of 0.33333 0.33333 0.33333 and what is a ceiling feeling of a number is the least integer which is greater than or equal to the given number so what it's saying is what is the list integer which is greater than or equal to this 0.333 it's one 0.333 it's one 0.333 it's one so you can only take the second ring after one hour at one hour note before that because you cannot take the secondary net V3 0.33 hours V3 0.33 hours V3 0.33 hours just after you have finished traveling from uh from training one so I hope it's clear now let's move back to the prolong statement for example if the first train takes 1.5 for example if the first train takes 1.5 for example if the first train takes 1.5 hours you must wait for the additional 0.5 hours before you can depart on the 0.5 hours before you can depart on the 0.5 hours before you can depart on the second Android it's pretty much the same thing which I have told you and what you have to return is you have to return the minimum possible positive integer speed uh what is minimum integer period so that you reach office in TRS or given us so if you let's move to the constraints part uh n is and here is the length of the distance array which represents the distance for each strain right and Order of n is of 10 raised to power 5 and the distance is in the distance array are reported 10 raised to power 5. and the number of hours that you will be given to reach the office will be of order 10 raised to power 9. also it is given tests are generated test cases are then it is such that the minimum speed uh that will be possible or the answer will not exceed 10 raised to power 7. so it will be our maximum minimum speed possible so if let's say you are traveling with the maximum speed or a maximum minimum speed possible for including all test cases let's say this is the maximum speed you are traveling in each stream let's say then or if this is the maximum speed then you want to know what is the minimum speed then you can say that from 0 to 10 raised to power 7 there are that many options for Speed of train or whether this much speed would be sufficient or not that is another issue uh we have to check for that so these many options are available for value of speed uh since we have to find the common speed for each strain so this is when your options are available and let what's the size of the distance array how many trains we are will be given uh it will be order of 10 raised to power 5 let uh 10 raised to the power 7 into 10 raise to power 5 it's 10 is to power 12. and it's clearly greater than 10 raised to power it which are operations allowed in once again so it will clearly give this Brute Force approach of checking for every possible speed Brute Force approach for checking for every option uh available for Speed will give us tle so what we need to do we have to optimize this Brute Force approach and for those of you who do not know how the time complexity of accepted solution berries according to input size I'll provide a link for it right now what you can understand is uh this is the article that will those are using I will be providing to you and since n is greater than of order 10 raised to power 3 and it's between 10 raise to power over 6 so n log n of 1 or Logan time complexities will be fine for the solution so what you will do in order to make your solution uh time complexity according equal to one of these uh so basically you for each distance or train ride for each strain right you have to check the time taken that we cannot reduce but we can reduce the option that we will select for Speed what we will be reducing options that we will check for speed initially you were having 0 to 10 raise to power 7 values available for Speed values available for speed of trends and you input force approach you are checking for each of these values but now what we will be doing is If You observe these values are in a sorted fashion so after 0 will come one two three and so on till 10 raised to power 7 so these are in sorted order so what we can do for the next choice of speed we can apply binary search and since by research works for in log of end time complexity and here is 10 is 2.7 and here is 10 is 2.7 and here is 10 is 2.7 so order of logo 10 raised to power 7 and into 10 raised to power What will what is the input size of the distance array it's of the order 10 raised to power five it's it will be clearly less than 10 raised to Power 8 operations so our solution will be accepted so I will be applying binary search for the next choice of speed first of all you have to understand on for working which thing we are applying binary search for we are applying binary code search for the next choice of the speed uh now let's move to the coding part there you will be unders you will be able to understand the logic and the implementation in a more clearer way let me quickly zoom out yeah this is the implementation and what we have done is we have created a helper function find minimum speed uh this is nothing but binary search and what we have done is let's say minimum speed and also it is also told that in the program statement that if you are unable to reach office in the given time return minus 1 to indicate that it is impossible to reach so initially we are assuming that is impossible to reach the office so the minimum speed we are taking as minus 1 and the minimum possible value of the speed we are taking as 0 and since it's given that answer will not exceed 10 raised to power 7 so I have taken 10 raised to power 7 plus 1 you can also take 10 raised to 0.7 that can also take 10 raised to 0.7 that can also take 10 raised to 0.7 that would also be fine I just for safety I have taken plus one actually there's uh up to you basically it's the same order of 10 days to power seven so here I have applied a standard binary search but here is that a trickier part in the binary search what we are checking is uh this is the mid will be the mid is current uh choice or speeds value so uh what we are checking is in is enough function uh if the current choice or speed is sufficient to make us reach the office in given time Givens time limit which is or this value so in this function we are checking that this and it if it's the sufficient enough speed currently this will be the minimum speed and up and what we'll do is we will decrease our search space from one previous value to Mid and right will be shift shifted at the max limit of the search space will be shifted to one previous two current speed which is mid and if that's not the case the current speed is not enough we will simply uh shift or minimum value of search space to 1 greater than the current speed which is mid so uh this is a standard binary search approach and at last we will be returning our minimum speed depending upon whether the minimum speed value was uptrended or not uh it will return the answer and let's have a look at the isana function which is checking if the current choice of speed is sufficient to make us reach the office in a given time limit so what we have done is uh what will be the current time taken if the speed is this so it will be the distance that is to be covered in the trend writer index indx and so this will be the time it will take to cut do a particular train ride and if we are not having here we are having another train to take then what we'll do we'll take the feeling of the current time taken to use this current train and we'll add the current time taken to the total time taken and at last we will return whether the total time taken is in the limit of the given time limit which was r and yeah that's pretty much it for the solution part of this problem now the code will be available in C plus and Java both so thank you for watching thank you
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. * For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark. Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_. Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**. **Example 1:** **Input:** dist = \[1,3,2\], hour = 6 **Output:** 1 **Explanation:** At speed 1: - The first train ride takes 1/1 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. - You will arrive at exactly the 6 hour mark. **Example 2:** **Input:** dist = \[1,3,2\], hour = 2.7 **Output:** 3 **Explanation:** At speed 3: - The first train ride takes 1/3 = 0.33333 hours. - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. - You will arrive at the 2.66667 hour mark. **Example 3:** **Input:** dist = \[1,3,2\], hour = 1.9 **Output:** -1 **Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark. **Constraints:** * `n == dist.length` * `1 <= n <= 105` * `1 <= dist[i] <= 105` * `1 <= hour <= 109` * There will be at most two digits after the decimal point in `hour`.
null
null
Medium
null
956
hello friends today list of tallest billboard problem you are installing a billboard and you want to have the lag largest height the billboard will have two steel spots one on each side each steel spout must be an equal height so simply put that is we are given an integer rate we want to separate into two buckets each brackets bracket is a sum equal to the other one but you should notice that we do not need to use up older rows so in this example we can separate into one two three because they sum up equal to 6 and the other bucket you know only have one road which had the length of 6 so we meet the requirement we return 6. in this example we can separate it into two markets uh two three five they sum up to ten and they are the bargains they have four six they also sum up to ten and the 10 is the highest we can get but you notice that we do not use this one it's also okay in this example we cannot make it because we only have one two and we cannot separate into two markets which have the same height so how to do it for each road we actually have three options one is usage and the food is in the left bracket the second one is we use it and put it into the right bucket the third one is that we do not use it so i think the idea is straightforward that we just try every possibilities and to get the global max height maximum height but further search better problem we actually uh the hardest part is that we must know how to prove prune prove it pruning well we must know how to do pruning because for example if the left plus right the sun of the left and the right and plus uncheck the uh roads is less than twice of the maximum height we do not need to check anymore because even we use up all these unchecked roads we cannot uh we cannot be uh higher than this already get the maximum height actually we can put a u chord side here because if even if the equal we do not need to check anymore um the other way to pro to do the pruning is that if the left height their absolute value is greater than the unchecked sum we do not need to check anymore because even if we put all the unchecked height to one of these brackets we cannot make these two brackets equal so no need to check anymore so we can apply these two plugin techniques so now let's write the code the idea is simple we need to maintain a max global variable we call it max and then we get the we do the or this part we get the an equal to row star length and we needed to get the sum of all these rows so iterate this road in the roads so some plus this road then we do the help function which is actually uh that first search and finally we re return this max so let's see how to implement this help function well actually we can uh because it is not sorted we can search from left to right or from right to left but i think the uh the samples i mean the test cases are strange if i we search from left to right we will go turn limit exceeded but if we search from right to left we are quite fast so whatever we just search for right left let's see the parameters we need first of course is the red roads and we also need the index which indicate where are we in the road array the sum of the left bracket the sum of the right bracket in the remain one which is unchecked part so the best case once the index is less than zero we know we must return but in what case should we add the result which is the if the left bracket have this same height as the right bracket and of course they are higher than the max we should update the max to the their height so now let's do some pruning oh why oh do some pruning that if the left plus right plus on the remain unchecked which is less than less or equal than 2 times max we just written and the other part is that we can never make them equal so left minus right is greater than remain we just return other parts we just do three check because one is another index minus one is put to the current road to the left market right keep the right as it is and remain minus the roads index the other option is put the road to the right market so left unchanged the right plus rows index the remain minus rows index the third is do not use it so index minus one left right and the remain minus rows index okay so let's fill this part there will be rows zero uh zero also index is not there index is the roads the length minus one in the row zero and the remain is sum so okay i think we finished okay thank you for watching see you next time sorry i think it should be like a full uh meaning seconds or something see you next time
Tallest Billboard
number-of-music-playlists
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`. Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`. **Example 1:** **Input:** rods = \[1,2,3,6\] **Output:** 6 **Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6. **Example 2:** **Input:** rods = \[1,2,3,4,5,6\] **Output:** 10 **Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10. **Example 3:** **Input:** rods = \[1,2\] **Output:** 0 **Explanation:** The billboard cannot be supported, so we return 0. **Constraints:** * `1 <= rods.length <= 20` * `1 <= rods[i] <= 1000` * `sum(rods[i]) <= 5000`
null
Math,Dynamic Programming,Combinatorics
Hard
null
238
Hello friends in this section we are going to discuss about another light co problem product of acceptance of deposits of luxury all will do we call the product of all elements acid pimple or pimple 3000 will do protector of all elements subscribe The Channel do all Elements Element Product 5130 subscribe and subscribe the Channel That Apple Problem Statement Piece Expected to Solve Problem in Order of Time Complexity and Without Using Division Operation All Services Solvent in The Hague Specific Artist Click Half Hour Subscription Will Understand Porn Video Channel Subscribe and All Elements Class Products For All Elements After Elements In Next Withdrawal Product With Current Element In 98100 But One Which Assures Will Start At Whose Heart Is Indicative One Adhikari Directly To This Side Subscribe's Product Element At Index Product Left Side Element Which Product Right Side Element Subscribe To That Boat Lets Have A Product Top 2054 Multiply Between Answers Which Include Element At Index Product Amazon More Products Right Side Element Ultimately Final Product Subscribe That Something Matching Only Noobs Ramdev Opposite Glue Android Product Introduction Element Appointed Final Result Lets Understand This Approach Will Use This Is Element Product Left Right Will Use This Is Element Right Side Product From Right To Left Final Product Subscribe Default Product All Elements To Its Previous In Series Index Calculated By Product Previous Index Element Multiplied By Previous Product Multiplicative And On Thursday Subscribe Now to Subscribe Products From Right to Left Thursday Nilayam Default Product I am One Hair Not Wait and Active for a Previous Index Element Hair One is Pay Click Hair Products for Multiple Top 49th Urs Element Subscribe Product Multiple of 100 to the President Subscribe Multiply Android Products Final Product Multiply That 2286 Multiplicative Reason Divine Final Put It Is The Time This They Didn't Want End Complexity Video Channel Subscribe Left And Right Product Introduction Element subscribe The Channel subscribe this Video plz subscribe Channel Products Which Element In Directions Internet Subscribe Product Id That They'll Take Care Rather Holder Left Side Product The States Initial Satire Intekaam Team Via Job Element In Areas Default Subscribe 280 Right Side Flu Productive One Officer Will Update Products Current Element 151 Update Lu That In Extraction v8 Inductive Will Right Side Products Tubelight topper half-and- Side Products Tubelight topper half-and- Side Products Tubelight topper half-and- half glue current element to subscribe our that internet station website indicative right side product fluid two for multiply bittu quite update person update loop current elementary level plug bittu ne Thursday 12561 multiply quality update with egg final tuesday channel subscribe hour Subscribe to Video Channel to Novel Calculate Right Side Product A Prostrate Before the Will Cause You Lose Element Product Way Default Discussed A Bevy of and Look Hello Viewers on the Internet From Right to Left and Calculating Right Product Index Jhal Flash Lights Declare Attempt Rob Nichol Left Side Product In A Position To Set Default Value Will Give Oo Na That Let Complete Final Result Update Jhal To Left Value Attached's Reaction To Finally Returned Result Disruption With Coding Letter Code Have Already Written Friends Sometime We Make A Call To Products And Function With Fighting Kapil Now Input Electronics Result Who Is The Art Which Aspect And Thanks Watching Hope You Like This Video Please Do You Like The Video And To Subscribe My Channel Thank You
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
1,716
hello and welcome to another video in this video we're going to be working on calculate money in Elite code bank and in this problem someone wants to save money for his first car he puts money in a Le code Bank every day he puts $1 a Le code Bank every day he puts $1 a Le code Bank every day he puts $1 Monday and then every day he will put a $1 more and then on every subsequent $1 more and then on every subsequent $1 more and then on every subsequent Monday he will put in more than the previous Monday $1 more given and return previous Monday $1 more given and return previous Monday $1 more given and return the total amount of money he'll have an El code bank so here we have four days so you'll just put in 1 2 3 4 10 days the first week every day will increase and then on the next Monday it's going to go back to one more than the previous Monday and then for a bunch of days kind of the same thing so every day increase by one then on the start of the week you drop down to one more than the previous Monday then you increase every day and then the same thing you have one more than the previous Monday so you could pretty easily make a simulation of this where you just Loop end times and you figure out like okay for every day let's just add one and then on every single Monday let's subtract some number and then you can get a total so that's one way to do it um we're actually going to talk about the 01 solution cuz it's a little bit more interesting and uh yeah it's a little harder to do so we'll get into that so there's a few things to that we need to get the of one solution and the first thing is number of weeks that pass right like full weeks so the number of full weeks that pass so like for let's um look at like maybe this third example so the number of full weeks that pass if n equals 20 is just going to be two right then the second thing we need is number of days left and so for the number of days left we need to figure out basically like how many days do we have leftovers like the remainder after we did some full weeks so in this case we have two full weeks so we have 6 days left and then from there the next thing we need to do is we need to figure out like how do we quickly calculate like we know how many weeks passed is there a way we could just plug this into some math equation and get a result and so notice for our actual if you look at these sequences so like let's look at the weeks right so for week zero the sequence is 1 2 3 4 5 6 7 for week one it's 2 three 4 5 6 7 8 and then for week two it is 3 4 five 6 7 8 9 so notice for one thing these are arithmetic sequences right they start at some number and then they always increase by constant amount so let's take a look at the totals here so actually for this total is 13 18 22 + 6 so 18 22 + 6 so 18 22 + 6 so 28 this total is the same as the previous total but since every number is one Higher it's going to be 28 + 7 so 35 one Higher it's going to be 28 + 7 so 35 one Higher it's going to be 28 + 7 so 35 and this is going to be 42 so basically we can write this down for like for a week so like week zero week one week two week three are actually total for an entire week is going to be like 28 35 42 49 and so on so if we have the number of weeks that we actually fully completed like let's say we completed two weeks in this case we did we can just figure out exactly like what the total is for the two weeks right because we know week one is going to take 28 week two is going to take 35 if we had some arbitrary week um we can just do that number right we can just do 28 plus seven times like the number of weeks so seven times weeks and we can figure out like how many weeks the last week took so if two weeks passed then week two at this index one is just going to be um SE 28 + 7 * 1 so we can figure out um SE 28 + 7 * 1 so we can figure out um SE 28 + 7 * 1 so we can figure out like how long did the last week take so in this case the last week was week one right if it's if the weeks are zero index let's just say um then week one you know Z week zero took 28 Week 1 took 35 so we can figure that out so for example if 10 weeks passed then we would just calculate how long did week nine take that's zero indexed so here the first week all always takes 28 or this zero index week we can also write it like this to make it a little bit less confusing and then we can just change our formula a little bit slightly right so it be like week one week two week three week four something like this so we could say Okay week two would take seven * week what whatever week you're seven * week what whatever week you're seven * week what whatever week you're on you can just do this if you want it to be one index so this would also work right so if we're on week two um it's going to we're going to get 35 week minus one so that's totally fine as well okay and so now that we know that what we really need is how to get a total like let's say we did some number of weeks what we really need is What's the total that we actually got right because this is per week but really what we want is we want a total so because this is an arithmetic sequence is actually pretty straightforward and let's just like have some easier numbers just to see how we could easily do it let's say our sequence instead was like 2 4 6 81 and we're trying to get the a average right the idea is because this is an arithmetic sequence it increases by the same amount all we want to do is just get an average and then multiply that by the length of the sequence so here it's kind of pretty straightforward to get the average would be the six so we can just say okay well if the average is six then we'll multiply that by the length of the sequence which is five so the sum of this sequence should just be 30 and if we look at it so it's 18 2430 and that's how you get the um the total of an arithmetic sequence quickly is it's just going to be first Value Plus last value over two to get the average so we can call this also average over two times length of the sequence will be the sum so we're not actually going to build the sequence we're just going to figure it out and then get the sum so in this case let's plug in our numbers so um what's the average the first number in the sequence is going to be 28 and the second number of the sequence if two week pass is going to be 28 plus 7 * weeks - one so the 28 plus 7 * weeks - one so the 28 plus 7 * weeks - one so the last week that happened was week two so this would be 2 - 1 so the last is going this would be 2 - 1 so the last is going this would be 2 - 1 so the last is going to be 35 so we just take the average of 28 and 35 and then we divide by two so we do 28 + we do 28 + we do 28 + 35 divide by two and then we multiply that by the length of the sequence is two weeks so we just multiply by two and then um the twos cancel out so we just get this as our total so in this case it's going to be 63 yeah okay and so that is our total for two weeks right so total for the two weeks but now the thing is we also have days left over like in this case we have days left over right we have six days left over and so now we can kind of do the same thing for an arithmetic sequence basically exactly the same thing so if we have six days left over how do we know what the numbers are for these six days well we can just figure out what week we're on right so this is the last week here so it should be 3 4 5 6 7 8 so if we know we are on week three for these last six days and we know every week we add one so because we're on week three we'd have added one twice right because our numbers are like 1 2 3 4 5 six seven then week two we add one it's 2 3 4 5 6 7 8 uh like up here and then so on so when we're on week three if this was one indexed if this was week one week 2 week three then basically the number we add is just going to be number to add is just weeks or the week we're on minus one right so in this case because we're on week three for these last six days for every single number we will add two so the number for the first day of the days we have left is going to be three and then it's going to be like four five six and so on right so the number for the first day is going to be three and if we have six days left we can just calculate like what's going to be the last day so if you think about it's going to be like 3 four five 6 7 8 so the number for the last day is just the number for the first day so we can write that down as well number for last day equals number for first day plus the number of days minus one right so that's just like pretty straightforward so the number of days here is six so the number for the last day would be eight that's just like a basic you know if your array increases by one like what's the index like six indices ahead and so on right it's going to be whatever the first one was plus the length minus one and so now that we have the first and last day we can do this like range again right where we can take the average and then we can just multiply by the length so let's get an average here and then multiply by the number of days so in this case we have six days so then what it's going to be is it's going to be 11 * 3 which is * 3 which is * 3 which is 33 and if we write out our days again so it's going to be like 3 4 5 6 7 8 we do a total we have 15 21 26 + 7 which is 33 a total we have 15 21 26 + 7 which is 33 a total we have 15 21 26 + 7 which is 33 so basically you do this arithmetic sequence sum for the days and the weeks and then you're able to get both of them in 01 because you know exactly like for the last week you know exactly where the first day starts depending on the week because every week you add one and then also for your sums every week for the total week you just add seven so that's kind of how you do it's a pretty straightforward problem once you know that and this is kind of useful to know how to get the sum of an arithmetic sequence because now you if you recognize you get something like this you never actually have to build it all you have to do is just get an average and just multiply by the length of it okay and now we can code it up so I think uh solution's closer to a medium problem um you know if you were asked to do the sov one so I think the simulation is like pretty straightforward so no real point in going over that one okay so we're going to calculate our weeks so we'll say full weeks equals n IDE by 7 then we have our days left over as like the remainder which is n mod 7 so let's say we have uh like n is 20 here we would have two full weeks and then we would get 20 mod 7 which would be 6 days now we're just going to do this range sum thing for the weeks and then we'll do the range sum for the uh days and then we can just add those together so you say total full weeks equals full weeks times so a lot of these things are going to add together so basically uh the first day is going to be 28 and the last day will be 28 or sorry not the first day uh the first week will be the sum will be 28 and then the last week it'll be 28 plus 7 times some number so this is really going to be 56 plus and then you add seven full weeks minus one times for the last week so get that divide by two so this part gives you the average this is the length of your act thing okay so the second part is going to be pretty similar where we'll do this for the days left so we'll say total days left equals days left is going to be the length of this uh arithmetic sequence and then it's going to be kind of similar where the number we start with for both of them will be full weeks so it's going to be two times because the number we start with for both of them will be two or full weeks plus one so for example um if our full weeks that we went through was two that means this first number of the days should just be three right so it should be like 3 4 5 6 7even 8 so whatever full week who went through Plus One will give us the starting number for both of them and then for the last day we also need to add what we need to add right so the last day is going to be days uh left minus one greater than the first day right so if you do this the first day will be 2 + 1 which is correct first day will be 2 + 1 which is correct first day will be 2 + 1 which is correct and then the last day will be 2 + 1 plus and then the last day will be 2 + 1 plus and then the last day will be 2 + 1 plus this days left so that'll be 6 minus one which will be 8 so essentially uh this part is going to be in both of them and then this part is going to be in the second one so 2+ 1 is going to be in the second one so 2+ 1 is going to be in the second one so 2+ 1 2+ one and then this is in the second 2+ one and then this is in the second 2+ one and then this is in the second one so you just combine terms here okay and then we also need to get the average here so we got the average multiply by the length of the sequence and finally we just return both of these added together so and there we go and so you could also do this um you could for your days left you could just do that in a loop because you only have like six days or something so you're still quite saving on constraints here right because if this is a th you could calculate your days left in a loop but basically you can do both of these in an arithmetic sum so this would be like a true o of one I guess solution and yeah I think this is like significantly faster than um the other ones and I'm sure I guess we H don't need to do that actually so yeah um so we can write down time here uh and it's just going to be a one and space one and also another thing I noticed I don't know if you guys noticed I think they added a new feature Le code I don't know when so you can actually like click on Solutions now and it will literally tell you like here's what the solution that got this was so kind of useful as well so you can see they yeah okay so finally enough here they actually didn't do the arithmetic sum and it's actually faster than yeah this is why the Le code Solutions don't make sense because here they didn't do the arithmetic sum they actually Loop through the number of weeks and this ends up being faster so for these small run times this stuff isn't super accurate which is kind of hilarious like a slower runtime solution actually uh actually is or sorry a bigger time complexity actually runs faster so that's why I said when you get these Solutions like don't really worry about what numbers you get worry more about like theoretical time complexity because I had plenty of solutions that I wrote that are like that I wrote in oen but then like my n log n answer was like significantly faster somehow so oh yeah so that's going to be all for this one so if you liked it please like the video and subscribe to your channel and uh I'll see you in the next one thanks for watching
Calculate Money in Leetcode Bank
maximum-non-negative-product-in-a-matrix
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Array,Dynamic Programming,Matrix
Medium
null
22
in this video we have to uh generate uh all the possible parentheses valid parenthesis with a given length so let's understand the problem so here we are given some input in n is 3 in this case so in this case we have to generate all the valid parenthesis which can be formed using three open and three closing parenthesis so a parenthesis is considered valid if there is an opening parenthesis followed by closing parenthesis or the other way around is not valid for example if you have this it's not valid but this one is valid although the count is same we can also have nested parenthesis for example in this case this is the innermost parenthesis this is one pair and it is nested within this outer parenthesis and so on we can have other combinations for example with three all of these are the possible combinations so one two three four five so we have to return all those five values so see uh this is a valid parenthesis open close then open close so if you look at this inner parenthesis it's valid and then we have another valid parenthesis pair of parenthesis and then these two are enclosed within this outer parenthesis and you can verify it's true for all there is no other possible ah arrangement of this open and closed parenthesis so that they remain valid so we have to figure a way of returning this so if there is a n is three then we have total six parenthesis three open and three close so let's see how we will attack this problem first let's try with this example of three so initially our solution space is empty so there is no nothing in the result let us say this bracket is the list denoting the result so initially it is empty next uh one thing you can notice is that a closing parenthesis cannot come before opening parenthesis or let's say we have one opening parenthesis and then one closing parenthesis now the count of both open is one closes one again if we place a closing parenthesis then closing parenthesis becomes more than open parenthesis till this point if we are going from left to right so at any point of time we have to keep in mind that number of open parentheses should be more than or equal to number of closing parenthesis otherwise it will be invalid so this is one check and the other condition is that maximum number of open and close parenthesis should be 3 in fact it should be exactly 3 but at any given point of time it should not go more than three so keeping those two points in mind one is that open should always be more than equal to close number of close parenthesis and open should be at any point of time we have not yet reached the complete solution but we are adding parenthesis one by one so at any point of time it should be less than or equal to n in our case it's 3 so we are taking the example of three so here initially our solution is empty we are not reached at any solution so we are allowed to add only open parenthesis since here open is 0 close is 0. so we if we add close that violates this condition so we will only add one open parenthesis so this is the string that is formed so far or we can get rid of this square bracket so this is the current string now we have open equal to one so open is now 1 close is zero so we can add both so we can add one closing parenthesis one opening parenthesis that's fine we can add open because open is still less than three or we can also add close parenthesis since it does not violate both of these conditions so this is another possibility from this value from here we can reach these two now if you look here at this part open is 2 close is 0 and in this case open is one closes one so I am writing them side by side so here there are two open so we can add one more open so that is another possibility now open S3 closes zero so here there is another possibility that we can add one close because open is 2 close is 0 so we can add one close now here again uh we cannot add any further open because open has reached 3 and 3 is the limit for n equal to 3 so we can only add one closed parenthesis so let's draw it below so that is the only possibility and here again open is 3 so we cannot add any further open and close is one so we can add more close parenthesis now it's 3 2 so we can add one close parenthesis now there are three open three Clues we have reached a solution so this is one of the solutions now let's get back to here open is 2 closes one so we have two possibilities we can add after this point we can add even open because open is not yet 3 or we can add one close because close is less than open now from here we have three open parentheses so we cannot add any further open parenthesis so only thing we can add to this substring is this close parenthesis and same thing three open two close we can only add one close and now we have three open three close parenthesis so this is the solution and let's come back to here we have two open two close so at this point of time we cannot add one closing parenthesis because that will exceed the number of open parenthesis so we can just add this open close open this is the only possibility and here there are three open two close so only possibilities one close parenthesis so this is another solution so this we have listed all the possibilities now let's get back to this here only thing we can do is add open parenthesis because there is one each so close can never be more than open and here we have two possibilities so let's draw them left and right so we can have open close open so we can add open and we can also add close now here 3 open so only one possibility that is close here also three open two close so only possibilities close so this is another solution and now here two each so we cannot add any further close so because close will exceed the number of open so only possibilities open now we have three open to close so we cannot add open since it will cross the maximum limit of three so we can only add close so this is another solution and we have listed down all the possibilities so we have these five possible valid parenthesis and you can see that the expected value was this same list of five strings having these parentheses so this is how it works now how we will convert it to code so we start with empty string so initially this is empty there is nothing here so it is a empty string then uh at all point of time we will check so we have this function let's say list parenthesis let's call this function p so we start with empty string and then we check uh we keep track of open and close so open is zero close is 0 initially so we check if open is less than n so n is the maximum length then we call this function again by adding this open parenthesis open equal to 1 close equal to 0 n equal to 3. and if close is less than open then only we can add this close to whatever string so let's take a generic string Str or current string then current Plus open we will add if open is less than n and increment the value of open and this will remain same and if close is less than open we can call it again with current Plus disclose and then open close plus one and three so let's see so here it will the string is empty when we call it with this we can add this open bracket because open is less than 3. so it will further call again check that open is less than three so it will again call this part again it will call this part now this condition is no more true so we made three p calls each time adding one of these open braces so we have three nested calls you can see here this function was called with adding this then again it called this now this first condition is false so it will go here close is less than open so at this point of time close is less than open and we cannot add any Open Bracket so we will add this so another call is made and what is the termination condition so we have to add a termination condition here that if current string so current is the variable here which denotes the running or the current string dot length is equal to 2 times n was 3 so if it's 6 3 open 3 close then we add this value to the result add current to result Vector so we have to return the all such string so whatever is the current result at that value there so now get back so here the length became 6 and we added it to the result so these are the series of calls made here you can see here in yellow so this call returns here there was no other call here so it returns here back here so this function had called triggered this call now ah it will come to this part so this option was called the other call can be made is adding this closing parenthesis here so this is the closing parenthesis so the left side denote when we added this open parenthesis now again it calls it first tries to add open so it can add open parenthesis so it adds now it calls again with this again the length is 6 so it will terminate back here and this will be added to result back here and now it will it can it has already tried with the open uh parenthesis so it will add this closing parenthesis and there is only one possibility and this will be added to solution since the length is 6 so it will return to calling function back and now this call terminates and comes back here this call also terminates comes back here and it tries a bit so it has added this open parenthesis after it so now the other possibility is with close parenthesis and here just one call is made here again two calls so you got the idea why this should work so now let's try it in our code so we will have we have to return a vector of a string and this is result and then let's write a recursive function make sure to pass by reference and then the count of open parenthesis count of close parenthesis the maximum length n and the current string so we have to add the termination condition if current dot length equal to 2 times n then we have to add this to the result whatever is the current string so result Dot push back current if this is not the case then we have to go down further so if open is less than n then we call this function recursively by adding One open parenthesis to the current string result or open is one more close remains same n remains same and current becomes current plus this open parenthesis similarly if close is less than open then we will call with adding a closed parenthesis and this these recursive calls will terminate once it has six parentheses and at any point of time while adding these opening and closing parenthesis we are making sure that those are valid so once the length becomes equal to 2 times n or in our example 6. then we know that it's a valid uh combination of parenthesis and here in the main function we will call this generate parenthesis and we will pass the result open should be initially zero close is also zero and the string is empty current is empty and finally we return the result so in this case the answer is correct let's submit if all the test cases pass or not so all the test cases are passing so I hope you understood this problem looked uh daunting in the beginning but it's just a few lines of code and it gives you a good practice of backtracking so you can see here we are backtracking we are trying first with opening uh adding open parenthesis and once we reach a solution we go back and then try with close parenthesis and again continue so it these kind of problems you need to will give you a good practice of recursion and backtracking
Generate Parentheses
generate-parentheses
Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_. **Example 1:** **Input:** n = 3 **Output:** \["((()))","(()())","(())()","()(())","()()()"\] **Example 2:** **Input:** n = 1 **Output:** \["()"\] **Constraints:** * `1 <= n <= 8`
null
String,Dynamic Programming,Backtracking
Medium
17,20,2221
735
hello and welcome to today's daily lead code challenge let's begin question 735 asteroid Collision in this question we are given an array of asteroids of integers representing asteroids in a row for each asteroid the absolute value represents its size and the sign represents its direction positive meaning right negative meaning left each asteroid moves at the same speed find out the state of the asteroids after all collisions if two asteroids meet the smaller one will explode if both are the same size both will explode two asteroids moving in the same direction will never meet okay let's rephrase this in my own words we're given a asteroid belt and this asteroid belt there are some that are moving to the right to the left some are different sizes some are the same we are a tasked to figure out which ones of the asteroids are left in the asteroid belt after all collisions after all possible collisions have occurred a collision is going to occur when um two asteroids are moving towards each other um and a collision will eliminate asteroids if well an elimination is going to occur but a bigger asteroid will eliminate a smaller one two asteroids of the same size will eliminate each other okay and so we're tasked to figure out which asteroids are left after all collisions have occurred so um let's start with some examples we're given an array of five ten negative five so these two are moving to the right this is moving to the left it's clear that this number 10 moving to the right will eliminate the negative five and we're going to be left with 5 10 since those are all of the same size that seems to be the output in this case they eliminate each other because this one's moving to the right this one's moving to the left and they will cancel out in this case we first see that the negative 5 eliminates the two but then the 10 eliminates the negative 5. okay so I guess what to notice here is that um I guess what we can notice here is that we don't have to compare um we can compare which asteroids eliminate which other ones in any order because um given let's say that we're that we have this here um we can know for certain that these two ones will meet eventually and these two ones will meet eventually so we don't have to look at either one of these in a particular order we can actually just be looking at them one by one we can first look at if these two are safe then see how adding a third one will affect our sort of safe asteroid belt and then if this gets eliminated or eliminates some in the safe belt we then look at the next one and so on so this kind of gives us a hint into what the approach is going to be um so the hint here is that since they're all moving at the same time it doesn't matter which asteroid collisions we look at first the collisions are going to occur regardless and they're only dictated by the position and the direction in which the asteroids are moving so with that let's have a safe belt and this is going to be essentially a stack and then over the um so this is going to be a stack and then we're just going to iterate over the asteroids that are given to us and see how those asteroids affect our safe belt so for asteroid is in asteroids we're going to do some logic and then we're going to return the safe belt okay so how do our asteroids um act in the asteroid belt well there is I see a couple of three different scenarios uh scenario one um new asteroid I'm going to call this new asteroid El Lima mates sum in the safe belt uh two new asteroid is a limit Ed um and then three which three is a bit sticky I think because it is essentially both of these and it can happen at any time but the third one and I'll figure out where to put this next is uh new s um asteroid eliminates some and then is eliminated so given that we have these three scenarios essentially let's figure out um how to treat them well um how to treat them I know that I know what conditions would make a I know what conditions would make an asteroid be eliminated so why not um why not just start with that how do I treat this hmm I have a new asteroid and my new asteroid will somehow affect the safe belt the belt of asteroids that I have already considered to be safe um what are the different scenarios well I could say that if an asteroid if the new asteroid is moving to the right then I can essentially just add it without even doing anything is that right um so I guess there is a fourth one nothing gets eliminated nothing gets uh and let's start with this fourth one actually at the top um let's say that if new asteroid greater than zero save belt append new asteroid and continue pretty simple um that seems about right so now what if the asteroid is not moving to the right and what if it is moving to the left then there's a condition upon there's a condition one where the asteroid eliminates some asteroids in the safe belt or potentially just gets added to the asteroid belt so um and but all of these fall under these three scenarios so if it's already moving to the left then it's going to be one of these um let's see under which condition would this and this be met and I'm getting a feel that these will be somehow related so if um save belt negative one is greater than zero no if it is moving to the right so yes if it is greater than zero and let's see safe belt um negative one is smaller than absolute value of new asteroid I'm trying to get the situation where I'm actually removing or popping um asteroids from the safe belt well this would lead me to pop all of the asteroids that are in the safe belt so one more time given that we're already at this if statement we are our new asteroid is moving to the left and if asteroid belt it still exists and there and the second in the last asteroid belt is moving to the right which would mean that they're colliding and the safe belt asteroid is the last asteroid in the safe belt is smaller than the absolute value okay let me see this absolute value of the new asteroid then I'm going to be popping this asteroid and This falls under the category of new asteroid uh new asteroid eliminates some in the safe belt and let's see since once it has eliminated all of them um I think it's safe to add the asteroid right uh could I now just say that the um I need to make sure that the asteroid here isn't of the same size because if it is of the same so if um I actually need to look at oh but how would I okay so if safe belt so if there is a safe belt and um the last asteroid belt and the safe belt is uh if the last asteroid and the safe build is equal to no is if it's larger then let's say equal to new belt then nothing happens both get destroyed if um if however both don't get destroyed and um if how about this first okay I'm going to remove this for now I need to see if um I need to see if the safe belt is actually empty if that's the reason why we've stopped this oh and this should be a while safe belt and belt negative one is greater than zero so there is an asteroid moving to the right and the safe belt last asteroid is smaller than the new I'm going to be destroying them so now what is what does it mean that we've passed this while loop either that there's no more either no more safe belt or I've met and S terroid that's greater I've met a safe asteroid that's GR ater or equal to new asteroid okay and we have to take care of all of these scenarios so if the how do we do that uh just one at a time would probably be the best solution unless there's some pattern in between them unless one of them can go first and the other one can go next um okay so how do I do that if not safe belt then could I just save belt append new asteroid right uh what about if not safe belt okay now if safe belt meaning that there is a uh meaning that there is something in a safe belt but they are of the same size no if they are of the L if they are of the same size or greater so if they're of the same size then would I if L if uh safe belt is greater or equal to um no let's say greater than uh new asteroid if it's greater than new asteroid then how do I then what do I do then I just simply continue I don't do anything the new the safe belt continues to exist and the new asteroid is removed so the only thing I need to care about is if it is the same if it's the same then I say safe belt pop um save that belt pop and is that it I think that's it so if it's the same belt then I don't do anything and I um and I remove and the new yeah I think this is it um let's try to run this and go through the logic one more time um so again the what I'm trying to do is essentially safe belt is a stack and I am trying to write out all of the situations that would all of the conditions that would or I'm trying to meet all the conditions uh there are three different cases the cases are the asteroids are just moving in opposite directions or sorry the bet the better way is the asteroid the new asteroid is moving to the right in which case nothing gets done about it just keeps moving the other situation is it's moving to the left but um but so but it and if it's moving to the left there are a number of things that can happen either um either we have to remove some asteroids from the safe belt and that would be only if the last asteroid and the safe belt is moving to the right and is smaller uh than the new asteroid so if that happens then we keep on popping elements from the safe belt until that condition no longer meets uh that condition can break on two different scenarios one the safe belt is exhausted and if it is exhausted then the new asteroid beats everyone and it is now the start of the new and is now the end of the safe belt in which case we simply appended and um and move on the other situation is um the asteroid those the last asteroid is actually uh bigger than or equal to the new asteroid now if it is bigger than the new asteroid then we don't really do anything we just don't we just remove the new asteroid from the condition otherwise if it's equal to then we pop the safe okay so now there's a situation where we could actually be popping from the safe belt for a while because um yeah so how do I take that into account how can we be popping for a while so um yeah let's continue let's submit this and see where it goes wrong and I yeah it clearly does go wrong somewhere but uh okay these two are moving to the right okay so what goes wrong here because somehow this asteroid gets removed from the stack how does it now how does it get removed um okay so let's start debugging um started debugging how do we go about this uh well probably I just want to print the um save belt for each one of these iterations and at least see where it would be getting killed so um so what is the case where so why does one never appear here why does negative one never appear um new asteroid is smaller than so then at which point would I add it what I only add it if well a save belt if not save belt and then yeah so I'm not looking into the situation where I simply um I simply add the asteroid since it's going to the left so with this if my asteroid if my new asteroid is moving to the left the belt is not destroyed and um it's not equal then couldn't I just say safe belt append new asteroid would that work oh else okay and now the other ones are failing but this one is causing so um how do I split up this logic into more into better blocks um hmm um what okay I'm overlooking the situation where the new asteroid is moving to the left if it's moving to the left it's definitely going here and since it's going in here and this scenario then um this is not going to get executed because could I just this is not going to get executed so if not or if not safe belt or save belt negative one is smaller well it is going to be smaller than zero right smaller than zero append and let go yeah because I can't have that else there we go okay so I had that else there and that would meant that things that don't meet the condition in the case where a new asteroid is just not taken acknowled is not acknowledged it was being added so let's submit here and see if this actually okay time limit exceeded how can time limit exceeded oh because I still have the print statement Okay so okay let's submit one more time and I'm pretty sure this is going to work um all right who so that was a bit of a hard one I would say um hard not because the implementation is hard but because it's hard to keep track of all of the different conditions that are happening one by one so um let me just go through this one more time quickly uh this is I don't even know what this is heavy on just keeping track of different conditions that are happening but we have an asteroid belt and we have to meet uh a bunch of different conditions there's uh two asteroids that could or could not Collide if they're not colliding um it means that three things are happening either the going in opposite directions either they're both going to the left or they're both going to the right um that's already three conditions to take no I a lot I lost track they could be colliding one yeah that is four conditions either they're not colliding which is those three or they are colliding if they are colliding then we have to consider which one will survive or if either Will Survive and that's another three conditions uh left one survives right one survives both survive and then we have to see and then we have to repeat that logic so uh yeah this is a bit of a harder one I actually don't appreciate these as much but um this is a pretty clean solution still and very little code uh I would probably imagine that pretty much the rest are going in the same pattern um yeah they both are they're all using a stack they're all have a for Loop and they all have some conditions so this one is a bit different but still the same yeah Yep they're all approaching this the same way as stack and an iteration over all of the asteroids so in that case um I would just see if this one makes sense to you and uh feel free to use this all right well thanks for watching and we'll see you later bye
Asteroid Collision
asteroid-collision
We are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. **Example 1:** **Input:** asteroids = \[5,10,-5\] **Output:** \[5,10\] **Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide. **Example 2:** **Input:** asteroids = \[8,-8\] **Output:** \[\] **Explanation:** The 8 and -8 collide exploding each other. **Example 3:** **Input:** asteroids = \[10,2,-5\] **Output:** \[10\] **Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. **Constraints:** * `2 <= asteroids.length <= 104` * `-1000 <= asteroids[i] <= 1000` * `asteroids[i] != 0`
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
Array,Stack
Medium
605,2245,2317
224
hey everybody this is larry this is the 11th of september so that you'll have on the september league daily challenge hit the like button to subscribe and join me on discord let me know what you think about today's problem basic calculator um you know i'm from new york i grew up in new york my high school was actually um a couple of blocks away from um from uh the old world trade center so yeah i hope everyone you know i don't know what to say about these things but yeah i just hope everyone kind of keep it in mind and i don't know maybe just sitting in some of us it's kind of tough to figure out what is up but it is 20 years so 20 years is a long time um anyway you're not here for that i suppose but you know but i am from new york and it's in the handle so you know gotta it is what it is right um anyway today's problem is basic calculator um so okay return to resolve the evaluation you're not able to use any url okay so this is kind of um a silly problem that basically you know i mean it's just what implemented right except for that it could be messy and you know it's a very implementation heavy one uh the one that makes it slightly easier is that it only has plus and minus um so yeah so i don't think there's that much to explain um there are a couple of ways you can do it you could do it with stack you could do um what's it called um recursive descent uh and stuff like that if you like um and if you want to learn more you know google them but this is you know passing has been a thing that's been you know um from the beginning of computers ever since you have computers you want to pause and people build you know languages and stuff like that and there's a lot of fun things you can do with it so you know so and i don't know if this is still in style anymore but when i was younger definitely um these kind of problems were on more interviews because they were considered practical because you know these are things that you do in real life yeah maybe at the time anyway in theory because nowadays you could just you know their functions and their libraries and their language libraries and stuff like that and the libraries on that libraries that kind of help you do these things anyway but um but yeah uh without further ado i do let's uh you know take advantage of this subset because we don't have to worry about um we don't have to worry about the order of operation because we only have plus and minuses uh i could be used as the unit has to be inside parentheses um what does that mean or like i know what this part means but i don't know what by inside parentheses do they have an example i feel like i'm gonna have an example by um by getting a wa getting a wrong answer together because like okay i mean i guess we could just try it out right like what does that mean damn it's like 91.1 is does that mean damn it's like 91.1 is does that mean damn it's like 91.1 is that just zero that does make things a little bit trickier if that's writing but uh okay well but yeah i don't really think they have damage to teach it is just a practice type thing what does the inside parenthesis mean that's really con oh i just don't know what that means there'll be no two consecutive operators i guess that makes sense if this is not a thing but is that a thing then okay so this isn't a thing but the other one is and you can imagine you have someone like this maybe right but yeah i mean to be frank this is just going to be really annoying i don't think oh i guess this isn't still invalid try to remove it first but yeah it is probably just you know if you spend enough time on this you can get it but it's it is just annoying um because now there is some complexion with just being a possible negative um so yeah okay first of all maybe we'll replace how does replace work um or maybe it's just start like that right so we remove all the order um we remove all the spaces because they don't do anything other than making us confused so yeah okay that it works so i make sure because i'm really bad at python apparently so yeah okay then now we just pause one character at a time and in this case now you know i've been grunting and kind of trying to figure out how to do it but i mean i know how to do it's just this is one of those problems where it doesn't matter you know i mean you could do things slightly cleaner if you have experience but it is just going to be putting in the work so let's get started then uh let's just use a stack and then okay what do we do okay if c is equal to 2 then we push something up then we put the current number on the stack so let's just say current um yeah let's just say how do i do this i don't even remember this anymore but if it's fine yeah i just say current is zero if this is this then we just push this on the stack um else if c is equal to do then we push it off the stack then we pop the last number of the stack and then either we but let's write out the cases but even if we don't write out the code yet um either stack is empty and i guess we're done no that's not true well in this case then we can actually um yeah okay then we can now start merging let's actually uh let's just uh append this maybe this is less confusing okay we append this and then here we um yeah while length of well i mean okay i guess this should always be true now while the last element is not to do what do we do well we pop it like mary poppins um whoops this is the beginning of this like i mean that means that okay so we take so this is the last number and then the last operation is you go to the next pop um this is if length of stack is this right let me think about there's so many cases to think about when i think about this oh yeah so if the top is not right then it must be a number but can you have something that just um can you have something that's just um like this is that a valid input i guess so okay so in that case okay if length of stack is greater than zero then that means that we have an operator and um i guess that operator can actually be um okay i guess we have to check now if stack the top of the stack is equal to the thing then we just um we're just able to pop this and then we push x back on so basically we reduce um this thing so this is the case of in this case it's just something like this and then we do this to five right that's basically what we're doing here and then we continue otherwise what happens otherwise we have an operator so we have op is to go to stack.pop i so we have op is to go to stack.pop i so we have op is to go to stack.pop i suspect i'm going to get a live wrong answer for this so don't i mean you can learn from me making mistakes i think that's gonna be the thing uh and i think it's a little bit late because i forgot to say it this time but i am usually solving these lives so feel free to watch it you know in a yeah faster speed or whatever i'm going to see how larry messes up um yeah and why is he going to stack that pop and then now if up um yeah i guess the hard part is that you can you know i'm the hard part is that you have to do the operations left to right so and that's not quite the way that i'm doing it so it's a little bit awkward um i think there's probably a quite more clever way to do it but i'm like i'm just going to do something a little bit dumber um okay so then now while stack of negative one is not equal to do don't try this at home i would not recommend this just to be professional parsing code but yeah so then here um to do is you go to this to do dot append stack that pop so then now we keep on adding these things and then now we look at from the bottom up okay file to do length of to do is greater than zero um okay or if this is okay and then at the way and we pop off the top of the doo for the future and now for to do now we can go from right to left to do it okay so while this is at least three and it should be at least three so that should be okay dude pop so this is x is the first number up is equal to the second operation and then y is equal to do um and then we um and then what do we do uh yeah and then we hmm if ob is equal to plus uh we push this back on x plus y else um x minus y i think that's it okay i mean this isn't quite right but i've but it is i'm just gonna try to see how it goes oh the next i don't handle this case okay oh yeah that way and we um we should have length of you know would assert that length is you go to one oh and also you might have multiple numbers this is so annoying because you got like for some something like this um and yeah and i don't handle this either because that's not an operator but okay let's print out the stack at least this should work though i mean it may not work correctly but it should do something hmm oh i don't append any other things that's right otherwise we appen see though again this is working process so uh my apologies yeah oh i have to convert them to ends but that's okay so this looks okay this does not look okay because of this uh negative one and but anyway okay so let's just say and no else if c is in is numeric then we have panned in version of it otherwise we just this is an operator and we just append c still not super good because of that negative thing but i think we should be okay uh well hmm i don't know this is for the next one so okay wait is that right oh well because we have to do this thing at the right end again okay let's just have a helper function for this hmm okay and then now because of that we can we can evaluate this but from left to right so that means that we actually want this to go backwards because in here the way that we did is we actually uh we kind of look at it backwards i don't know this is way messy i'm not going to lie nice very well evaluate that's not right so now i don't have a spell anymore because i feel like i saw it like five times kind of thing okay i think now we're good except for this unit well and this number we have to pause as well but uh okay but that looks you know in theory this looks good so this is hopeful for me um and of course if you know you should consider the tdd type thing and you would have uh more test cases that kind of address these things but of course uh you know this thing fails and then tells me like one time hours right so um but conceptually uh you know we will kind of see what pass and what fails and i'll be okay but yeah um i think the first thing we need to do um are these this actually maybe could be right four of these nope i don't get this one right so this is six and this is four so why is this four it may be that i just don't have that's not right oh how do i return this i should this is where i should return okay it's just that i returned the wrong thing because i changed the code without thinking about it okay so this is mostly right again we don't we know that this is wrong this is expected wrong in this is one expected way because um because we didn't implement multi digit things here we can kind of um yeah how do we want to do it yikes so okay so it can be a leading zero let's think about all the possibilities that has to do with here right so the cur the current parsing is think is this thing and that means that we don't okay so if it's numeric then we times it by 10 and then we add end of c um and then for everything else and then what can follow this right it can follow it as an operator so here we append uh current and then set current back to zero and then uh add the operator that's following and then the other thing that could follow it is this thing so let's also put that there um yeah because the thing that is before this has the close friends has to be a number right so we can do that um let's see if that gives us the right answer for this nope i mean i think we're in the right direction but i might be missing a case hmm oh this is i don't know what this should be but i guess we set it to zero anyway but this is an awkward part of the stack so it's a little bit weird let's put out the stack is ready to get it as well where's my other print statement right where does that come from okay so empty and then this and then we get this all right let's get c so we could see what character we're passing okay we process one we just processed correctly if this files it correctly this it keeps going and then oh and then it's the end of the string okay so down here if current um how do i think about this huh i just have a flag ongoing as you go to force here it sets ongoing as you go to true um ongoing as you go to force and then now if it's ongoing then stack data pen current and then hopefully this should be good for the last dump that's basically why we're doing it nope uh five one i mean this d should be backwards so that should be okay that's six okay five okay now i think we're this there's an extra zero here so this is six and this is four but why is this 0 oh i guess we should only yeah we should only do this if we haven't already passed it because otherwise it doesn't make sense i don't even add one there okay so here now everything is good but we don't handle um i mean i don't know if this is good but it is a better than what we had before let's actually add a couple more of multiple digit ones uh this is just me banging on the keyboard i don't know the answer to this but if this is right i'm i'll be really happy okay so this is right so i'm actually very happy right now um and if and i don't really have a good explanation if you have trouble catching uh following along not because i'm pretending i'm arrogant and smart or whatever but because this is the opposite this is terrible this is me just literally thinking about and having an if statement for every possible case so this is terrible uh i don't think there's anything underlying behind it's just about like i said earlier right it's about grinding and kind of pushing through and getting it and that's it i'm still not done i okay so i have all this but i don't have to one that is um let's just say negative one plus five right we don't have that we don't have five plus um negative one plus uh ten but what i was thinking was actually we should also handle some zeros just in case i have some weird zero logic um yeah okay i suspect that this should give me an exception about passing one time things yep because right now we count this as an operator but hmm okay i think we can actually this one can only be part of they're saying that it has to be in the beginning because you cannot add negative thingies right let me remove this for now just to make sure that everything oh i guess this one as well just make sure that everything still pauses i want to make sure to check the zero cases first as well okay so that looks good so far and then the other thing i wanted to make sure was that um like something like this does that count okay so this is a valid input but that's why that's what i was checking because you cannot do something like this but this is a valid input right because now it should give me an invalid expression okay and then now these should be other ones that are good um i think this is also good the negative one plus five um okay yeah so in that case that means that the negative appearance will only be in the first item so we can actually hard code this maybe we'll see if this is right but um yeah if length of total is greater than zero and the first element now that's actually the last element because we're doing it backwards is equal to negative then we pop the negative and then we pop the pre the top number and then we just append negative x right okay let's give it a spin okay so this looks good i think but if you ask me about my confidence would i stick anything in it i wouldn't even i wouldn't put my money in it i wouldn't even put you know a sandwich on it uh so that but that said i am lazy though so let's give it a submit and see what because there are billion test edge cases so i suspect that something will fail but of course after i said all that it did get accepted on the first try so i'm really happy uh okay so the running time is going to be linear because well i didn't mention this but n is 10 3 times 10 to the fifth so if it's not linear it's going to be too slow anyway um and i know that n log n would be fast enough for 3 times 10 to the fifth but you would have to have a weird operate um you have to do something weird to get unlocked in this case um but in any case we basically for each character we only push and pop off the stack once and then we also push and pop off this to-do we also push and pop off this to-do we also push and pop off this to-do thing uh once right so we push and pop off here once and we push and pop off the stacked ones so in that case everything is going to get pushed and popped once so this is constant per character or per chunk per token um so yeah so this is human linear time in terms of space of course we use linear space we have two stacks and it can get pretty full like a full house party kind of thing so yeah linear time linear space that's all i have it's a little bit long um and like i said i just did everything by if statements i um my strategy was to just break it down case by case and kind of try to make progress slowly but incrementally and hopefully this is good for you anyway uh stay good stay healthy to good mental health i'll see you later uh and yeah have a great weekend bye
Basic Calculator
basic-calculator
Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return _the result of the evaluation_. **Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "1 + 1 " **Output:** 2 **Example 2:** **Input:** s = " 2-1 + 2 " **Output:** 3 **Example 3:** **Input:** s = "(1+(4+5+2)-3)+(6+8) " **Output:** 23 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`. * `s` represents a valid expression. * `'+'` is **not** used as a unary operation (i.e., `"+1 "` and `"+(2 + 3) "` is invalid). * `'-'` could be used as a unary operation (i.e., `"-1 "` and `"-(2 + 3) "` is valid). * There will be no two consecutive operators in the input. * Every number and running calculation will fit in a signed 32-bit integer.
null
Math,String,Stack,Recursion
Hard
150,227,241,282,785,2147,2328
1,696
you are initially standing at index zero in one move you can jump at most k steps in one movie jump to those k steps without going outside the boundaries obviously and the index i to any index in the range of i plus 1 minimum of n minus 1 till i plus k so you want to reach the last index of the array which is n minus 1 so your score is the sum of all numbers of j for each index j you visited in the array so we will try to go from good force of course to the optimal so for each index if we want to consider if we visit this index then we can go either one job or two jump for getting the optimum answer here they have done one jump then it is one minus one zero then from here they have taken two jumps then the total sum will be total score will be four and from here they have taken two jumps the total score will be seven so four plus three seven so seven is the optimal answer that you can get maximum max mean so we have to maximize it so we have for each index for considering in each index i can take k steps i can take from plus one plus two from the for this index i can take plus one plus two so i can i have many possibilities so i have choices obviously if we have any choices then we can go for a recursive problem because the solution so i will write the recursive function passing the parameters nums k and 0 is the index i so now i will define the recursive function so if i has reached my end of the edit number size then i can say return 0 or else i should i will declare a value which is uh minimum in women since i have to get the maximum score i will say it has messed up my score and i can for each and every index i can go at most k steps so i will have a variable steps that starts from 1 still steps less than or equal to k steps plus next step i plus steps if my next step is greater than or equal to my number then i can just break this income this would be a more case where i can handle or else i can find the current score considering uh i'm taking this skip steps out so i can uh include this index the included indexes numbers of steps plus solve of nums k and next step and i will update my max score raspberry so max 4 is nothing but max of max score comma that's good so i'm finally i will return max code so this will be my recursive approach i will be taking all the possible cases uh max of mexico uh oh this is numb some steps it's numbs up next overflow um next step if my next step is like the steps now next time is greater than my number size then i am making the slope i'm calculating the current score numbers of my next step last solve of numbers k and next step and i'm going to do that index and i will be taking the all the k steps if i am going to reach mems dot size minus one then i will just return next return zero computer that i don't want to take subscribe i want to reach the end of the exo here i have two for each for every result i'm going to include my first element uh because as you can see that when i call this recursive function it goes to this call and then i will declare a max variable then i will not include this first element and rather i will implode the next element the steps count as 1 so 0 plus 1 so i plus 1 which is 0 plus 1 and i'm going to add the num sum 1 only i will not be adding numbers of zero itself so uh what i can say is numbers of zero can be added here always i'm going to add so the score which is at the first index and then i'm going to call this recursive function so hope this makes clear here we are seeing every possible cases but this will not get accepted as the constraints is uh in terms of length is important and cased in perfect now it grows exponentially the time composition will be exponential in nature so we can try to memorize it for memoization we want to see what are the changing parameters is only the yield i is the ie varies 0 to n so i will declare on the array current dp of size now size unable to initialize with minus one i will pass the dp in amazon dp and i will pass dp here as well if my dp of i is not equal to minus 1 then i will just return here this recursive call will go for order of n so the time complexity time complexity k steps so r of n into k as you can see the n grows still at in power and k is also 10 power okay so it will be 10 power 10 so 10 power 10 is a n square solution so this will give our tle obviously the space complexity is our rock and we are using an extra uh we are using an extra space of automation and then auxiliary stack space two we are going to use text so the of our recursive solution so we can try to submit the code so we get time limit excited for this so how can we optimize this further so let us analyze what we are doing in reverse matter let us take this example one minus two then four minus seven and three so obviously from back we will be taking this three then the three steps now then three steps we can we have taken and uh in minus seven what is the best steps we can take minus seven plus three which is minus four then from minus four uh from this four what are the three step what are the next step i can take either this minus seven or this three so i will take four minus four zero or i will be taking four plus three seven so i will be taking four plus three seven next i will be taking a uh minus two either i can take this seven or i can take this minus four so which is best i will be taking minus two plus minus four which is minus six or is best or seven minus two five is best so i will be taking five next uh minus one i will be taking either five minus one which is four or seven minus one which is six i will taking seven minus one which is six so i will be taking some minus one which is six i can move only k steps which is two steps so uh what i'm doing can i you can observe uh that i hope it makes sense then in one i will be taking either this six or this five so one plus six which is seven or one plus five which is six so i will be taking the maximum which is one plus six which is seven so i'm filling this dp array in the reverse fashion uh so by for each uh iteration i go i will be going i for each i index i will be going to uh every k steps forward and i will be checking which is best so obviously for each and every step i am getting the maximum element of that i will do a dry run once again so that it will be more clear for you i will be coming from reverse and taking this current and i will be taking this current elementary so i have pulled it so in minus seven uh from minus seven what is the maximum element on its right it is obviously three so i will be taking y minus seven plus three which is minus four then uh from this current index what is the greatest element of these two elements it is obviously three four plus three seven uh i should not see all the elements that are in right yeah we are having only k steps so we have to take care of those k distance also so 4 plus 3 7 in this minus 2 what will be the best option that i am going to choose i cannot have a choice of choosing every the elements in the right i'll be having a choice for only 7 and minus 4. so in minus 2 what will be the best possible element that i can choose is obviously this seven minus two which is five so i will say it as five in this index minor in this element minus one water in this course with the score or what is the best element that i will be going to choose i will be choosing 7 so 7 minus 1 which is 6 so i am just want a greater element always i just want a greater element if i'm if i have some way to have a greater element seven five uh such a way or three minus four such a way what you can understand in this i am having a monotonically decreasing elements of k elements monotonically decreasing k elements if for each particular for each index if i can maintain a monotonically decreasing k element then i can say uh for to calculate the current index i consider the dp of i is the current index to calculate the current index db of i will say uh the some data structure uh considered for the monotonically decreasing k elements i am having some data structure ds data structure dot friend top but the element which is a different plus my number of i so this is uh this makes sense right it makes sense dbfi is nothing but data structure that uh databases of print element which is going to give me the greatest element of k distance plus that number of i and then i will obviously uh obviously insert this dpf i do that monodragonically decreasing their k elements so how so to maintain uh monotonically decreasing k elements we'll be using a dq which can be inserted or a friend insert front and back so by this i can maintain the to maintain the order so that i can reduce this k loop instead of uh going for a n square solution we can reduce the scale loop and we can do it in linear method so for this particular index one i want a greater element of 6 and 5 if i have a data structure if i have a dq where i have maintaining the 6 and 5 i can take 1 plus 6 which is 7 sound will be the answer and i will move consider in the data structure dq i have six and five now i have calculated the dp of is db of is one plus six which is seven so now i have to insert seven here how we can insert i am going to insert uh seven uh if uh insert seven if this uh elements are smaller then i will be inserting the seven at the back so i will be popping this five and then i will be popping the six and then i will be inserting the seven domain eq right this is what i'm going to do now we will write the code so that it will be more clear now we will try to import this approach first of all we are going to have we will eliminate this code i will have a db of dp of size yen itself of n minus 1 dp of n minus 1 is nothing but numbers of n minus 1 then from last before and x 4 and i equal to n minus 2 i greater than or equal to zero i minus i will be having a dq which is the data structure eq i will name it as dq itself so this is going to maintain monotonically decreasing elements this is going to maintain my monological decreasing elements so from the last before index i'm going to traverse it and i'm going to calculate dp of i is nothing but dq uh dq dot friend plus my numbers of i correct yeah it makes sense so then i will be pushing this dpf i into my dq if my dq is not empty and if my dq dot bank is less than my dp of i then i can obviously pop the elements i can obviously pop those elements yeah i don't want those elements they are smaller than the elements which are in the back so i will uh just pop those in sleepy. dq dot com back after popping back i have to insert this dpr file insert this current element into my pack so dx do not push back of dp and finally what we are going to return db of zero as you can see in my dpf 0 the value is stored 7 so this is what we are going to do but is that all the cases are handled no uh for each and every index i we are going to calculate the next care we are going to maintain the next k elements but how we can see that this current index if my current index current value is the current value is exceeding that k distance if this alignment is uh calculated and if this element if the queue has this element in the friend then this 6 scan can't be calculated with minus 4 because it is k distance more than that so we have to keep some index to that data structure so that we can maintain them we can eliminate those uh those elements so how we can do this we can uh instead of inserting elements into our dq we will insert the index into rdq uh so we will insert the index dq dot push back of n minus one so instead of dq dot friend it will be i and we have to check if my dq is my dq dot friend minus the current index i is greater than k then i will be deleting that element i don't want that so i will deleting the dq dot print element index so hope that makes clear we are eliminating this uh k distance elements that's it we are nothing uh doing more complicated we'll use the example test cases and run the code we get uh wrong answer let us see where we are making the mistake sorry here they use my dq dot friend minus i is greater than yeah okay i am going to say that i am eliminating that element so dq friend so i should do the dq dot pop file so i have eliminated that index element i have admitted of i and then while the dq is not empty so this is wrongly checked if my if there is at least one element size then install on black is less than my dp of i then i will popping back and then i will be pushing back next let us check what is happening here sorry before we answer the dpr friendly via friend will giving me the value but this is not the numbers of dq dot print it is dp of dq dot friend right now i think it will be the current answer we have made some silly mistake um it is dpp of it got accepted so here the time complexity will be order of n and this y is not going to cost me r of k so it will be this it is uh just in our linear solution it is so hope you like this video so let us see tomorrow's video tomorrow's great coach daily challenge
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
778
hey what's up guys this is chung here so today uh lead called number 778 swim in rising water okay so you're given like an unbiased grade right so each element or each position represents the elevation of that point and now the rain water starts to fall now the rain starts to fall and that's why i know the water will keep uh keep rising right so at time t i time t the depths of the water everywhere is t okay and you can swim from a square to another neighbors neighbor four adjacent squares if and only if the elevation of the waters sorry if both the division of the squares individually are at most t right and then you can swim in different in infinite distance in zero time and of course you must stay within the boundaries of the grid so our task is to find out the minimum time right so that we can swim from the top left corner to the bottom right corner right so yeah so for example we have a like two by two uh grid here you know so each of the cell has it has their own height right so the answer is three because you know so see at that beginning the zero the top left corner has like zero height which means we can swim uh here but we cannot swim to any neighbors right because we have two zero one three right so in order for us to swim from zero to two we need to wait for two for time for two times right from zero to one we need to wait for one times right and then either from two to three work from one to three we also need to wait some time right for example from two to three we need to wait for another time here we need to wait for another two time that's why the answer is three because we need at least three time to swim from the source to start to the end right and yeah so that's it right i mean the uh the range is at fif uh is 50 by 50. right so obviously this one is a con it's a kind of like the uh a graph problem or like a search problem right uh so i was at the beginning you know every time we see this kind of uh what is that uh the list where the minimum values we're looking for in the graph problem uh i actually at the beginning i was thinking about can we use a bfs search right but the bfs search um it seems like this graph problem is not like a bfs problem because it has like as you guys can see it has a weight right it has a weight on each ad so from here to here it's not free we have to wait some time so that's why you know this one is not like traditional bfs and then we can definitely use uh dextra right to solve this problem and yeah and we'll be uh doing the doctor today and there's also like another solution for this one it's a binary search right because every so binary search can also help us find the either the least or the max values and so for binary search you know the key point for binary search that we have to find the trend basically we have there's like uh monotonic trend right while the value is either increasing or decreasing so for this problem you know basically when the time is increasing right so when the time is increasing along the way right there will be a time right we can reach from lap from the start to the end right because you know because we know by the time the water had uh the water is deep enough to cover all the other square that obviously we can swim from one place from the top left corner to the bottom right corner right so then we can simply search we can do a binary search of the t here right binary search the t here so and we have hyper functions basically given like a fixed t there are some sorry that's my theory so given like a fixed t here we know in this grid we have some grids uh so we have some squares that are currently connected to each other which means we can swim across them right and then we can just have a helper function with a given t and can we swim from the top left corner to the bottom right corner right so that's that one actually there's a third one there's a third solution for this which is the uh the union find um so how does this union find works actually it's a similar i think it's a similar idea as the binary search basically you know we have kind of a grid here let's say we have five by five okay uh maybe i should just write four by four okay anyway i'm almost done here and each basically each cell has its own height right so what is the unifying can how the unifying union fund can help us basically if you know the uh there's a algorithm called uh minimum spin spinning tree right so basically here we are we're actually building like a minimum spinning tree uh to connect uh the source and the target by connecting some of the path by some by connecting some of the after the square right and we need to find the smallest time so what is the smallest time right so the smallest time is the time that you know uh if we basically if we sort all this kind of uh element from smallest to the biggest and if we process them one by one right from the smallest to the biggest and by the time we process you know let's say we have some uh this is zero let's say this is like um five or something like that right and then right in the middle let's see there's like this one let's see the value is seven so basically what so this what how this algorithm works is that you know we uh we're using a union find and then we sort each square by the height from the smallest to the biggest and every time when we have like uh the current uh square we try to do a union find with all its neighbors okay and after that we can check if the zero if the source and target has the same root if that's the case and then we know this value is the minimum time we're looking for right so this is like how the minimum spinning tree right basically by the time we have uh connected zero and five then the minimum spinning tree is it's completed and since we are like processing from this from the smallest from smallest uh time here then we are sure you know the current time or the current cut this current value here is the minimum time we need to build this minimum spinning tree right um yeah because yeah i think that's the basic idea here right so and of course you know when we try to uh do a union with all the four neighbors we simply cannot union all the four neighbors because we have to have like you know uh a visit a scene set here uh where when we do the union find for with all the neighbors we only a union do the union with the with a square we have already the same view before right that's i think it's obvious because you know let's say this one is 7 right so since we're processing from the smallest to the biggest let's say the neighbors has like three uh four and six this one is let's say it's ten okay so by the time we're processing this cell here square here obviously all the others these three neighbors right three six four have already been uh visited before same before that's why we can uh do the union with them right but with 10 since 10 has not been seen before we cannot do it do a union is here because obviously you know if we do a union with 10 it means that okay actually because 10 has like a bigger value here you know if union 10 if 10 has like a uh if 10 has like a connection with five here right it's the is the end here and then we're getting the wrong value here it shouldn't be seven it should be changed that right that's why you know uh obviously you know we only want to uh know the nature of the union fine is like we only union with the value we have already a union b before in this case right yeah so yeah basically if we were union of a number that we have not been seen before it means that you know the time will be increasing right which it will not be the same in this case uh cool yeah i think that's all the explanation for all three uh i think solutions you know i think we can start coding then right um so where should we start um let me think uh how about binary search i think binary search is the most uh straightforward one uh the binary search right so we have uh we have n going to be the length of grade right now we have left equal to zero and the right equals to n times two right so the upper bound is this one because it says all the values is a permutation from n to n squared minus one that's why the right boundary is this one right and then the binary search right at the template uh so wow this one is smaller than r right we have middle l plus m1 right minus elapsed divided by two and then and then we're going to have like a hover function so i'm going to cut can reach okay can reach from with the middle level water right if it can see okay so now we're looking for the smallest the minimum value right that's why you know we have to do uh r is going to be the middle and then the left house will be the uh left will be middle plot plus one right so this is a kind of template you know because you know uh see if we're looking for the minimum you know we will be doing this middle equals to r to the right and the left equals to this one if we're doing the maximum right if you are doing the maximum and basically this is as if like this you can try to picture a picture of this scenario here if we're looking for the minimum at the maximum and if this can reach so this harbor functions always return to it which means that you know now they will always return to it if this harbor functions return true it means that because the current value i mean works right so means it might be the answer so for the minimum for uh to look for the minimum values let's say with the middle is right here right that's why it means that you know the middle could be the answer right and but since we're looking for the minimum one right so which means we need to look for this side right that's why you know we set this right into the middle right so similarly if we're looking for the maximum all right so again right for the maximum if this one a half function uh return true it means that this one could be a one of the values right but for this one since we're looking for the maximum that's why we need to look uh to the right side right also including this one right that's why you know uh when we're looking for the maximum when this thing happens we have to do a left equals to middle right and then this one is going to be r dot middle minus one because for the maximum we're looking for the right side right so that's how you remember this template and oh and when you do a left equals to middle you have to do this one password right i think i've already talked about that several times okay so that's a little bit about the body of the binary search okay template and then uh what else and then we just return the left in the end right so now let's implement that hyper functions can reach right range of middle so this hardware functions here is simply like a dfs search where like you can use stack or anything you prefer to start search from the beginning from top left corner and see if we can reach the end right with this current middle basically with some constraints uh so first you know i'm going to have like this uh do a quick check if this thing if this starting point uh is greater than the middle right then we simply return false it means that we can we'll never be able to move to anywhere from the top left corner that's why we need to return false here otherwise have a stack equals to this 0.0 right and then we have a scene set and then scene dot add right and then zero and then directions so this is all tedious coding here and then do a while loop here you know wow stack current i current j equals to stack that pop right so here i'm using a stack to do the dfi search so if the ci equals to n minus 1 this cj equals to n minus 1 then we return true right we know we find it to find the path it's it can reach basically or we do it uh search from four directions okay so new i is going to be ci plus d0 right and then new j goes to c j plus d one and then if this thing is in the range of n same thing uh for the new j in the n and new i new j not in scene okay and the great right so the last one is it's the constraints we bring in with the middle with the current level of the water right basically neighbor can only be visited if the water is higher than the height then activation of this square right than the middle okay then we do a stack dot append a new i new j right oh we need another pair of parentheses here and then c dot add ui dot new j okay and then in the end return false right uh yeah that's it so let's run the code here okay accept it nice all right cool so it works um yeah so that's the that's a binary search right i mean time complexity so obviously here we have uh the range is like this so we have a log in log n square right so that's the uh the binary search and for the helper functions here it's just uh just while loop so the worst case scenarios we have to search the entire graph right that's why we have an n square log n square right so that's the binary search time complexity and so next uh let me think yeah dark stroke right so let's do dextro next i think we have already uh basically analyze a bit about dextro basically the actual the way the reason we can use dioxide is because from one node to another so from one square to another there's a cost in this case it's a time we have the weight right in case this one is it's uh it's lower than this one right i mean this is 10 let's say this is five if you want to travel you want to swing from this one to here we have to wait for five times right but if this one is 10 5 then this one is zero right then it's free okay cool so now we have a graph with the uh with the weighted edge right and we want to find the minimum cost from top left corner to the bottom right corner right so that's a perfect candidate for the dextro okay cool so for a digestion uh let me think uh we need uh distance right i mean i think it's not decent it's like i'll call it cost right so we need a basically a two dimensional array to help us to store the minimum cost right from between each between any two nodes here okay and at the beginning we have a cost at zero right so what is this one so keep in mind this one is it's not zero it's what it's a grid of zero right remember so the first one does not necessarily to be zero out uh every time if the zero let's say if there's ten here ten uh two five and one right so for example this one here so what is the answer for this it's ten right because we're standing at the top left corners but we cannot move anywhere until the time ten is equal to 10 right and by the time it is equal to 10 we can simply move to anywhere right including this one that's why at that's why the cost zero is the value of the grid zero okay and then the prior queue right for the darkest row and we have the grid of zero dot zero and then the coordinates right along with it now we also need the scene set right and then the wow well priority queue thing right then the cost dot ci current right and then we do us scene dot at uh ci dot cj right so we only add to the scene after we pop out pop-up from the product queue because we pop-up from the product queue because we pop-up from the product queue because we there could be multiple items for the same uh coordinates in this particular and we only add it whenever it's his turn to be processed which means it's he which means he has this one has the smallest cost right for the darkest row and then for d oh and we need to define this but luckily we can copy and paste we don't have to type in this and i guess we also need this n here okay so for d uh actually i'm going to copy this part you know because they're pretty much the same so we have a d here and this part is that's uh this is this one and we're going to remove this part right so now here inside so part of the dark stroke problem of the template we have a new cost the new class will be with the grade from the new place new i minus new this new one subtract the uh the grid of this one dot c j right so it seems like this one but you know there's this one is not correct first this one could be smaller than this one right so the new cost could be negative that's why first thing we need to add is the maximum between zero right so in this case we are sure that uh we'll always get a zero for negative values and there's a second thing second issue here because uh oh for example right so we have i have already give you the example here so let's say we have 10 we have one and then let's say we have five two and five okay so for example in this case right if you're only trying to do the new cost with this formula okay so at the beginning we have 10 the cost is 10 right so from 10 to 1 this is zero right and we're fine but from one to five we have five here we have four right so are we saying that you know from here to here you know if we follow this one you know the cost from here to here will be four will be 14. it's instead of 10 because the real answer is 10 instead of 14. that's why we cannot simply just do uh this one with uh with this with the previous one instead we should also do a comparison with this one for this one with the current of the cost so we're getting the maximum between two of them and that's how we can get the correct basically the previous cost all right cool so now we have a new cost and then we can do uh the dikes part right and then if this thing is smaller than that this the cost of new i and new j right and then we update and we do a heap push right probably that we have a new cost plus cost and then ui new j okay and then don't forget to update this cost nu i u j equals to this right so that's it and that's the hold actual and in the end just return the uh distance of minus one and minus one right so that's the uh that's the value right that's the answer we're looking for from the starting point to this last one cool so run the code hip or hip pop excuse me oh sorry yeah i was using distance at the beginning then i change it that's why i mistyped that okay accept it and then cool so this one dax also works right and for the time complexity for the texture and it's i think it's v plus e log v right so that's the uh that's time complexity for dextro and as when we convert it into this problem so the vertices and edges right so we have vertices are like n squared right plus how about address add is also n square okay and then we have a log of n square right so this one is gone right actually as you guys can see this one is the same as the binary search by the time complexity that okay so that's the direction for you guys and the last one uh what is that uh oh the union find right so let's do the unified with the minimum speed uh spinning tree which is also called uh cool crew score algorithm right if i'm not mistaken okay so the last one is the union find uh for the union find so to do the union find we have to create the parents right so the parents list first so because at the beginning everything is its own parents so it's going to be the range of and square right and then for the yeah for the union fine let's define the union find function here so the first one is find if x is not equal to the parent of x right so we do a terms that x equals to defined our parents of x okay and then we return the uh the parents of x that's defined and then the union right so this one is like a find with the path compression i have already talked about this part a lot of times many times i'm not going to repeat that here today so for a union we have r1 is going to be defined of x right and r2 because the find of y okay so if r1 is not equal to r2 we do appearance of r2 equals to r1 so again here i'm skipping that right the rating part right so because actually to make this finite union a real one time complexity uh ideally here when we do the units we should also compare the uh the weight for each of the spinning tree right and we'll only uh append a sorry not the spinning tree though sorry the tree for each of the reach of the root group so we only will only be appending assigning the root who has the smaller weight to the root who has a larger weight that's the way we can make this like a tree structure balanced right but here i'm just simplifying that union version a little bit okay yeah basically every time we if we really want to do that basically we have a like i think there's a score or something scroll something at the beginning we have everything it's going to be zero right and then uh this is uh and this one i think that's the how we do it right so basically if this one doesn't equal this uh basically the if the score of r1 is greater than the scores of r2 right and then we do uh we do this we do appearance of this one okay else right oh and when we do this we also need to update the scores of r1 right so this scores of r1 gonna be the increase uh going to be the sum of this right else we do it in the reverse way right so now we're assigning the presence of r1 to r2 and now the square of r2 will be increased by this right something like this yeah okay cool so that's the uh the union find template right pretty straightforward now the next thing is that we have to uh do this uh minimum spinning trade which means we have to sort this uh the coordinates by its value from the smallest to the biggest uh so i'm going to call sorted position right and then here i'm going to write a pretty long like expression here so we need to have a sort sorted so the first part is it's a list so it's a list gonna be it's a list of the uh it's a list of the coordinates so it's going to be the inj right so where does ij coming from right so it's going to be a for i in range n and then for j oh where did i go here for j in range and right so that's the uh so that's the list we're trying to sort how about the key for to sort and then we need this kind of lambda function right uh it's going to be x and the value we're looking for is the grade of this x right so the x has is a tuple here so and the first one is the i and the second one is the j right that's how we do sorting and then yeah i'm going to copy this i think we also need these two variables here now we can do a i think yeah also the scene stats i think so now we start processing the trying to do the union from the smallest uh smallest square uh the lowest square right for i and j insert it position right so every time we do this we first we add this one to the scene set right so to mark it we have okay so this position has already been visited which means we can a union with it later on okay and then i'm also going to copy this part so there's always some there's always something that never change you know for example this part uh oh yeah i think this is exactly what we need so right because we also on the oh this part now this is going to be in instead of not right because we only allow we should only union with the previously visited uh note then union uh yeah so for the union you know when whenever we have a 2d board here you know we have to since you know i like you guys as you guys seen here right so we have we basically we flattened this 2d uh grid into a 1d list here okay and then to find that location in this 1d list we can simply convert this one into a do this conversion plus j right and then new i times n plus new j that's the basically the index for these two coordinates okay cool then after this union for after union this one do the unit for this one we can simply check if the find zero right is equal to the find of n minus one if this is true it means that okay we have find a path right or we have finished building the minimum spinning tray to cannot connect the source and target and that's we can that's when we need we can simply return a grid of inj right cool i think that's it right if i run the code uh did i oh yeah okay before oh i see uh yeah let me move this one down below okay ci oh i see so this part yeah that's a that's the price you need to pay for copy and pas copy and paste right and i hope this one this time what scores oh i think this part is it ah yeah all right accept it and then submit cool so it also works right and yeah i think that's it for the uh the unified right and the time compressive for the union find right and the like i said the final union uh with this uh path compression for find and with the score or the weight with union so we can treat this both two with the operation with o1 time complexity okay and that's why so the real time complexity falls into this part right because here you know here we have this is n square right we have one square of the position right and then here's the constant four loop here and then here's o one right this is also one so basically this four oops n square so but the real uh deciding factor is this sorting part right so because we have how many elements we have here n square right all right and the sorted it's n square log n square right see it's exactly the same as the previous two solutions for the union find and yeah i think that's everything i can talk for this problem how to stop okay cool thank you for watching this video guys and stay tuned see you guys soon bye
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
152
so we are looking at this question maximum products of array and it's a variation of basically maximum sums of array so uh i won't go into detail you might have already seen so many videos but this is specifically for the edge cases the test cases which are failing generally because everyone is telling this max and men on youtube so you might have seen them uh i'll just give you an overview uh how things will happen like uh this is a variation of maximum subway okay and the only difference is uh while using cadance we knew where we need to break it for example this was our uh maximum sum array some question type 765 3408 and this was some test case and we knew that once we reaches at 34 we need to break our train or break our cycle because it got bigger and we'll start fresh from here so you must be having the idea of maximum sub sum square because it's a variation but here we do not know like where do we need to break and people are going bad because of the zero and especially negative cases like here we do not have any negative and if we have any negative we just treat them like we just add them some but while multiplying while doing product negative plays a vital role i'll just explain you why so three points you need to consider uh we need to consider this max min which everyone is telling and how to treat zeros basically this one is the key point because many people like i have seen uh this video uh sorry is explaining like this approach will work but this will not work in you know zero case is something and he just leaves you on a cliffhanger so instead uh this is a very simple solution you just need not to treat zeros i'll tell you why so uh three things which i would like to tell you max till now why we need this max till now because uh this will provide us our answer basically this is like this will be our answer we'll uh keep a count of max till now and this will just uh return answer in the end till now this plays a vital role because uh min is a kind of number which can convert any time for example if you are considering men and men is going on some minus 34 okay then it change to minus 78 and now suddenly a negative number appears for example 48 appears now when these two number will be multiplied this will result into a positive number which will be a huge number so suddenly our min changes to max that's why we are like considering our main it's a hope it's a kind of hope that someday this will convert into positive if not we are already having our max so we need not to worry that like we are just uh going with max so what we are doing how we are calculating back so i'll just tell you and this point i'll tell you in a while so for max what we are doing is uh this is my array and this is my provided array i'll just write this is my provided error okay so uh you can do this either by uh you know dp and when ddp or you can do it simple by number so i'm preferring numbers because dp is just uh creating any you know array just increases it's basically time little bit like i've checked uh it shows just a second like i've submitted uh quite a few times and whenever i'm using ra it's just giving me extra space and extra time you know basically extra time not extra space so what we are doing is we have this number uh we have this added 2 3 minus 2 4 and we are calculating our max and min in digits in number basically not in array what we'll do for this max is 2 and 2 for this and now the situation is till this we need to find maximum of an array which is ending on this number basically if you give me 3 2 3 4 8 and 6 and i'll ask you what does this 8 represent so this 8 represent maximum array ending on this 8 this can be 4 and 8 it can be 3 and 4 it can be a whole area i don't uh like i don't mind whatever it is but i just need basically uh highest value so max how we are finding max this is our uh this is our provided number we'll just multiply with the previous max basically and how we are finding min i'll just tell you uh i'll just tell you just a second here so consider this thing consider i have uh consider this array max and min i need these three things array max and min okay how i'll calculate first i have array i have i'm calculating max now i'm calculating currently max i'm having a this thing like this thing can also be greater now we need to consider for example if this thing was 13 and our product came uh six something just imagine our product came something our product came six so this 13 will be our main answer like you should be getting it three then after three what uh we need to ask max and min for these value okay how will consider that you need to multiply this with this max and with this min so you'll get your current max and min i'll tell you how multiplying this three with two will give you six multiply this three with min like two of men will give you again six so what is the max from it and what is the min from it what is the main three success what is the min so max is six and min is three basically so what will store three and will store basically uh six max six and then six sorry max six and bin three now uh for second number four minus two what we'll do just a second 4 minus 2 what will be doing same thing again 6 multiplied by like you need to find max now and you need to find min then so first uh hold this number minus 2 because array okay now max multiply this 6 by -2 this will give minus 12 multiply 6 by -2 this will give minus 12 multiply 6 by -2 this will give minus 12 multiply this minus 2 with 3 this will give minus 6 minus 12 and minus 6 now find out the max from this what is the max is minus 2 so we'll store minus 2 what is win min is minus 12 we'll store minus 12 okay we have another number which is 4 we'll do it for 4 also just a uh so thing again multiply it with this minus eight multiply with this will be minus 48 okay uh and for minimum it won't be minus 48 it will be four because whenever you will enter this min 4 minus 8 and minus 48 so my bad for max it will be 4 and for minimum it will be minus 48 so now we have these number we have this number and we need to find which number is the highest basically so 6 is the i so 6 will be the answer i know like this explanation was kind of messy you must be having an idea and like this explanation is for those who are stuck on the edge cases instead like i won't uh give to interview 30 minutes explaining this whole concept and this i just gave you an overview like how we are doing it so now we are jumping onto edge cases because uh how we are finding max is calculating by this is my array this is my current number this is my ar this is my current number on which i am working what is this max till now this is max till now this number 6 multiplied with my current number is minus 2 so this 6 is multiplied by minus 2. now another number min i told you man i need to find min till now what is meant till now minus 3 multiplied again with minus 2 multiplied again with -2 so uh this whole array again with -2 so uh this whole array again with -2 so uh this whole array this whole like expression will give me a number array max and min array like max and min all it will give me some value for example x and y now out of these value i need to find my max and my min basically arr now i need to find max and min so that's what i'm doing here and that's what i'll be using for min also one minute also same expression and nothing is saying this is just a hope this min till now multiplied with number like this lower uh thing is just a hope i hope that someday it will get multiplied with some negative value and it will convert itself into a greater uh max value basically so now let's hop on to the edge cases so edge cases many people are telling like on zero you need to change this to one you need to break it you need to do blah no we need not to do any uh nothing keep zero as zero like just keep going according to our formula this is our formula just keep going according to this uh sir also told that uh if you want to you know for 0 just change it no we need not to change it to 1 we'll just keep i'll show you how i'll take an example of this minus 2 0 and minus 1 just remember the formula array x and y max of this and min of this max of this will go at this place and men of this will go at uh this place okay sorted i will start solving i guess so i'll just solve it here for you know minus 2 0 and minus 1 okay i'll just solve it minus 2 0 and minus 1 this is my array this is my max this is my min for first value min and max will be same you know now uh what was our algorithm arr which is this array comma a number x and y how this x and y are calculated these are calculated by previous max is this thing multiply by my current array is this thing so multiply minus 0 with 0 this will give us 0 okay and how this y is created this is created by previous min multiplied by ra so previous min was this thing multiplied by array what is 0 okay it will give again zero so uh people were telling like just convert them to one because you need to move forward no need of that just keep them to zero and keep going according to your you know algorithm now on one again same thing multiply with this find out max and min so my current number is minus 1 i multiplied with previous max and previous min now i need to find max and i need to find min so what is the max out of this max is 0 what is the min out of this minus one max is zero uh min is minus one so i told you when uh after our traversing is complete we need to find maximum number from this array is zero and that's our answer basically if you'll go one if you'll go like if you change it break it no need of that then again this case uh 0 minus 20 0 again we'll do the same thing for 0 same max and min 420 what we need to do minus 20 x and y what is our x is multiplication of this and this what is our y is our multiplication of this and this multiplying them will give you 0 keep going in the same fashion 0 multiplied 0 this is multiplied this is again 0 now what we need to do we just need to find the max out of this array this can be array or this can be you know numbers if you're using number used this way we are using number used this way i'll just explain code also so our max will be zero again this is also like submitted so i'll just come back on to this uh these three what are these three this first line uh this first line i'm just initializing uh my max my min i'm just initializing my max my min and my overall max will be my answer basically so i have declared uh them with zero now i'll move further because this is indexing is like zero one two three and four now i'll move from one to four so i started on one and i'll be going till four basically less than the size now this is a very crucial part like why i'm implementing this because earlier what i was doing i was just using i was just updating my dp of max air only but a problem with that thing is you need to use tp of max here also and once i'll update my dp of max here i will never be able to use my previous value so what i have done i created this you know variable i stored my value in this variable once my dp of min is calculated i stored that value back in my dp of max and then i have just calculated if my value if my current d like if my current value is greater than what was the previous value for example uh this thing is basically i'll explain this thing is uh saving me a single loop for example i'm using array just imagine this for this max thing i'm using a array and in my array there are numbers stored like 0 for this okay i'll just go to a better example this is a test case we'll go to this example for this for example consider that i am using a array 2 6 minus 2 4 i have this array now i need to find the max of this array either i'll run a loop or i'll just use something else okay you'll run the loop you'll increase the complexity instead what we are doing whenever we are filling the values in we are just checking hand by hand like we are checking hand by end if we are getting a greater value we are adding we are like putting it in our overall max same thing is with numbers basically uh this is arrogantly now just imagine these are number two six minus two and four and imagine that they are falling from top so whenever two falls you check with your number like uh with your omax overall max my overall max was in the starting whatever number is given the starting basically this 2 my overall max was 2 so my first number will be checked if it's greater then no it's not it's like equal okay no worries keep my omax equals to 2 only now 6 will fall uh if six is greater than two yes it's greater than update my omax overall max to six now minus two will fall is minus two greater than two no i keep my o max same omax is six now four will fall four is for is four greater than my omax sorry my bad is four greater than my omax so no my omax is greater so omax will be six and i'll return this six so i'll return this so that was all for this question see you in our
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
540
Have Hello Guys Welcome Back To Back Door Sign In This Video Will See How To Find The Evening Element In Adhere This Is From List To Date Waiver Of The Match Challenge So Let's Not Look At The Problem Statement The Problems That Are Very Single Unique Element Noida To have unique element and they are not listening to know where you can find all the elements of the year subscribe for techniques will take you need to solve this problem in log in to no1 express so how can achieve This long and 10ft is a property of decreasing order so they can take benefit from its requirements for elementary and give them to give you want to search and its properties in order to solve this problem which gives no the first Indian to win the element this Present at the event will share this post with the return of the day disciple statement in this will not be you unique element in this cassette is not unique elements which was unique element and will have just returned without performing in research no this is the richest which Will Be Doing Property Paper Property This Is The Real Name Of The Element Will Exist In Ten Years And Will Always Will 98100 This Chapter Notes Withdrawal West Is The Property Of But You Can Actually Make Decisions Which Partner For Dust Properties 12 Minutes Will Not Be queries the previous element and will not be construed as a statement of a unique element property in order for property is the partition property latest from this point * this point index three ok no you point * this point index three ok no you point * this point index three ok no you found at nh-3 you have value 218 text does found at nh-3 you have value 218 text does found at nh-3 you have value 218 text does well You Have Value To Suzy Sparing Tank Property You Can See What This Point To Is Setting On Its Related Unique Element Will Not Be Present At The Center From next9news See What Is The Forest Witch Ad Twitter The Amazing More Unique And Subscribe After Partition Property And values ​​that After Partition Property And values ​​that After Partition Property And values ​​that in order to apply brain research so let us know how to apply brain research for this problem solve if you are already explained in this is the element 98100 plus minus subscribe and subscribe the Channel Please subscribe and subscribe this Video like and subscribe the Channel Okay so ifin Takkar Samudra left side dene will depart to a what was the beginning daughter for the beginning whats the year will always stand events and will end turnon isse phir width istri in between this point to solve with 000 0123 40 Video Starting From Debit The Element subscribe this Video not Is The Name Of The Question Is Very Important Subscribe Will Update This Point To The Day And I Will Remain In The Same Position 9 Meet Will Be Equal To Low Plus High - Low Be Equal To Low Plus High - Low Be Equal To Low Plus High - Low Bittu Which Will be equal to 500 media nodes page directly 4600 width union's president of mother and son will make a call to the time complexity of algorithm using subscribe to that this is the code that you can see Heroic Values Exam Start Size Minus One Which You Want to Know The Current President Should Not Be Considered Otherwise This Is Not True When Will The Current Element Fear Or Turn On The Swadeshi Central Gautam Fear Not Able To Find Anything When Will Simply Return Minus One But In This Question Sensitive Guaranteed Dubai This Limit Will Never Run For This Is Very Simple Banner Solution I Hope You Enjoy Difficulty Other Approach And Solution In Different Languages ​​Then Please Go Here In Different Languages ​​Then Please Go Here In Different Languages ​​Then Please Go Here everyone can benefit from it like share and Video subscribe our Channel 020 This Program in Videos 0
Single Element in a Sorted Array
single-element-in-a-sorted-array
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Array,Binary Search
Medium
null
792
hey hi guys today we will see the good problem 792 which is saying number of matching subsequences what does it mean so the problem is saying that we have a given a string and we have given an array of words now we have to return the total number of subsequences which are available in the given string s so how do we do that so if you can see that we are having few examples over here which is saying that we have the input s which is the string required to check how many subsequences are available in the words a b's a c d a c okay the output is 3 for the example one and why the output is three so if I can walk you through just check this a is available in this ABCD yes it is available at the first position then this ACD it is available in the string is okay a is available in the zeroth index then C is available in the second index and then D is available on the third index so this ecd is also has a subsequences of string s now we need to check AC so a then C and then e is also available in the string s is not available so the reason over here is if we walk go through this particular string this B is available in the string s only for once and how many B's are over available over here is two so we'll cancel this particular B with this B do we have any other B in the string as that can be matched and create a subsequences no so that is why the output of this particular s is equal to a b c d e and the words a b a c d and AC is three so remember one thing over here the question is given that we have to return the integer means we have to return the total number of count not we are not that we have to print the subsequences of the string okay so we over here the subsequences are three so we have printed three in the example two if we can see that we have few of the string and then we have the words so out of this four only two words can be the subsequences of this string as so we are returning the output 2. now if we write this particular code over here let's write the code and then we'll go one by one to check what exactly the logic we are trying to implement it over here to solve this question okay so first of all because we have to return the value as integer so let's take one counter and then we'll return this particular counter asset output okay now what we need to do so first what we'll try to do over here is we try to create a map and this map will holds the occurrence of this a b a c d and AC so what we exactly trying to do over here is we are trying to iterate over the words array and then we are trying to capture the number of occurrence of this words into a map okay so let's define a map which is a map of string comma integer and let's say map is equal to new and now how do we add the values in this so we'll use a simple for Loop we'll treat over or gods of Harry and we will try to put map Dot it's Dr this particular key as my key so this e will become the key of a map this BB will become the key of a map and then we'll try to capture the number of occurrence of this a in the whole word area so how do we do that so we'll say a map Dot get over default this is estia zero plus one so now if you will get confused what this get or default means so get a deferred means let's say I have this a available twice in this word array so why do we go and iterate over this a multiple times when we say this a is a subsequences of a b c d e that means the other a is also going to be the subsequences okay so rather than going and iterating over the same word again and again we'll see if my map already contained that particular string word then we'll take the counter of it and add one particular counter in the current occurrence otherwise we'll take the default value as 0 so this is the by default method provided by Java which takes the default value if you don't have the map contains key and it will take the value or it will get the value for you if you have a particular value associated with the key so that is what we have done over here so now we'll iterate toward our map and we'll try to find out what all occurrences are there so we all know how to trade over a map so map dot entry I am using I'm using a string dot integer then let's try map dot I hope you all know how to iterate over a map in Java so the string K will become entry Dot get key and when we're trying to get the value what exactly you are trying to get out over here okay so I'll tell first what I'm trying to do over here is now I'll write one more function which will iterate over my this word map and this string so we will try to match this a is available in this string or not this BB is available in the string or not so that logic we are trying to write in our this method so let's say get once count and it will take two integer sorry two string so the first string will be the key which we have stored like a is present in the map at once so first we'll pass this key over here and along with this we'll pass this particular string because we need to check the subsequences in this string itself okay so now what this function will exactly do so I'll tell you this function is exactly going to check One By One The each character availability so how does it is going to check so I'll write that while I less than str1 Dot length and JS less than thank you okay so what does this mean so when we say this particular a is available in this or not so I'll try to take this word as I counter and this word is a g counter so my I should always be less than the length of this particular word and my Gene should be always less than this particular total string okay so this is where my while loop will run and inside that what we will do we will check whether this a exist in this string or not so how do we check that so we check if I sorry if str1 dot Care at I equal to str2 Dot care correct means if this a is available over here yes I can see this is available over here so if it is available over here we'll say I plus will increment this counter to B and then we will check whether this if this particular word has some other characters then we'll have to check in the remaining string so in this case we'll see I plus or else we in every of the case we have to move one G counter why because we are checking one by one this word to this string so if first word is not available at the second or first word is available at the first position then we'll have to check the second word or we'll have to check the second character B likewise C and all so we'll go and do J plus okay and if this particular J plus is 10 then we'll check if I equal to str1 what length then we will say yes the subsequence is available otherwise the subsequences is not available or not and then on the basis of that we'll increment the counter one by one and we'll return the counter so let's run this code I hope it should work okay so there is some spelling mistake map okay so now we'll test for all the test cases available example one and two it will get successfully executed yes it gets so I'll submit this code okay so guys we have submitted this code successfully and to this question has been solved I hope you like this video thank you so much
Number of Matching Subsequences
binary-search
Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`. A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. * For example, `"ace "` is a subsequence of `"abcde "`. **Example 1:** **Input:** s = "abcde ", words = \[ "a ", "bb ", "acd ", "ace "\] **Output:** 3 **Explanation:** There are three strings in words that are a subsequence of s: "a ", "acd ", "ace ". **Example 2:** **Input:** s = "dsahjpjauf ", words = \[ "ahjpjau ", "ja ", "ahbwzgqnuk ", "tnmlanowax "\] **Output:** 2 **Constraints:** * `1 <= s.length <= 5 * 104` * `1 <= words.length <= 5000` * `1 <= words[i].length <= 50` * `s` and `words[i]` consist of only lowercase English letters.
null
Array,Binary Search
Easy
786
256
intel's problem that we are going to discuss today let me just write it here so there is a famous lead code problem okay so what is given here is there are n number of houses so i have taken only three houses which are presented in the rows and they are colored with three colors okay red green and blue here there can be more colors also so what you have to find out is like color all the houses uh with the minimum cost in such a way so that the first house or like the nth house let's say this house if it is colored with colored red then the previous house cannot be colored with red so it can be either colored with green or cloud colored with blue ok now if it is colored with green then previous one can be colored with red or blue like anything but not the same so two consecutive houses cannot be colored with the same color it means short okay so let's see the problem at first and i will remove the solution for now so there are in houses so here there are one two three houses where each house can be colored with red blue or green so these things are limited here it can be more also but here it's told that it's only three red green and blue okay now the cost of painting each house with certain color is different it's 17 to 17 which is different for house one you have to paint all the houses such that no two adjacent houses same color okay so this i already said the cost of painting each house is represented by the matrix cost so for this it is 17 for the this it is two cost of painting house one with red house one with green and house one with blue okay now cost zero yeah this they'll explain this return the minimum cost to pay and all the houses so basically this is a dp problem okay and uh how we can solve it is i'm directly going into the explanation of how we can solve it and not explaining the why it is a dp why like if a problem has to be a dp problem it's solved by dynamic programming then it has to have optimal substructure and overlapping sub problems okay if you know the basics of dp if you don't know the basics of udp you can go and watch any other videos on youtube now let's see how to solve this so at first the first step is to solve it the using dp is to find the dp stats okay so for this we have to find the dp states and the second step is to find the recurrence relation so what is the dp state it is the like definition of what is the meaning of tph dpi j and i and j are the states or i j k l whatever there can be n number of states okay so here we can tell is that dpis let's say we are solving it with the 2d dp and dpi j denotes minimum cost okay listen this very carefully so dpij let's say this is dpi j dpi one y one this is because zero based indexing zero through first okay so dp1 and then j is this column so dpij is cost took minimum cost to color like all the houses till now i houses because it is in ninth row so minimum goes to color eye houses with jade color in the eighth house so this is the ieth house last house okay jth color in the last house also you can see so if i have to choose this one right if i have to choose this one this color for the ith row then what i can't do is i can't pick the previous row with the same color so it cannot be two other than two it can be anything like it can be red or it can be blue but it cannot be green because i'm picking green here okay so this is the definition of the dp or if i say let's say i'm saying this so what can be the color of this can be red like i am saying the dpi one so we are picking red for this and then what we are saying is that the previous row cannot have red it can have either green or blue or whatever other color is there so minimum of all this or in here you will actually have the minimum of all this tp i minus 1 j okay so this is dpi 0 this is dpi 1 and this is tpi 2 same for here so we'll have the previous computed values here in the dp so at first this is if this is dpi 1 this dp this is dpi zero this dpi one and this is dp i2 so you can consider that there are many other states before also so here we have only taken three houses you can consider there are many other houses and in here when i take uh choose red color for this house then i can find the answers to the previous houses whatever there are in n number of houses let's say before this so you can find the answer for this here so what is the answer for this what is the definition of this it's that the cost of coloring all previous all houses with green being the color of the like i minus one eighth house here it is the cost of coloring all whatever houses are there before this like n number of houses last ten house last i minus one houses with blue being the last like color of the eye minus one eighth house so you can take the minimum of this one and all of this the minimum of all this is cost of coloring last time minus one houses okay so let's see what we have in the definition here stated the dp states and it is the minimum goes to color first it's the minimum cost to color minimum first i houses with jth color in the 8th house okay and recurrence relation we have to see which is dpij equal to color ij plus minimum of dpi minus 1 j minus 1 let's see if this one what is the cost to color first i houses here let's they're the first n houses or i houses with color blue for the eighth house so i am fixing this one has to be blue so if i am fixing this i just cannot take this 5 anymore because these two will be same color then so i have to take either this column so i have to take answer for this or this anything so which one will i choose i will choose the minimum because that is what i am doing in the recurrence relation so minimum of dpi minus 1 j minus and dpi minus 1 j plus 1 so i have considered that this is here there can be another color but here there is no other color so all so here i have taken only for 2 because there are only three colors so remaining only two colors are there if i don't take this color then they're remaining two colors but if there are let's say an m number of colors here so you can take all minima except this one the one on the above it we can take all minimum for all and then this value so this is dpij and the answer is minimum of all this dpis why it is the minimum of all this answer like why is this one answer this one is the answer because this one gives the value dpn minus one zero gives the value when the color is zeroth color and when the color is first color for the last row but like for the last house the color can be anything it can be the red or green or blue so when the color is red then some answer is there when it is green then some other answer is that when it is blue then some other answer is there and you have to take the minimum of all this to get the final answer okay so let's see the code a bit so here it's only for three houses so it becomes a smaller version of the problem and limited number of colors so it's not three hours i think it's n houses only but colors are three so there are only three colors but there can be more colors also the problem remains the same okay so here i have taken it directly i have not taken the jth loop because only three colors are there so for columns we can do it directly so here i have done it directly i have not taken any other loop but if there are m colors then you have to run a loop okay so at first this is the color matrix i have renamed it to a and is the number of rows number of columns so number of rows means number of houses okay so first house one house two house three there are three houses here so number of rows is three and number of colors is fixed so you can also take it as fixed but i have taken it in a variable now you have to initialize the dpi i have taken it i have taken a dp array with in rows and m columns where n is the number of houses and m is the number of so this is houses and this is colors for each house okay so how many colors are there and first row is same so first row we have taken it as the basic this one it will be the minimum okay so many more of this so imagine that if there is only one house okay if there is only one house this is the base case so what will you color it you will color it with the either red green but which is the minimum cost you will color it with that one so simple you will just take the minimum for first so we have initialized the first stress this one now from the second row for house so this tpi zero what is this is like coloring here for eighth house so here we are taking as a second house we are coloring it with zeroth color then you're taking the cost directly so you're taking the cost directly and then you're taking the minimum of all this from the other on the previous row on the previous house you can you cannot color to color it with the same color so this is the concept so you are doing it as minimum of dp of i minus one because this is a zeroth color so you can take one or two first color or the second color okay so next is your coloring with the house if you choose to color the house with one then you can take zeroth or second okay and if you choose the color choose to color it with two then you can either take it as zero or one on the previous whatever is transferred to the previous houses and you have to color it with ai to simple and then you have to return the minimum from the last row of tp so this contents what is the last row of definition last row definition disks the same definition as dp definition minimum cost to color first i houses or first n houses because this is the last row and i equal to n then it is the last row so first in houses which is the answer actually so minimum cost to file part of the answer because once it is minimum of this one so minimum cost to color first n houses with jth color on the nth house so red color on the nth house green color on the ninth house blue color on the nth house okay so if anything else contains this color then what is the minimum cost to cloud color in houses so you have to take the minimum of this one to find the final answer okay i hope this is clear and if you have any questions or can comment down and thank you for watching
Paint House
paint-house
There is a row of `n` houses, where each house can be painted one of three colors: red, blue, or green. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. The cost of painting each house with a certain color is represented by an `n x 3` cost matrix `costs`. * For example, `costs[0][0]` is the cost of painting house `0` with the color red; `costs[1][2]` is the cost of painting house 1 with color green, and so on... Return _the minimum cost to paint all houses_. **Example 1:** **Input:** costs = \[\[17,2,17\],\[16,16,5\],\[14,3,19\]\] **Output:** 10 **Explanation:** Paint house 0 into blue, paint house 1 into green, paint house 2 into blue. Minimum cost: 2 + 5 + 3 = 10. **Example 2:** **Input:** costs = \[\[7,6,2\]\] **Output:** 2 **Constraints:** * `costs.length == n` * `costs[i].length == 3` * `1 <= n <= 100` * `1 <= costs[i][j] <= 20`
null
Array,Dynamic Programming
Medium
198,213,265,276
980
Hello Hi Everyone Welcome To My Channel It's All The Best Quotes From Unique Bar 300 Basis Of Your Problem Of Uniform 125 Amount As Well As Opening Day Of Mushroom Grid Yaar Four Types Of One Representing Starting Competition Lever Starting And Ending Teri Dekhi 150 Ki Pitch Ball Subscribe our channel subscribe our channel like from starting and every subscribe on subscribe and share and subscribe that and subscribe ud in over 500 start from where one of the way can go all like this way is so this is vibrant energy approach another part we can take Start From A Group Se Ek Pan Come With Saroj Time Take This And Come Hair Sunidhi Hai Nazar Password Have Two Part To Avoid Doing So Will Solve This Problem For Tourists Visit All Dual App Phone Number Of Rose In A Number Of Columns When Will Check This one is well that this vansh will load in this claim Ujjain to our such Zee coordinator of standards and good enough to start your day starting channel subscribe number of cases on that anti sales and zero sales will condom policy of development slide Indian once riching Tours And Here And Need To Check Weather Will Cover All 20 Know That Is Not A Solution Of The Match Will Start From Vishnu Directly With Us For B.Com Final Year To Do Subscribe Us For B.Com Final Year To Do Subscribe Us For B.Com Final Year To Do Subscribe Starting From Do And Listen And Evil Returns In All Directions And Subscribe Our Channel Created Str Subscribe 0 Half Diary Marking Idiots Marking Vitamin Thorning Acid And Difficult Candle This Point To Receive New Updates Reviews And Little But It's Not Even Aware Of Recent Examples Start One Of The Likes And Subscribe Hair Growth In This Page Subscribe Have So Instant Of Taking Describe It Can Start From Hair Growth Sexual This Is This Feel VPN Emergency Come 10th Time 5 Minutes Click Subscribe Button On Side Subscribe 0 Subscribe 10 For It's A You All The Number Of Plus 98100 A Breed Of 0497 C plus newly developed reddy 90 bill account plus0 plus grade one will not dalungi a thousand hua hai ne yes starting that according advice such facilities for studies page subscribe this uniform share and subscribe the number 90 to 100 subscribe and you will regret and wide that enterr10 account first of all will change it's possible cases can't avoid it acts as an executive editor in chief in his voice mail - Dr his voice mail - Dr his voice mail - Dr that an ax has greater than or equal spoon number of roles which is the great don't like boys this time greater than Noida Greater Noida and Greater Subscribe To That XY Effective Already Visited And Obstacle That Ranbir Will Replace Return 2019 Paswan Hai If Roy Jab Scooter Great Planning And History 's Sister Will Return 's Sister Will Return 's Sister Will Return Which Hair Buffalo Mist 109 - 151 - One Because CD And Number 90 - 151 - One Because CD And Number 90 - 151 - One Because CD And Number 90 Degree 3621 Soviet Decreasing 33051 Total Processing Subscribe Start 2010 Subscribe Must Subscribe My Channel I Will Be Total Five I Hotel Talk Share Fennel According to All Four Directions of But Can Go in the Direction Over Close Sell Susan Boyle Egg Vighn All Possible Thing for This Absolutely Great And subscribe ns200 video time for love you tell a message hair let's make a moderate year 1234 subscribe now he can give thursday switch on the tribe skin total advice appointment subscribe channel and subscribe to medium first time cutting Translate Samay Decode Hai Director Shirts For This Is The Same War Little Bit Familiar With Questions And Difficulties No Problem subscribe and subscribe the Channel thanks for watching
Unique Paths III
find-the-shortest-superstring
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Array,String,Dynamic Programming,Bit Manipulation,Bitmask
Hard
null
284
hello everyone welcome today we are looking at another lead code question which is speaking iterator now this question is being asked in the february first second week of 2021 and what this question says is we are given an integrator class interface with method next and has next design an implemented picking iterator that supports a p functionality it essentially picks an element that can that will be done by the next call or to next so if you look at this question right we need to kind of come up with a class and then it has say three methods which is like peak next and has next and these three methods are supposed to kind of either uh tell the given user whoever is going to use this class uh what is my current value to that particular enumerator is what is my next value and does it contains a next value or not right now in a way whatever what i'm understanding out of this question is this is more specific to a given language because your i numerator which is being used here is very intrinsic to c sharp language now if i want to understand more what this particular language does is i have to just go and look for this link which is given to us as a hint that okay what this numerator interface is now if i change the language right say i change it to um uh let me change it to say python if you see right this is a different concept here i'm just saying that okay i have a given nums it is a list format and need to work on it right now list has its own method which is specifically to that python language if i use java if you see it is having a iterator class and that is what we are going to use in order to implement our uh solution in right now considering i'm using a c-sharp language so if i go i'm using a c-sharp language so if i go i'm using a c-sharp language so if i go and look for this i numerator right what function it contains or what method it contains so uh i have this uh i numerator class and in if i look at it contains the following properties it contains a current property which says the element which is in the current position okay kind of helps us okay what this peak has to do right peak has to do nothing but it has to just return my uh whatever my enumerator which i'm going to create dot current right now what is my numerator in numerator here uh so if someone is trying to call a class right whenever he is going to instantiate an object of it right and whenever he's going to create an object of it he has to call the internal constructor to it right so whenever i'm going to call a constructor i have to assign values whichever i'm going to use in that method right so if i take it in that manner i have to create an i enumerator internal you can say i can make it private and i can create an enumerator now what i'm trying to say here is whenever someone instantiates this class right this property of this class will now have this integrator whichever is given as an input because this is a input which is given to me now i when the moment i do this right i have my internal property or internal you can say variable which holds that value right and i here if i'm someone then if someone calls they say p get rated dot peak then i'm using that internal uh method and i'm just using the current functionality which is given to us as a property here right now what is the next one next question which is they are asking okay i need to implement the next class that means i need to implement whatever uh the next value in that iterator is so in order to see what is next let's go back to this one and see okay what is what methods i have a move next okay what does this do is it successfully advances to the next element so in a way right if you see she sharp has already given us those methods those uh properties which in a way we are trying to implement here right so in this is what i'm going to create is right i'm going to create a boolean this will always keep a flag off that okay whether i have a next variable in place or not so i have a next val flag okay i have a next variable which is present or not right so what i'll do is write what is going to be my current value that will be my enumerator dot current all right and i'll move advance to the next uh value right so i'll run my uh iterator to the next uh value so what that will be so that will be uh inimitated dot move next as we just saw in the uh in the helper link which was shown here right so let me first see whether i'll move to the next one that was move next capitals and why i'm having this one this is always going to maintain that whenever this scope uh the object's scope is given to us it always maintains whether i have a next value or not i'll return my current value and what i'll do here in the index i'll just return my next well scope which is this one okay so if you see right uh this is a medium-based question in lead this is a medium-based question in lead this is a medium-based question in lead code but it more or less like very internal to a given um language which you are using here what i have done is i have leveraged the i numerator properties and methods which are given to us i have another method which is called reset it will reset back to uh this reset hold collection to kind of to ground zero but considering i have to use only whatever i have to move to the next iterator or i have to use the current index peak is supposed to do just say what is my next element is so that was current and my next element my next method was supposed to move my cursor to the next particular value which is present or not right i created this flag just to maintain that okay do i have a next value to it right and because so that i can leverage that next flag into this particular has next method so let's run this and see what is happening okay i think the output matched let's submit it i got a wrong answer for one of the options which is this one i got one false instead of a true let's see what happened here oh so for starters right the moment i instantiated i missed one thing that okay i'll mark this too true let's run this and see if that did the trick okay i got the right results let's submit it now cool it got accepted so uh suggestion to this one is more or less like the moment you see this question and in case you didn't follow what i did in the c sharp use your preferred language go to the helper documents read through what that iterator or numerator is whichever is being leveraged in your language read through those methods and properties which you can leverage and just simply apply them in the method which will be requested here with this i'll take your leave uh thank you guys thanks a lot in case you like the explanation like description please go and do like and subscribe uh in case you have any questions please post that into the comment section see you next time thank you thanks
Peeking Iterator
peeking-iterator
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations. Implement the `PeekingIterator` class: * `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`. * `int next()` Returns the next element in the array and moves the pointer to the next element. * `boolean hasNext()` Returns `true` if there are still elements in the array. * `int peek()` Returns the next element in the array **without** moving the pointer. **Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions. **Example 1:** **Input** \[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 2, 2, 3, false\] **Explanation** PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\] peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\]. peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\]. peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\] peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\] peekingIterator.hasNext(); // return False **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 1000` * All the calls to `next` and `peek` are valid. * At most `1000` calls will be made to `next`, `hasNext`, and `peek`. **Follow up:** How would you extend your design to be generic and work with all types, not just integer?
Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code.
Array,Design,Iterator
Medium
173,251,281
1,066
hey what's up guys this is john here again so uh today uh let's take a look at this problem here number 1066 campus bike bikes number two very interesting it's not it's a good problem you know it's a media level i think it's a good medium level problem okay you know i think i have uploaded another videos regarding camper spike number one okay so this one is like a little bit of variation comparing with the other one so let's take a look okay so you're given like a campus represented like a 2d grade here they're like n workers and m bikes where like n is smaller than m which means it's guaranteeing that every worker each worker can be assigned to a bike okay and we assign one unique bike to each worker so that the sum of the manhattan distance between each worker and they're assigned by bike is minimized so this is the formula to calculate the manhattan distance between those two points basically you know with given like this n number of workers and m numbers of bikes it asks you to find the minimum sum of the workers and the bikes yeah so and as you guys can see here right so the name and the worker then the workers and bikes the constraints is only like within the tin so which means you know every time when you see like this one here like see like this small number of here i think you should always try to think of like a beat mask okay and as for this problem right so this is like another classic two list of problems basically you have a at least one here okay at least one and then you have a list two here these two and they ask you to find the uh like the minimum like values right basically to connect each one of those in into the other okay we have seen us some other similar problems but there is this one right so since the uh since the bike sorry since the worker is smaller than the bikes so which means are when we define the dp here right so the dp here and the first one is the index right so we can define the first one with index because we know with this index it means that uh between zero and the index and index minus one uh for other workers within this range they are they have already been assigned to a bike okay so that first one is index the second one is of course is the mask it's a mask of the signed bikes right so because you know since we need to check which we need to track which bike had been assigned so instead of uh instead of looping through the whole list uh we should always try to use a mask okay so that's it's much easier for us to uh basically to compare or to track like the status of each bike you know basically every time when you have a list and you want to check the list out of this of the status always try to think of a mask here okay so and yeah basically that's the dp uh dp function here and then after that it's just like the uh backtracking right the backtracking it's not a it's kind of like backtracking plus a dp so first uh let's do a top down dp here okay basically you know with this index and the mask here we can uniquely identify a current state right because at this moment right at this moment if the previously this many workers have been assigned to a bike right plus this mask then we know okay this is a unique state that's why we can use this one as a dp definition cool so um so first i'm gonna define like a hyper functions to give us the manhattan distance okay between two points so return p1 0 minus p2 0 plus abs p1 1 minus p21 okay so that's that and the next one is it our dp here dp functions here like the index and the mask okay so as always right so our template right the template is this one and if index mask if this the key is in the memorization okay then we simply return the memorizations right with this one visit the values for this key here okay and then uh let me try to finish the template first okay so that's always a good thing to finish the template so you can focus on the actual business logic there so and the template is that we will return an answer here and we will define like a answer a value here and then later on we'll just assign this answer to this like memorizations right in the end we simply return the answer okay so and regarding our problem you know regarding this for this problem since we're asked to get the minimum values here that's why we need to assign this us initialize this thing to a maximum size of value here so that later on we can get the minimum value out of it okay so and all right so that's that and now it's the time for us to see from the current state how many other like different scenarios we can go from the current scenario so basically you know and the scenario when we can go from here is that i mean based on this one here there's a current worker here right and what all the other possible bikes we can assign to this worker right and remember this mask records the signed bike status so far right so in order to do that we just need to do a range we just need to loop through all the bikes here okay and we compare the beat the bit value so that we can so it so that it can tell us if this bike has been assigned to a worker or not right so to do that uh let's search the bike uh let me define uh a length of workers maybe a length of workers here because the length of workers okay and then we also need the bikes here right so the length of bikes length of bike so that we can loop through the bike so now we have a let's do a worker here so we have worker here what grade goes to the what the current index right the workers and the index that's our current worker right and then now we just need to loop through what are all the bikes that we can assign to the current worker okay so i in range of the uh of b right that's the yeah and so we just need to check the if this ice index has been assigned right i spike has been assigned so how can we do that right we just do a if you guys still remember like how can we check that the beat value right so we do a bit shift to the left by eighth position and then we do it to end with the mask okay if this one is equal to zero then we know this spike has not been assigned to anyone okay so for those who still don't know the speed manipulations here i mean i'll briefly uh give you like uh an explanation here basically let's say for example the mask is 0 1 0. and if we want to check if this bit value is one or zero how do we check that basically we create like a um we create a like a mask value by uh by doing this one here right so basically we're creating like this one zero that's the uh that's this like the bit shift here by creating this one and we do an end with the original mask here since everything every bit ev every other bit uh value is zero so the end the final result it depends on the end for this is one here okay which means if the original mass if the bit value of the android mask is one then the total answer at the final answer is this one is zero one zero which is not equal to zero otherwise if this one equals to zero then it means the final result is zero okay that's how we use this thing to check if the current bit value is one or not okay so basically you know if this one is one right so and we can get so now it means that okay so we can assign this bike to the current worker and now we can calculate the manhattan distance between those two right so uh bike bikes uh i right so now we have a distance right distance equal to get distance of the worker and the bike okay now uh we can do our dp here right so minimum answer of the what of the dp since the bike has already been assigned right so now let's move to the next one okay and we also need to update the mask so to update the mask which means to mark this index of bike to b1 so the way we're doing it is similar like the how we check the just how we check the value here instead of end we just need to do our work here okay or the mask okay then this is how we set this one this thing to value two to one here and since you know we are like we didn't change the mask we're just directly passing like updated uh another value in here so that we don't have to do a backtracking okay cool so that's and sorry so here we return the dp right 0 and 0. so because at the beginning we have a zero bikes and we have a zero bike and zero uh worker here so yeah now the base case right always remember to set your base case so what is the base case is when the index is equal to the work to the workers which means when every worker has a bike assigned then we simply return what we do we return 0 here makes sense right because oh so sorry because here okay i forgot to add this distance here because in the end right for the last workers right so for the last worker after the last worker has been assigned to the bike and then we do another like index plus one here and then later we need to set zero because there's nothing to be assigned here which means in this case there's zero manhattan distance for us that's why we just return to zero here cool i think that's that should work yeah that's pretty much everything let's try to run the code here cool so this one accept it let's try to submit it yeah so it's a success i mean yeah i mean you know for me i mean the top down is i think it's more in it's more intuitive for me so basically it's basically we're following the uh the problem right basically at the fir first we're signing we're assigned the first the bike to the first workers and then where then we try all the possible bikes okay and then we assigned the uh we signed the second one with all the other remaining bikes the third one so on so forth until in the end we reached this one but among all those kind of combinations right we get the minimum out of the out of those all the combinations cool so that's that and okay so how about a bottom up i think and it's always a good thing to practice both the top down and bottom top the bottom up so you can get a deeper understanding of the dp okay so like i said you know for the bottom up you have to think it in a reverse way right basically you know from here onwards you're getting from the current state you need to move to the next state right but from for the bottom up with the current state you need to think backwards basically you have to think of okay how many what are the different like scenarios that can get to the current state from the previously previous state and that's the first difference and second difference is the uh how you do the for loop uh is the uh how you do the for loop here because you know and how you set up the base case because the uh you know for the top down you know uh it's almost guaranteed that the all out of all the other branches there are they're all valid uh except for the base case because it's guaranteed it's being controlled right basically you're from top down you're starting from the valid state and then you're just moving trying to explore a more valid state based on the current valid state okay but for the bottom up you know for the bottom up not every combinations are valid right and because as you guys can see here from the top down here right so we are actually there are some cases that i mean it's not valid so what are not what is other invalid cases the amount of cases are like maybe uh if we have a three workers that have been marked to assign the bikes okay and but the mask here let's say you if the workers we're at like right three here let's see the if three workers have been marked to the uh to be uh have a bike here but what if the ma the mask is zero one zero what if there's only like two ones in this mask so basically no this is an invalid state it means that okay we're saying three persons workers have been assigned to the mask so to assign to the bikes but instead on the other side we only have two bikes being assigned which is invalid state but these things will not happen in the top down because we are we're guaranteed here right basically now since we're doing a top down here the first state is always valid which is zero okay and then from here onwards right we are exploring all the valid states because we're it's guaranteeing that as you guys can see we only assign a unassigned bike to the current person so it's guaranteeing that the state uh the index and the mask they're always matched to each other okay but if you're doing for if you're doing like the top down sorry the bottom up you know since we are going to loop through all the possible other possible like combinations right and some of them are invalid states so we have to be careful about those so and okay and of course so before doing that let's so today the date and time complexity for this right so how many of our state we have here we have like uh let's say we have a the walk run bike right so basically this one is like the workers times uh 2 to the power of bike that's the total statement here that's the total uh total state here and for each of the state we will be exploring all the bikes here so it's going to be another a b here right that's the length of the bike so that's the total time complexity for this problem okay and from here actually you we can use this one to construct our bottom up dp here so which is so we have a we need these things here right so and then we have a dp so for dp so what do we need the dp the first thing is that we have two dimensions the first one is the worker second one is the 2 to the power of the b here so which means when we construct the dp here we have to do this right so the second dimension is what uh is this right so sorry of this one okay and four in range w plus one okay excuse me what happened here okay and here max size what happened here okay so the reason we are setting this one to max size is because we need to uh calculate the minimum value right so we initialize everything to the maximum okay and then now it's the okay you know what let's try to finish the our main for loop here so on the outer loop here we need to ring look through the workers right basically we have worker plus one so which means we have worker equals to the workers uh i minus one since we are doing like the one base and the worker is the zero base okay now the second loop is a mask okay as you guys can see here so and so for the top down here we are only exploring the valid uh the valid states here but here we are exploring all the masks okay in range like this right we're exploring all the masks out of the mask for the current worker and but for some of them it's not valid okay so and uh yeah same thing here right so with the current mask how can we get to the previously state right basically same thing we need to uh we need to range the bike here again okay so the way we're checking is that i mean if the current if this range if this one is it's one then it means that okay so some once okay so this one has been assigned to a bike which means the previous state is uh we so which means that previously this bike had not has not been assigned which means we can get to the current state from that state okay so this is what i'm what i mean here so basically i do the check here the k right uh and the mask is not equal to zero so this one this means that this spike been assigned has been assigned okay to a worker right to a worker okay yeah then it means what it means that okay so let's do a get the distance for this bike first right so the bikes equals to this the k similar like the top down version and we have distance equals the get distance right the worker and the bikes the bike yeah so now the only difference here is this right so we'll do a eye mask right so which means that for the current bikes and current mask so we have find a way to get to the current state right so we do a minimum of that dpi mask of what comparing to what so the previous state is that we have i minus one worker uh have been assigned to a map to a bike and uh and without this bike has not been assigned okay so how can we do that we just need to do a reverse basically we need to remove this one from the current mask so that we can uh convert it to the previously state of the mask which we uh do a uh one this k right we do a x or xor of the mask that's how we remove this one from this mask so that we can revert to a previously state here and yeah don't forget to add this distance okay and then in the end we do what we simply return we return the minimum we return a minimum of dpr minus one okay so why we do a minimum here uh because you know okay so dp minus one means that okay we have a we have all the workers to be assigned to all the bikes but the problem is that you know within all those kind of uh the possible values right of the mask here we need to find the minimum out of them because let's say we have two workers and we have 10 bikes right so dp we have dp2 here and the mask here it could be anything it could be zero one zero okay and it could be dpr two maybe uh zero one basically there are like multiple ways of assigning this the bike to these two workers that's why we have to do a minimum out of all of them okay but as you guys can see right so now all of the possible masks are valid only the ones with these two ones are valid so how do we control that you know so we control that i mean we can show that uh by setting up like a base case so the base case is this like the uh like how do we how we start from this from the top down basically the base case is we have zero workers and zero and the zero uh zero bikes so which means this is a valid state and with zero workers and zero spikes the total manhattan distance is zero okay and but to be careful here i mean you know somewhat i think it's a time thing to set to do something like this for example you know let's say what if the uh let's say the bikes is zero let's say uh sorry fc you it's it let's see the worker is equal to zero but the bike is not back is not to zero so which means we have zero workers but we have uh like five bikes i think you know it's tempting to do something like this it means that you know with uh with the mask right in like uh you know like something like this right so we do a dp like uh zero workers right zero workers and the mask two to zero similarly as we can do something like this uh with this i equal in the workers right in range of w plus one okay so these things means that okay we have uh that we have this many workers but we don't have any bikes right so something like this because you i mean you might think that you know of course you know with zero workers or zero bikes of course the manhattan the minimum distance is zero okay which is correct but you cannot do this the reason being is that you know not every state here is i actually except for the zero all the other state they are all invalid state so right because the problem is telling us each worker has to have one bike but in this case we have zero workers and we have many bikes here so which means that uh which means that not every worker can have a bike okay same thing for this one right same thing for this like the uh we have a many workers but we have zero bikes oh also means that okay there's no basically not everyone every worker can has like a bike so we which means we cannot set this two for loop here the only thing we should set is zero because with zero zeros so that you know it's guaranteeing that when we reach the last dp i here all the other cases for the mask they will all be max mike's size only the ones starting from zero will give us the correct answer okay yeah um yeah okay let's try to run the code first yeah cool so accept it submit yeah as you guys can see here right actually this bottom up is actually slower than the top down why is that like i said you know even though the time complexity is the same but the difference that you know for the uh for the top down we're only exploring the valid states okay by making sure each worker is assigned to a bike and the mask is ma the mask matches with the current workers but with the bottom up as you guys can see we have a nested for loop three level nested photo basically we're looking through all the possible states that's the difference okay and cool i think that's it for this problem yeah and thank you so much for watching this video guys stay tuned see you guys soon bye
Campus Bikes II
fixed-point
On a campus represented as a 2D grid, there are `n` workers and `m` bikes, with `n <= m`. Each worker and bike is a 2D coordinate on this grid. We assign one unique bike to each worker so that the sum of the **Manhattan distances** between each worker and their assigned bike is minimized. Return `the minimum possible sum of Manhattan distances between each worker and their assigned bike`. The **Manhattan distance** between two points `p1` and `p2` is `Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|`. **Example 1:** **Input:** workers = \[\[0,0\],\[2,1\]\], bikes = \[\[1,2\],\[3,3\]\] **Output:** 6 **Explanation:** We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6. **Example 2:** **Input:** workers = \[\[0,0\],\[1,1\],\[2,0\]\], bikes = \[\[1,0\],\[2,2\],\[2,1\]\] **Output:** 4 **Explanation:** We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4. **Example 3:** **Input:** workers = \[\[0,0\],\[1,0\],\[2,0\],\[3,0\],\[4,0\]\], bikes = \[\[0,999\],\[1,999\],\[2,999\],\[3,999\],\[4,999\]\] **Output:** 4995 **Constraints:** * `n == workers.length` * `m == bikes.length` * `1 <= n <= m <= 10` * `workers[i].length == 2` * `bikes[i].length == 2` * `0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000` * All the workers and the bikes locations are **unique**.
Loop over the array and check the first index i such A[i] == i
Array,Binary Search
Easy
null
171
To a pick hello welcome on the channel so a question we are doing 171 excel sheet column bird game first let's understand what is the question so basically this you have equal in this we title will be your screen life and you have to tell which one It will come on the number, okay, so I have given you an example to APN it like this, if your hair is fine then it will be on your worst position, it is on the middle second, if you do it like this, it is 2016, then it is basic. Okay, then egg is 2728, so today we will start understanding like how will we approach, how will be the solution, okay then support, there is only one slot, now there is one slot, so what can happen to it, if it is Muslim acid, it is B, so what will be the position of it. The answer will be that if you do it, then two slots have been given back, so if you use the seal here, then what can happen here, you can teach horoscope together, you can teach horoscope with your wife, then it is Hi Guys and after that came Think here, you can keep it here D, then you will calculate from the sun, what time together, 226, okay, Twenty-20 with one should be 226, okay, Twenty-20 with one should be 226, okay, Twenty-20 with one should be completed, that means one calculation, you have kept anything, they must have kept it together, still how many together. Will be completed, still with between 6 will be completed, okay, so it means that this brain here twice, we have deleted the food, then if we support, there are 3 slots here, okay, there are 3 slots here, so here You understand, it is from the seat, okay, so its simple meaning is that there is one year here, 2016 and feet C will come, then whatever happens after that, it will be with agriculture, then here 126 and then Whatever happens here, it will get that much solution, so once you start the pattern here, then what is there, here we will multiply it, what will be its position, we will apply happiness and prosperity here with the power of 80 of these 226. This position will be 2060 Power Descendant and if we understand this and apply it, then what will happen here from the zero next to 16, then 16506 Power One and here 2016, you are crazy, you are fine, then the pattern has become, then now I understand. What we have to do is that we have to approach it from behind. By back we mean that we will travel this system from behind and while increasing from 2060 power, we will apply the real age from zero till here till Yoga and Management. From this position, what we have to do is What will we do for the very Ballia account, we gave it our own that red button wheat 20680 and English results and come to do more anti virus and started taking it, the reverse will not work, the campaign had said column that National Eye Technical 05 - Will that National Eye Technical 05 - Will that National Eye Technical 05 - Will you not do Scientific Plus app and tell me that Cat came - ah that Cat came - ah that Cat came - ah why Candy Crush OnePlus One on the phone because if it will go to 20 G but if it is one then the position is different, right in 282 we will do that account, now it has to be increased in Uble 2016 So Tips * Scanner increased what to do So Tips * Scanner increased what to do So Tips * Scanner increased what to do this Khurram please remind please return race let's take the soil anywhere in the court but it is okay that you take York whether he has given this range answer is right or wrong Hello Hi, it is correct on this also, it is okay, so it seems straight, this is what is coming, let's submit it, ok, so it is basic simple, I am asking you a question, it is a Taiji question, similar to the list board's Delhi Changes questions are coming. Will keep and announcement of B-2 will keep coming. Will keep and announcement of B-2 will keep coming. Will keep and announcement of B-2 will keep coming so if you like then like share subscribe ok by the jhal
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
314
hello guys they will try to solve the binary vertical order traversal profit and see the problem statement given by me tree return the vertical altered force all his notes value from top to bottom and column by : if two notes are bottom and column by : if two notes are bottom and column by : if two notes are in the same row and a colander older should be from left to right okay how to solve this problem let's see the example in this case you should have returned the 9 and then 3 15 and then 27 how to get this answer say you are at the root and the you can see this root know that as there 0 in there you can see the three at the dealer there and is left a child should be negative 1 because it's on the left of it so the horizontal distance should be negative 1 and this 20 should be positive 1 and okay we go down and we are at 20 now at the same idea now the 15 is positive 1 minus 1 so it's the same it's a 0 now so it's in the same vertical line with the 3 and how about a 7 because their 20 is part of one so the favor is part of 2 because we plus 1 on the 20 so this is the idea we have to calculate a horizontal distance of each node and then put them together the same horizontal distance in the same group then he will be the answer so as I said we needed to get her on this and of each node so an easy way a simple way data I made another class that I will have a tree node and either will also have a horizontal distance and the contractor know to route this will be a running distance okay so I will use hash map why because if I get the hurom distance I can simply put it into the list the same her own systems list so there will make this in constant time so I will use hash map okay but I still need a first me that this result in result list okay each case root if root equal to not simply return this then we will do PFS why because when we do BFS we can get the horizontal distance of the current route and this left or right route if I can make it is easier so you know Q new linked list okay our first offer this route not into it is hurry on to this and will be 0 okay and the way to the typical BFS why queue is not empty okay now the curve in co2 q po okay do not forget we need a inter minimum horizontal distance first we initialize to integer max value and the max distance will be integer minimum value why because the hashmap do not have older and in the last so we should a return the list in order so instead we just needed who saved me my Harlem dissonant Maxima around the distance okay so it gets the current node um map but oh I haven't map integer the key is the horizontal distance and other value is the root value okay if absent if this very untraditional easy so we need a new array list and then I will add that get to this her long distance and add other was Kurt root Davao okay have them into it and there if Kirk Rueter karuta top left not naughty what you now offer them in tutor you know you see the root and the horizontal distance will be her own distance minus one laughter so is minus one is the Curt root all right not equal to not offer all right what okay mmm so in this case we have um choice every node and Indiana we should get our answer we should do that Oh do not forget update a mini Maryland is and will be mess minimum mehar long distance and the current around Oh distance the same max along this'll be mass max around is anaconda around the distance okay in the end for in - I go to minimum a long end for in - I go to minimum a long end for in - I go to minimum a long distance I left I called em max her long horizontal distance I trust us I will add the into the final result yet I so finally returned risk mmm I think it's right okay thank you for watching
Binary Tree Vertical Order Traversal
binary-tree-vertical-order-traversal
Given the `root` of a binary tree, return _**the vertical order traversal** of its nodes' values_. (i.e., from top to bottom, column by column). If two nodes are in the same row and column, the order should be from **left to right**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Example 2:** **Input:** root = \[3,9,8,4,0,1,7\] **Output:** \[\[4\],\[9\],\[3,0,1\],\[8\],\[7\]\] **Example 3:** **Input:** root = \[3,9,8,4,0,1,7,null,null,null,2,5\] **Output:** \[\[4\],\[9,5\],\[3,0,1\],\[8,2\],\[7\]\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
102
887
Hello Hi Ap Me Zu Lakshan To The Super Hero Problem And Dasha Problem And The Video then subscribe to the Page if you liked The Video then subscribe to Ya Baby When You Have A Center Of You To Find The Number Of Birth youtu.be that I will tell you what Mamu sa flat you checked and difficult video subscribe the channel and that and your eclipse horoscope one and super absolutely minimum number of requests definitely subscribe loot-loot subscribe Video subscribe to this meeting And MS Word Yuktiyukt Dash Loot Jaane To E Superheroine Phase Vacuya Research Loot Liya Subscribe If Login Middle Video Subscribe Quick Iodine Us Login Upvas Na Subscribe Number Off Number One Side Subscribe And Half Fuel Subscribe From This Do Quite Like SUV Increase The Number Of Mode Number One To Do Subscribe Button More Folic Acid Number To The Total Visits A Confusing Conditioner Kangar Hi A Yeh Problem Ko Subscribe Now To CPI(M) Building subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe A Pressure Horn Rate And Account Sirvi The Best All The Subscribe My Channel Do n't forget to subscribe [ n't forget to subscribe [ n't forget to subscribe Bluetooth And Boys And Subscribe The Channel Please subscribe and subscribe the ki mumkin forward No End Different Problems Mantra subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page Om Namo Been Followed But Let's Check Officer Sunil You Are You Decide Subscribe Now Different Approach If you must subscribe to this channel then Ishwar Kilometer Hai Water Digest Award Dhoop Ignore Ad Tak Hum Idli Subscribe My Channel Subscribe To Hai IDBI Temple Dedicated To Leave When You Will Not Give Up At Least One Item Number 19 Different Oil Co Hai And Mode Ki And K X The Fifth Odi At some of lotus that is the meaning of hello how you decided to tooth on more do 102.1 decree hello how you decided to tooth on more do 102.1 decree from districts 512 hello hi me eggs tod not so young boys are used for your exams from sacha floor set up the withering mode Prohibition Are You Can Work Order Follow Radhe-Radhe subscribe And subscribe The Amazing spider-man Idi Subscribe spider-man Idi Subscribe spider-man Idi Subscribe Yes this indicates these notes are printed subscribe and subscribe the Video then subscribe to the Page Mein Latk Controller Rakesh Vriddhi one rate like this That Aapne Side Sona Baby 19 2010 A Timeless Twitter - Unmukt S Huey Porn Pics And Subscribe To That Aapke Smartphone Tuition Middle Man Video Best All The I Late European From This And Didn't Know What Is The Meaning Of This is the time - Vanchit Yovan Plus This is the time - Vanchit Yovan Plus This is the time - Vanchit Yovan Plus subscribe number road to Lord Mahavir and Shravan one hundred rupees 119 and where it definitely smells youth debit the loot your left my needs and guess what is the maximum number Off till now subscribe to the Page if you liked The Video then Love You Can Maa Hai - One Common Adhed Ko Hain Love You Can Maa Hai - One Common Adhed Ko Hain Love You Can Maa Hai - One Common Adhed Ko Hain Yes To Jab Road That Even The Great Venerable To My Channel Ko Subscribe And Subscribe Video Ko Hue Loot Not Been Gone To Cash To lekar Kunwar Ajay ko aap soe great you all activities in rituals CPI (M) CPI (M) CPI (M) came 20 minutes ago a Gautam festival subscribe kare subscribe to the Page if you liked The Video then subscribe to the Page that till now friends and have been marked a break in These questions on which dancer Ruby PM David Cameron plus one luck to all the best subscribe to this is the increase one break policy fixed schedule subscribe to the page come now Jai Hind Sacrifice - Who's First Jai Hind Sacrifice - Who's First Jai Hind Sacrifice - Who's First International What is the number Of the subscribe this Video is not fixed 2019 Trick will be in a position to be a great desire will give you soe game modes and one item minimum Video then subscribe to the Page that such mental updates will be on Up solution tasty undhiyo ke declared in adhik na dharma loot increasing number of subscribe to subscribe contact number off do tag increasing in cases in the mid jabir wa peeth subscribe to aur dasha tay and addictive subscribe to a pre-destined amazon is video Ko a pre-destined amazon is video Ko a pre-destined amazon is video Ko and Ashok Ji Hai and Shola Delhi-Noida Ashtamesh Videos Hai and Shola Delhi-Noida Ashtamesh Videos Hai and Shola Delhi-Noida Ashtamesh Videos Do Subscribe Must Subscribe
Super Egg Drop
minimum-cost-to-hire-k-workers
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, you may take an unbroken egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. **Example 1:** **Input:** k = 1, n = 2 **Output:** 2 **Explanation:** Drop the egg from floor 1. If it breaks, we know that f = 0. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. If it does not break, then we know f = 2. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. **Example 2:** **Input:** k = 2, n = 6 **Output:** 3 **Example 3:** **Input:** k = 3, n = 14 **Output:** 4 **Constraints:** * `1 <= k <= 100` * `1 <= n <= 104`
null
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
null
5
hello guys welcome to another video in the series of coding today we are going to do the problem which is called longest palindromic substring so given a string s you have to return the longest palindromic substring in s let's try to take an example to understand so we are given b a d we have to return which is the longest sub string that is a palindrome you have to return the longest palindrome in this let's take an example first of all what is a palindrome means if you read from the starting or from the end means you read either from right to left or left to right it's going to read the same for example this is a palindrome because b a b if you read this way also it's b a b if you read in this way also it is b a b right so that's why this is a palindrome now in this string the maximum possible is of length three because we can see that b a b is a palindrome there is no other substring which is of longer length that is a palindrome in this because see if you take b a d ah from the starting it will be b a b i d but you if you take from right to left it will be d a b a d and both are not same and so on right so in this uh you can take any of the answers for example babs answer abs answer but everything is of length three only maximum okay let's take another example let's say we have let's take a simpler string a b a now in this you can see that there are many palindromes the character a alone is a palindrome the characters a is also a palindrome uh you can see aba is also a palindrome but the longest one is of length phi and it's going to be this a b a if you read from the beginning it's a b a if you read from this side also it's going to be a b a and both are same that's right it's a polynomial now if we think of the brute force approach to solve this problem we are going to first of all list down all the possible substrings and if you do that the time complexity will be of n square and then we will again i need to check whether each substring is a palindrome or not so we will keep two pointers start and end and one by one we'll keep comparing the characters we'll keep moving the pointers and so on right so again it will be o of n cube time complexity to check whether each substring is a palindrome or not to list the substrings it will be of n square because they are going to be these many substrings uh and then um to find out whether it's a palindrome or not the time complexity again will be multiplied by n so then it will be of n cube but we don't want this right we want to uh reduce the time complexity so the hint that they have given us see they have given us a very beautiful hint to solve this problem if you see the hint how can we reuse a previously computed palindrome to compute a larger parallelogram okay now it is much better right let's say that i want to check whether the entire string a b a is a palindrome or not okay now if i want to check this entire string right what i'm going to do i'm going to keep one pointer at the start one pointer at the end now a is equal to a so i will move my pointers okay so now my pointer comes here at this position again a is equal to a so i will move my pointers now i reach in the middle and since this is a palindrome because all the characters are equal from both the sides they are going to be same okay so this is where we can save some time complexity we can just check if the last characters are equal or not right so i'm just going to check the last character a is equal to a okay this is correct now the for the inner palindrome we can already store the answer and we can use this answer let's say i've already computed whether aba is a palindrome if aba is already a palindrome and i know that right let's say this is a palindrome i have already completed and i have stored it then i can just check the first and the last characters if they are equal and the inner string is a palindrome let's say a is equal to a the first character and the last character are equal and the inner string in a string in this case is a b a is a palindrome which i have already computed then i need not do o of n complexity to check whether it's a palindrome i can just do it in over one complexity i can just take the first and last characters so i need to already compute the inner string so how are we going to do that now it's become very simple so let's start from the very beginning so for the inner palindromes i will already have to compute right let's say this is i this is j okay so i plus 1 and j minus 1 whether this is a palindrome or not i should have already computed right so let's say i have a matrix and i am checking if i want to find out the number of characters uh dp of ij is a palindrome or not if it is a palindrome how many characters how many how much length does it have right uh to be a palindrome so let's say my i is equal to 0 and j is equal to 4 right so i'm checking whether dp of 0 4 is a palindrome or not if it is a palindrome the length of this will be stored as the answer so i will just give a condition check if s of i s is the string if s of i is equal to s of j right that means here i am just checking whether a is equal to a right so this is equal to this so i can just store whatever value is there in my dp of i plus 1 and j minus 1 right so inner string the inner string will start from here and it will end from here plus 2 y 2 because i am adding two new characters right i am adding the first and the last character so dp of i plus one j minus one should already store three okay because the this a b a is of length three right so if this is of length three and i am adding two new characters to my parent room dp of 0 4 will be equal to 5 it's a palindrome of length phi obviously right the length of this string is 5 so this is a simple logic to solve this problem now how can we solve this problem so let us start from the very beginning we will have i and j values corresponding to where the string is starting so my i will correspond to where the substring is starting and my j is corresponding to where the substring is ending okay so let us build the matrix okay so this is a b a this is my i means where the string is starting this is my j where the string is ending okay now let me quickly try to do one thing draw lines here so that it is a little bit neater and we can easily fill the values okay so we have to fill the values here so let us start from the very beginning okay let me also write the i and j values 0 1 2 3 4 okay similarly let me write the j values here this is 0 this is 1 this is 2 this is 3 this is 4 okay so let us start so we are going to start from the very first thing so this a is equal to this i is equal to 0 and j is also equal to 0 that means our string is starting at a and ending it let me write rewrite the string here so that it's much more clearer first we are at i equal to 0 j equal to 0 because you can see the inj values here that means our substring is starting at a and ending at a right so it is just one single character one now for all the single characters are always palindrome right you read from the beginning or you read from the end it's always palindrome so single characters are palindromes of length one right so for all the single characters i can just store one so zero comma zero is one now let's say my i was here and j was here right so this i is equal to one j is equal to one this is also a single character so here also i can fill one okay let's say i move my i to two and j to two this b is also a single character it is also palindrome so whenever we have single characters they are definitely palindromes of length one so similarly i can just fill one in all the diagonal values because let's say starting at 2 ending at 2 the string starting at 3 ending at 3 it is just single character right so i can just fill 1 okay now let's fill the next values now you can note that we are filling values diagonally ok so this is another beautiful problem where we fill values diagonally okay let's continue it will be much more clearer when we discuss the entire problem now let us try to fill this box right so what does this box correspond to 0 comma 1 so i is at 0 j is at 1 right that means we are starting from here and we are ending here that means this substring we are thinking what to fill in this substring now for this for palindromes of length 2 it is very easy right you can just check if the first and last characters are equal then it is a palindrome of length two if the first and last characters are not equal then it is of length zero that's it as simple as that okay so for panel rooms of length two also it's very easy you can just check you can easily just check if the characters are equal or not in this case a is equal to a right so the string a is a palindrome so i can just fill two okay now let's go forward next box i have to fill this box a is starting at in this box a starting at 1 b is ending at 2 that means here uh i is starting at 1 and j is at 2 that means this string now a is not equal to b right that means this is not a palindrome so here i can just fill 0 very simple okay similarly let's go here 2 3 right so this is your i this is your j so i'm just checking this string now b does not equal to a that means it's not a palindrome so the length of palindrome is 0 because it's not even a palindrome as simple as that so we can just fill 0 here similarly let's check here for this box this character is a this character is also a so now again this is your i this is your j both are a right a is equal to a that means it's a palindrome and it's a palindrome of length two okay so we can fill two here and we can continue our iterations now let's try to fill this box okay so this is starting at zero and this is going to end at 2 so this is starting 0 so this is starting at the character a and this is ending at this character b right so this is your i starting at 0 this is your j ending at 2 okay so we are going to check whether this string is a panel now it's not a paladin you can just check the first and last characters you need not do anything just check first character is a right here you can see it is a and here this is b right a does not equal to b so this cannot be a palindrome so we can just fill 0 here no need to just think anything if characters are not matching if the outer characters are itself not matching how can it be a palindrome that's it simply just write zero now we'll try to do it a bit more quickly okay because we want to fill out the values and write the code also now let's consider this and this you can see that here in this case i is at 1 and j is at 3 sorry we have to yes it's correct i is at 1 and j is equal to 3 right we are filling this box so in this case you are checking whether the string a b a is a parallel room or not so you are just checking the first and last character just check if a is equal to a it is equal right so now we will check whether the inner string is a parallel how can we check the inner string we have to just check this diagonal why this diagonal because let's see this is i this is j so the what is the inner box i plus 1 j minus 1 right so we are just going to check if the string starting at i plus 1 and ending at j minus 1 is a palindrome or not so if this is i and this is j i plus 1 comma j minus 1 will be equal to this box right so you have to just check the box on the diagonal below so if it is a palindrome then we can just get its length right so this is having a length of one now these two characters are matching that means we have got two characters and the inner box is a panel of length one so we can fill two plus one equal to three in this box okay as simple as that so we can just fill three here why are we filling three because we have to check whether this is a palindrome now the inner string is a palindrome of length one and we have got two extra characters so two plus one is equal to three so that is why it is a panel of length three okay now let's go to the next box we are starting here and we are ending here so i is starting at two j is ending at four right so we are checking whether b a is a pallet room now b is not equal to a right b is not equal to a so how can it be a panel room we can just fill 0 and move forward okay that's it let's just fill 0 and go forward now let's we have to fill this box so this box is starting at a equal to 0 ending at a equal to 3 so this is your i this is your j we are checking whether this is a palindrome or not okay so first let's compare the inner characters now if we see that if we see the sorry outer characters a is equal to a right so obviously this is awesome for us but when we check the inner string right when we check i plus 1 j minus 1 which is in a string when we check here we see it is not a palindrome so the inner string is not a palindrome a b is not a palindrome right a b is not a palindrome the inner string is not a palindrome we can see we have already checked that it is having a value of zero inner string is not a palindrome even if outer characters are same this cannot be a palindrome a aba is not a palindrome right so in this case the answer will still be zero because if the inner string is not a palindrome if it if the answer is zero here it cannot be a palindrome okay now let's continue to this box so what is this box it is starting at i 1 and it is ending at j 4 right so we are checking if a b a is a palindrome ok again a is equal to a awesome but a is equal to a this is great but if we check for i plus 1 j minus 1 which is equal to this box this is also 0 so ba is not a palindrome right so even if the characters are equal if inside the string is not a palindrome that means that this has to be 0 there is no other option but this has to be zero right so both of these are zero now let's come to the last box it is starting at a equal to zero ending at a equal to four so this is your i this is your j i is zero j is equal to four now uh a is equal to a right outer strings is a paladin so we have to just check the inner string so you will check i plus 1 j minus 1 this entire inner string if it is a parallelogram of length 3. so inner string is a palindrome of length 3 you have got 2 extra characters out of character so 2 plus 3 is equal to 5 so this is a panel room of length 5 that's it simple so we can fill 5 here and we can just write 5 here and we can continue and return 5 is our answer so this is our entire logic now let's move forward to coding this okay so let's start coding this let me just quickly make it full screen so that's a little bit better okay so let's start so we have to build this matrix that we just discussed you can call it anything you like i am just calling it dp and let me initially take the size of the string so let's say the length of the string is equal to n so this is a matrix that is going to be built of n cross n size so let me just give the size in the matrix initially i am going to fill all the values as zero okay now let me start hydrating with this matrix we will also take this example that we just discussed a b a okay we have this current string so let us start iterating current okay by the way we are going to iterate diagonally right so let's quickly discuss how to iterate diagonally so first we are going to start with 0 then we are going to go to 1 then 2 i am writing the coordinates over which we are iterating right so we have to iterate in this manner first we have to start from the cell with coordinate 0 and go up to 4 right in the next iteration we are iterating this side diagonally so let me write the coordinates so when we iterate this side diagonally we are going to start at 0 1 and we are going to continue our iterations from 0 1 we are going to go to 1 2 then we are going to go to 2 3 then we are going to go to 3 4 right and then when we iterate in the third row we are starting at 0 2 and increasing i j so it becomes 1 3 then it becomes 2 4 and so on right so what are we doing is we are starting where are the starting position first we are going to start iterating from 0 this is the first coordinate after that okay this is our i this is j okay in the next loop when we start our iteration we are going to start from 0 1 so then this is how your i this is your j starting i n j then you are going to start from 0 to this is your starting i this is your starting j okay this is for the outer loop this is what we are going to start with our i j and then each time you are just increasing i by 1 and j by 1 in the inner loop you are just increasing i by 1 and j by 1 every time right you are just doing in the inner loop you are just always doing i plus 1 j plus 1 so when you are starting the difference between i and j is equal to 0 when you increase the difference and make the difference between i and j s 1 then you increase the difference make the difference between i and j s 2. so we can use this difference variable in the outer loop initially the difference between your i and j is equal to 0 and then the difference goes on difference less than n right so in our case in the string if n is equal to 5 the difference goes from 0 to 4 okay and then we can just increase our difference so then we can take a inner loop inner so then we can take a inner loop is going to start with i equal to 0 and what will be your j is going to be simply i plus difference right so because the difference between i and j is defined as j sorry the difference between i and j is defined as difference so because of which this is going to be your condition right now we can just move forward till when can we go for when do we stop always we are stopping when the j value becomes equal to 4 right so this is your stopping condition for the hydration j value less than n is your stopping condition now you can just increment i increment j that's it this is a simple inner loop okay now uh very simple logic if i is equal to j i sorry i is equal to j that means we are iterating in the first diagonal right when i is equal to j you are just iterating in the very first diagonal so for the very first diagonal the values are all going to be one it's very simple dp of ij is just one because you have single character as only length one right okay now we can go to else let's say if difference is equal to 1 in this case you are hydrating over the second it has become very messy let me do one thing let me erase this we have understood how to declare the variables okay let me try to make it a little bit less messy okay let me erase all this okay so we have finished the first diagonal we made all the values equal to one okay very simple now let's go to the second diagonal some values are going to be two which values if the strings if the starting and end positions right if your i and j characters are equal then it's going to be 2 otherwise it's going to be 0 very simple as that so we can just check if s of i is equal to s of j in that case okay so dp of i j i can just give is equal to if s of i is equal to s of j then it's going to be two otherwise it's going to be zero okay for the second diagonal also it's very easy now comes from the third diagonal onwards what do you have to do now also it's very simple let's take the next case from the third diagonal onwards you are going to just check for example let's consider this case this is starting at a this is ending at a here right your i is equal to 1 and your j is equal to 3 in this box so you are just checking if these characters are equal you are getting the value of the inner string okay so what we did we saw the left diagonal this is a palindrome of length one b is a palindrome of length one so to b we are adding two characters which we just found i and j so two plus one is equal to 3 that's why we fill 3 in that box so very simple again just check if s of i is equal to s of j right and the inner diagonal should also be a palindrome so how will you check dp of i plus 1 j minus 1 should be greater than 0 right it should be greater than 0 if it is equal to 0 that means it's not a palindrome so the outer character should be equal and the inner string should also be not equal to zero means this should also be a palindrome inner string is a palindrome of length greater than zero and outer strings are also outer characters are also equal if it is so then in that case you can just make dp of ij equal to d p of i plus 1 j minus 1 plus 2 okay that's it as simple as that otherwise d p of i j will just be 0 right so that's it these are the three conditions very simple conditions now we can just check for the answer every time right so here if this condition is equal to true right now after this we can give after these three conditions we can just store our answer we need to return the string that is a panel rule in our case we have to return this a b a string as our answer so let me declare string answer okay and let me also take one um variable that is going to store the maximum length of the palindrome that we got till now initially it is 0 right initially it is 0. now let me check if the palindrome that we have got right now right so if dp of ij is not equal to 0 if it is a non-zero value not equal to 0 if it is a non-zero value not equal to 0 if it is a non-zero value that means this is the palindrome right so the string starting at i and ending at j is a paladin okay so now i can check if now what is going to be the length of this string the length of the string is equal to j minus i plus 1 because it is starting at i and ending at j let me take one example let's say you have the simple string aba right now it's a palindrome where is it starting at it's starting at the index 0 it is ending at the index 2 and what is the length of this is equal to 2 minus 0 plus 1 so the length of the string is going to be equal to 3 how are you getting the length j minus i plus 1 right so that is how you are getting the length j minus i plus 1 is going to give you the length right so this is going to be the length of us of a string so i am going to check if the length of the string that i have got currently is greater than the max length that i already have because i have to return the maximum length string as my answer right then in that case i can change the max length to be equal to j minus i plus 1 right and i can also change my answer what is going to be my answer is going to be the string that is starting at the index i and it is of this much length so when you use the sub str function the first parameter is the index where the string is starting which is i and the second parameter is the length right it is the length so i can also give max length here right it is the length of the string that's it and finally after all this you can just return answer okay that's it this is a simple code let me just slide it this is the entire code let's run and see if it's going to work it is working let me just submit and see if it's working for all the given test cases so it's working and thank you for being patient and listening
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647