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 |
---|---|---|---|---|---|---|---|---|
279 | hey guys welcome to a new video in today's video we're going to look at lead code problem and the problem's name is perfect squares so in this question we given an integer n and we have to return the least number of perfect squares that are needed to sum up to n by definition a perfect square is an integer that is a square of an integer in other words it is the product of some integer with itself so this is a point which can be implemented using Code so for example 1 1496 perfect squares because if you multiply a number with itself you get these respective numbers for example if you multiply 1 into 1 you get uh 1 you get four if you multiply 2 into 2 you get 9 if you multiply 3 into 3 you get 16 if you multiply 4 into 4 and so on 25 36 49 are perfect squares whereas for example 3 and 11 are not perfect squares because there is no number which when multiplied with itself gives three or 11 so let's take these examples and see how we can form this question so let's take the first example n is equal to 12 and here we have to observe that we need to get the least number of perfect squares that sum up to n and what are the perfect squares starts from 1 4 9 16 25 49 and so on so here you can see that 1 is a perfect square and we know you can build any number for example 12 using 12 1es so 12 into 1 is equal to 1 so this means 12 1es if you add them up is equal to 12 so there are 12 1es here so 12 will be the maximum number but we need to find the minimum number so we have to pick the perfect squares so for 12 you can pick 1 you can pick 4 because it is less than 12 you can pick 9 because it is less than 12 and you cannot pick 16 because if you pick 16 it is already greater than n so you can't add this with something to make it to 12 so we have to pick numbers which are less than n so for 12 you can pick 12 ones or you can pick 4 + 4 + 4 which is equal to 12 can pick 4 + 4 + 4 which is equal to 12 can pick 4 + 4 + 4 which is equal to 12 and here the number of perfect squares you used were three so 3 is the output which is the optimal answer or you can also make 12 with 4 1es and 2 fours this is also equal to 12 and how many perfect squares you used you use six but we already found our minimum answer which is three so three will be your output so what are you doing here you're picking all the perfect squares less than n and here n is 12 so these are the three options you can use and in every call you are checking if you can use this or if you can use this so we keep on doing the same steps so this is a good example of a recursive approach so let's build the recursive tree so here if you pick we picked one number and we make the recursive call of 12 minus 1 we picked one so this one represents the number of perfect squares we picked until now we have to reduce this value from our 12 so that we can apply recursive call on this 1 is already there so we add + 1 and do F of already there so we add + 1 and do F of already there so we add + 1 and do F of 11 - 1 and here again we do 1 + 1 + 1 + 11 - 1 and here again we do 1 + 1 + 1 + 11 - 1 and here again we do 1 + 1 + 1 + f of 10 - 1 and so on this tree you'll f of 10 - 1 and so on this tree you'll f of 10 - 1 and so on this tree you'll get 11 + f of 1 - 1 and F of 1 - 1 is f get 11 + f of 1 - 1 and F of 1 - 1 is f get 11 + f of 1 - 1 and F of 1 - 1 is f of 0 and once f is equal to 0 we return zero so this is 1 so finally you get 11 + 1 which is equal to 12 like I said so + 1 which is equal to 12 like I said so + 1 which is equal to 12 like I said so 12 is the answer for this tree so we have to take minimum of all that so minimum is initially 2^ 31 minus 1 that minimum is initially 2^ 31 minus 1 that minimum is initially 2^ 31 minus 1 that is the maximum possible value and you compare it with this we check if this value is less than this yes so Min will be updated to 12 and similarly here if you picked one we picked one four and we have to subtract 12 - 4 and similarly have to subtract 12 - 4 and similarly have to subtract 12 - 4 and similarly here if we picked 9 so you have to subtract 12 - 9 and for this let's build subtract 12 - 9 and for this let's build subtract 12 - 9 and for this let's build the tree again so 1 + 1 + f of 8 - 4 and the tree again so 1 + 1 + f of 8 - 4 and the tree again so 1 + 1 + f of 8 - 4 and so on so you make one call here and 1 + so on so you make one call here and 1 + so on so you make one call here and 1 + 1 + 1 + f of 4 - 4 you get zero so this 1 + 1 + f of 4 - 4 you get zero so this 1 + 1 + f of 4 - 4 you get zero so this will return zero so you get three from here and this three will be our optimal answer so this is the recursive call you keep on making inside the helper function and this recursive function there'll be many repeated calls for example and here somewhere there'll be F of4 and here also if you see this is F of4 this F of4 value we already calculated it but here again you're making recursive call and calculating it so to avoid these recursive calls you can Implement memorization so you store this value somewhere inside a 1D DPR because the only parameter which is going to change inside a recursive call is the value of n so you create a DP of size n and you store this value next time you want F of 4 this value you can directly get from this memo array instead of making F of4 call so this process is called memorization I'll show you during code how this is done now let's take a look at the code coming to the function given to us this is the function name and this is the input and given as input and we have to return an integer as an output representing the number of perfect squares that sum up to n so let's start off by creating a helper function which is a recursive function so this will return an integer which will be passed on to the main method I'm going to name this helper function as Helper and take the input n as a parameter and we are going to return this helper function inside the main function where we pass n as the parameter and now there should be a base condition for every recursive function that is the exit condition so for this whenever n is equal to Z we have to return 0o and now we have to find the perfect squares for that we start a loop where I will be the number which when multiplied with itself so we start with one and when I is Multiplied with itself so 1 into 1 we are going to check so if you multiply the same number with itself I into I this should be less than or equal to n and I will be keep on incrementing each time when the loop continues and now we calculate the value the current value which we are going to get so I'm going to name it current and I'm going to add one and call the helper function Again by subtracting the current value of I from n so I into I should be subtracted from n and now we need to keep track of the minimum number of uh current values so for that I create a variable minimum and assign it with the maximum possible value initially and now in each iteration I compare this minimum value with this current value so using mt. Min I compare the current minimum value Min with the current value current and now outside the for Loop we can return this minimum value so this is the recursive code now if you run this code the test cases will pass but if you submit this you'll get time limit exceeded error because there are lot of repeated calculations for that we have to implement memorization and the best way to imp M memorization is that you have to check the helper function and how many parameters are changing here in the every helper function only there's only one parameter which is keep on changing so we have to use a array to store its value so I'm going to create a memo array and inside the main function I'm going to initialize this memo array which is going to have the size n+ one which is going to have the size n+ one which is going to have the size n+ one because we start with zero and initially I'm going to fill all the elements inside this memo array with minus ones using arrays. fill and specify the arrays name and fill that array with minus ones it means that initially all the values are having minus 1es so if we haven't calculated that value for the end position that value will be minus one so inside this helper function before making the call here if we check if we already calculated that value if memo of n is not equal to minus1 it means we already calculated that value so we can directly return it instead of Performing the recursion so return memo of and if this is not true it means the value is minus one so we have to store this value inside the memo array before returning it so that we can use it in the next calls so memo of n is equal to Min and from the next time when that same value occurs it won't be minus one and we can return it from the memo now let's try to run the code the test case are being accepted let's submit the code and our solution has been accepted so the time complexity of this approach is O of n into root n where n is the input given to us and the speed B complexity is O ofn because we're using a 1D memo ARR to comput our output now let's take a look at the bottom of approach now let's take a look at the bottom up approach for that we have to use a 1D DP AR and now let's define the 1D DP AR so I created this 1D DP array and now let's define DP of I which is the state of every element so DP of I will represent the number of perfect square needed until that value so for example if you're calculating DP of 4 this will give us the optimal value of how many perfect squar we need to get n is equal to 4 so these values are equal to n so let's start filling our DP AR we take a DP of size n +1 and we fill the take a DP of size n +1 and we fill the take a DP of size n +1 and we fill the beginning element with zero because if n is equal to Z there will be zero number of perfect squares now DP of 1 what is the value of DP of 1 it is equal to 1 what is DP of 2 it is equal to 2 what is DP of 3 it is equal to 3 what is DP of 4 so the number of perfect square needed to get DP of 4 can be found out by 1 + 1 + 1 + 1 so you need four ones by 1 + 1 + 1 + 1 so you need four ones by 1 + 1 + 1 + 1 so you need four ones as perfect squares to build four so that will be your answer when you pick one so if you pick one as the perfect square you get four ones you can't pick two because it's not a perfect square you can't pick three because it's not a perfect square you can pick four which is the perfect square so there is 1 four now you can make five with the minimum value of 5 ones so if you add 5 ones you get five so that is the minimum value until now you can't pick because it's not a perfect square you can't pick three it's not a perfect square you can pick four so if you pick four you need one more one so 1 + 4 is equal to 5 so one more one so 1 + 4 is equal to 5 so one more one so 1 + 4 is equal to 5 so how many perfect squares you use you two so two will be the answer for this now n is equal to 6 if you pick six once the minimum value is six you can't pick two you can't pick three you can pick four so if you pick four and if you pick two ones you use three to get six so three will be a probable answer you can't pick five you can't pick six so three is your answer because Min of 6A 3 is 3 now n is equal to 7 you can pick seven ones you can't pick two you can't pick you can pick four so if you pick four you need three ones so how many you use three here you used one here so you used four you can't pick five you can't pick six so minimum among seven and four is four so four will be the optimal answer now n is equal to 8 so Min is equal to 8 because you can use 8 ones can't use you can't so if you use 14 you need four ones so how many use you use four year used one year so five perfect squares or you can use two fours so 4 + squares or you can use two fours so 4 + squares or you can use two fours so 4 + 4 is equal to 8 which is needed and how many used here you use two so two is also probable answer minimum among them is two so this will be two and when n is equal to 9 you can use 9 ons you can use 1 4 and 5 ones you can use 2 fours and one 1 and you can use 1 n because 9 is a perfect square you can use this so you can use one and minimum among them is one and similarly let me fill for 10 directly for 10 it will be 2 because we use 9 + 1 so we are using two perfect use 9 + 1 so we are using two perfect use 9 + 1 so we are using two perfect squares so that will be 2 and if n is equal to 11 we can use 1 n and 2 twos so it will be 3 so 9 + 2 this 2 is coming it will be 3 so 9 + 2 this 2 is coming it will be 3 so 9 + 2 this 2 is coming from 1 + 1 so you use three and from 1 + 1 so you use three and from 1 + 1 so you use three and finally n is equal to 12 and for 12 the optimal value is going to be 4 + 4 + 4 optimal value is going to be 4 + 4 + 4 optimal value is going to be 4 + 4 + 4 and we are using 3 so this will be three and now this is not used and now I just wrote it extra so this is not needed and your final answer is present at n is equal to 12 which is three which is matching here now let's take a look at the code coming to the code for the bottom up approach we just convert this topown approach code into bottom up for that we don't need the helper functions I'll copy the code inside this and paste it inside the main function and now we can remove the helper function and now this memo array I'm going to rename it into DP we don't need to declare it globally because there is only one function I'm going to name it DP which will be of the size n + one and DP of 0 is going to be size n + one and DP of 0 is going to be size n + one and DP of 0 is going to be zero because if you recall the state inside a DP array that is DP of I will represent how many number of perfect squares are needed to get that value since n is equal to Z there'll be zero number of perfect squares now we don't need the exit condition we can remove this we don't need this because we haven't implemented memorization and now we need to fill our DP array from index position one because DP of0 is already filled so I use a for Loop where I will start from one and I will iterate until n now I'll place this entire code inside the loop and now we declare a DP of I with the value I because so for example if DP of 7 is equal to 7 it means that at the minimum it will take seven perfect squares because one is a perfect square for every number 7even ones will be added and you get maximum possible value for the seventh index for six it will be six for five it will be five because we add all the ones until that number and represent it inside the DPR and now we have to calculate the minimum number for that I'm going to use a for Loop since we already used I here I'm going to rename it into J and J into J is less than or equal to I now because we only have to check until its previous number which we reached and now this will become j++ and now the same we will become j++ and now the same we will become j++ and now the same we don't have a helper function so we have to use the DP value now so helper will turn into DP and it will become DP of so like I said we don't need to go until n we only have to go until I and I we renamed it to J so it will become J into J and rest of the code is same and now we don't have uh memo array so we return DP of n which will uh be our answer and now we don't have a um Min variable right so we are calculating DP of I so replace Min with DP of I and here also DP of I now let's try to run the code the test case are being accepted let's submit the code and a solution has been accepted which is faster than the previous approach but the time complexity and space complexity is same as the top down approach so time complexity is Big of n into squ root of N and the space complexity is Big off end because we're using a DPR to computer output that's it guys thank you for watching and I'll see you in the next video | 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 |
1,332 | Once Hello Everyone Welcome To Day E F Malik And Challenge And I Hope All Of You Doing Well For Electrification Progressive Preparations In Full Swing To Remove Follow Me Must Subscribe Maulvi Subscribe Remove And Subscribe Skin Minimum Subscribe To Subscribe Our Is So Let's Walk Through All Possible After Bana Badhab Skin Remove Complete Strength Will Be Left With Only One Step At A TV Talk About What We Can Do We Can Remove From The Subscribe This To-Do List A Person Should Get Subscribe This To-Do List A Person Should Get Subscribe This To-Do List A Person Should Get Minimum Age Need To Be Rooted Through the return of the day I immediately get important information IBN7 Question Platform Last in the department Sequence in this note Springs What is the difference between and Suffering Means Kevin Explains Daily Life Zoom Vihar Benefits in A B C D and Clear Bach AIDS Patients Suffering In subscribe The Channel Please subscribe and like Share and subscribe the loot So let's talk about the second Rudraksha verses during different types of characters and chief and tell me about the meaning of free number for operations at mid day test ring. Tons of 20th is so let's talk about the solution with an example of life but example that in view of this to 20 Apr 20 so extra dot subscribe from this subscribe remove chief video subscribe remove chief bj subscribe ego joe alarms i morning life is shock Se Uber Bhi Left For Ads And Now Since Its Only Country In The Is A Way Can Remove Them In A Single Operations There Total Number Operation That Is Needed But Doesn't Enter Into Note And Subscribe Contains Two Types Of Taxes And All The Best All The Electronic subscribe The Channel Please subscribe this Video not support Play List of Budha Dar Ke Iss Videos Lightly Simpler Chief of Inputs in Tracking Systems Department Neer Vwe All District Unit subscribe to subscribe and subscribe the Channel Please subscribe and subscribe this Video not Front in this to so let's right pahal par minutes check jab under scooter not a ajay ko check ka lender am a hung verdict was a strength s inter high school and inter z till hold to start land and soil is left injured that this few stars Car eight came that sequence dots 48 details could china comment come and comment it carry out buddo daily quality fragrance return forms from no method is vansh vihar done with good convention breakup depression middle element been nominated for introduction of and want to so let's right Brother Method Tree Start Length One Object Belt Length Till Hero 6300 Egg Only One Takes Check With String To Me Can Not Only A Protest Creative Slaughter Now Is Hero Want To Wear For Removing All This From This Prank Pod By 20 For Boy Stabs Pressure Slice Of Sky And Anil Question By The Way Are Characters Quarter Time Complexity Of This Approach Astrologer Board Bhi Mode Of And Ant S Chief Force Confident Space Quality Unwanted Space And Time For Number Of Characters In The Important Lot That Thanks For Watching Video Hope You Enjoy This please don't forget to like comment and share this with your friends on | Remove Palindromic Subsequences | count-vowels-permutation | You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`.
Return _the **minimum** number of steps to make the given string empty_.
A string is a **subsequence** of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does **not** necessarily need to be contiguous.
A string is called **palindrome** if is one that reads the same backward as well as forward.
**Example 1:**
**Input:** s = "ababa "
**Output:** 1
**Explanation:** s is already a palindrome, so its entirety can be removed in a single step.
**Example 2:**
**Input:** s = "abb "
**Output:** 2
**Explanation:** "abb " -> "bb " -> " ".
Remove palindromic subsequence "a " then "bb ".
**Example 3:**
**Input:** s = "baabb "
**Output:** 2
**Explanation:** "baabb " -> "b " -> " ".
Remove palindromic subsequence "baab " then "b ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s[i]` is either `'a'` or `'b'`. | Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels. | Dynamic Programming | Hard | null |
380 | So hello everyone, our problem today is a medium level problem of lead code, so let's see how we will approach it, so today we are given the problem that we have to implement a random set class which has three classes. We have been given small functions for which we have to write the code. Right now let us see what those three functions are. First of all, there is an insert function which tells us what to do. Basically, this is our set which is a randomized set, this is our set. So what do we have to do, the obvious thing in the insert function is that if there is insert then we will insert the value inside the set. Now a condition has been given in it that if that value is not present inside the set then it has to be inserted and Return true. Write in case if that value is present in the set and we still want to insert it. Suppose it is present in the set. 1 2 3 And we want to insert one again in the set. In this case, it will not be inserted and we will return false in its place. Right now let's come to remove, this is the next remove function, so basically what we have to do in this is to remove the value from the set, right now when the value. Will be removed when there is value inside the set then it will be removed from it. Okay, if there is value inside the set and we want to remove it then we have to return true if there is no value inside the set and still we want to remove it. Suppose we have a set under 1 2 3 and we want to remove four, then four is not inside the set, otherwise in this case we will return false. Right after this, the next one is int get random one, we have to create a random function which is What will it do? It will take any random value from within that set and give us the right. Now let's see this example once. First of all we have randomized the set. What are we removing? We are removing two. There is only one lying inside the but set, so here we have given false right, after this what we are doing is inserting, what are we inserting, what was one inside the two set, now it has become one and two and because Two was not in the set earlier so we gave it true here, now we put get random here, we got one and two are lying in the set now, so we picked a random value, suppose that random value. There is two, one can also be two, here they have taken two right, now what we did next is run the remove function remove, what to do, we have to remove one, so we returned true because one was lying in our site, so We removed it successfully, after this we have to insert what to insert, but said is already true, so here we made it false, after this we have to get random i.e. again after this we have to get random i.e. again after this we have to get random i.e. again we have to get random function from a set. We have to pick a random element, but what is there inside the set right now, we have already removed one, only two are left inside the set, so what will we do, we will return two from the set, right, so its code is something. It wo n't happen but once we see its code, this is its code. First of all, what we did was we initialized an unordered set. After this what we saw inside our insert function is that if inside s that If the value is there then there is no need to insert then we will return false. In this case if that value is not there in s then first of all we put the value inside s and then we return true. Right after this we Let us see the remove function. In the remove function, first of all we checked if s has that value inside it or not. We checked in if s, then we erased it and returned true if else it is not so. We simply returned false, after this we had a get random function, here we simply rounded the enable function which returns a random variable, so we checked it, starting from the starting point which is set. From here we will pick any random variable from there and check whether it is within the bounds of its set or not, then from here we return it to a random variable or a random element. Okay, now once we see it submitted, this code should be our successfully submitted | Insert Delete GetRandom O(1) | insert-delete-getrandom-o1 | Implement the `RandomizedSet` class:
* `RandomizedSet()` Initializes the `RandomizedSet` object.
* `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise.
* `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise.
* `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned.
You must implement the functions of the class such that each function works in **average** `O(1)` time complexity.
**Example 1:**
**Input**
\[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\]
\[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\]
**Output**
\[null, true, false, true, 2, true, false, 2\]
**Explanation**
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.
**Constraints:**
* `-231 <= val <= 231 - 1`
* At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`.
* There will be **at least one** element in the data structure when `getRandom` is called. | null | Array,Hash Table,Math,Design,Randomized | Medium | 381 |
280 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem wiggle sort and if you're wondering that this is kind of a different ui you're right this is not actually on leak code wiggle sort is problem 280 on leak code but it's a premium problem but there's a way to solve premium problems for free sometimes on other sites and in this case i'm using a site called link code i'm not endorsed by them or anything it's just that you know they do sometimes have free problems which are premium on leak code so we're going to take advantage of that i mean google pays me pretty well but not well enough to afford leak code premium of course so in this case we're given an unsorted integer array and we want to reorder it in place basically such that these uh equalities hold but let's simplify the understanding of this what does this even tell us well so suppose we have some first value it could be anything the next value is going to be greater than or equal to the previous value makes sense the next value is going to be less than or equal to the previous value the next value is going to be greater than or equal to the previous value the next value is going to be less than or equal to the previous value etc basically anytime we add a new value it's going to be greater it's going to alternate between being greater and then being less than and then greater and then less than and then greater etc so it's just alternating the restriction here is that we want to do it in place so this is a pretty challenging problem but there's a thought process that can make it really simple the first thing you might be wondering is so this order is kind of weird but what if the input array was actually in sorted order instead of unsorted would that have made the problem easier definitely it would have because suppose we were given values like this one two three four five 6. we don't care too much what the first value is but we want the next value to be greater than or equal to this value that's true in this case because it's in sorted order but we want the next value to be less than or equal to this value and that's not going to be the case because these are in sorted order they're going to be in increasing order or of course they might be equal as well but how could we do this well the first idea would be to swap these two values right because since we already know that they're in sorted order we know that swapping them will give us what we want it'll make sure that uh you know let's do the swap here so we have a 3 here and then a 2 here what we wanted was this value to be less than or equal to this value so we achieved what we wanted but did we mess anything up beforehand well not really because we wanted this to be less than this value and we wanted this to be greater than this value now it doesn't matter which one of these values we put over here because all of them are greater than this value so it's pretty simple right we did we definitely did not mess anything up over here and then we're going to go to the next value we know that all of these are greater than all of these anyway so next when we say that we want this value to be greater than or equal to this one we know it's already true but we know that's not going to be the case here we want this value to be less than or equal to this value that's definitely not going to be the case but just like we did over here all we have to do is swap these two values so once we do that we'll be good right we wanted this to be less than this one and then we want this to be greater than this one and that's already the case so you can see that this algorithm when the input array is sorted is actually very easy we just start at the second value look at pairs of values so first we look at these two pairs swap them then we look at these two pairs and swap them but of course there's not two values so we don't have to swap anything so the downside of this approach is that while this algorithm kind of runs in linear time we did have to sort the array beforehand so the actual runtime is n log n which uh is not a bad solution at least it works but there is a way to do this in big o of end time without sorting the array and it's actually more simple than you might think let's just try it and see what happens first of all so first of all we're going to look at the first two values we want the second value to be greater than or equal to the previous one now if that's already the case which it is here we don't really have to do anything it makes our lives pretty easy so these two values are good but now we want to look at the next two values what we want is this value to be less than or equal to this one again it's already the case so we don't have to do anything again but there is going to come a point at the next value so now we're going to be looking at these two values we want this one to be greater than or equal to this one and it's not the case so what are we going to do well of course to make these two values valid all we have to do is swap them right that's the same thing we were doing before so what happens now if we swap them we get a 1 here and we get a 2 here so now this value is greater than this one greater than or equal to this one so these two values are good but did we mess anything up over here and my argument is that we definitely did not let me show you why we just want to make sure that this value is less than or equal to this one so how do we know that's still going to be the case uh even after we just did the swap we'll take a look beforehand we had a 2 and we had a 1. what we wanted was this value to be greater than or equal to this one but it wasn't it was less than or equal to 2. so when we swap it over here since we already knew that two was less than five which is what we wanted now that we have a value here one which is even smaller than two we know for sure it's still going to be less than 5 so we definitely didn't mess anything up and this is the example where we were looking at two values where this one was supposed to be greater than this one but you'll see that the same thing will hold even in the opposite case where we're looking at a value here that should be less than uh this one okay so far these four values are alternating right in terms of wiggle sore now we look at this one it should be less than this value it's not so what do we do all we have to do again is just swap the two values so we put the 2 over here and we put the 6 over here now did that mess anything up well remember what we want did that mess anything up over here well what we wanted was this value to be greater than or equal to this one now we replaced it now with a value that was even greater than two so for sure it's going to be greater than or equal to the previous one so in other words we didn't mess anything up and the first five values over here are in alternating order and next we're going to look at this value it should be greater than or equal to the previous one which it is so we don't have to do a swap in this case you can see that the exact same algorithm pretty much works out even if the array is unsorted all we have to do is compare values and if they're not in the correct order we just have to swap them and the good thing for us is that there are many valid orders for wiggle store and we don't have to create any particular one any of them will work as you can see below but one thing uh is algorithmically how are we gonna you know take care of the uh alternating order the value at index one should be greater than the value that came before it the value at index two should be less than the one that came before the value at index three should be greater than the one that came before it etcetera so what we're finding here is that values at odd indices should be greater than the previous value values at even indices should be less than the previous value so that's how we're going to handle it in code time complexity is big o of n memory complexity is big o of one so now let's write it up okay so now let's code it up a little bit of a different ui because remember we're doing this on lint code because it's free on there so what we're gonna do is just iterate through the array we're going to start at index 1 though because we want to look at the previous value we know that index 0 there is no previous value for index 0. so let's go through starting out index 1 and there's going to be two cases here remember so first is if we're at an odd index how do we determine that we can take the index mod it by 2 and if it's equal to 1 then we know that we're at an odd index and remember about odd indexes that means the value at nums of i should be greater than or equal to the value that came before it right that's what should happen but if it's not the case so basically we're going to inverse this inequality if it's not the case if the opposite is true if the value is less than the previous value what does that mean that means we have to perform a swap in python it's pretty easy to do that we're going to swap numbers of i and nums of i minus 1. of course you could use a temporary variable if you can't do this swap as easily as you can in python so let's do it like this we're literally just swapping the two values we can do it in one line so that's one case where we have to swap the values but let me copy and paste this because it's going to be very similar we know something different happens at even indices will be i modded by 2 is equal to 0. we know that at even indices numbers of i should be less than or equal to the value that came before it but if it's not the case meaning if nums of i is greater than the value that came before it again we are going to do a swap operation just like this one so that actually pretty much is the entire logic one thing you might notice though is we can clean this up a little bit because both of these conditionals are executing the exact same line so what we can do is literally combine them we can say if the above is true or if uh this is true let me fit it onto one line though so just putting it on the two lines actually so if either of these conditions is true let's get rid of this bottom stuff then we're going to perform a swap if neither of them are true we don't need to do a swap so after all that's done we can just go ahead and return nums and let's run it to make sure that it works and as you can see below yes it does and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching | Wiggle Sort | wiggle-sort | Given an integer array `nums`, reorder it such that `nums[0] <= nums[1] >= nums[2] <= nums[3]...`.
You may assume the input array always has a valid answer.
**Example 1:**
**Input:** nums = \[3,5,2,1,6,4\]
**Output:** \[3,5,1,6,2,4\]
**Explanation:** \[1,6,2,5,3,4\] is also accepted.
**Example 2:**
**Input:** nums = \[6,6,5,6,3,8\]
**Output:** \[6,6,5,6,3,8\]
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 104`
* It is guaranteed that there will be an answer for the given input `nums`.
**Follow up:** Could you solve the problem in `O(n)` time complexity? | null | Array,Greedy,Sorting | Medium | 75,324,2085 |
74 | certainly you already know how to perform a binary search on a sorted single dimensional array correct so naturally your interview will be interested to know okay what if you have two dimensional array that is sorted how will you perform this binary search algorithm on that so let's see what we can do about it Hello friends welcome back to my Channel first I will make a problem statement and we will look at some summative cases going forward we are going to discuss all the different methods that you can use to approach this problem and then we will derive an efficient solution out of them after that as usual we will also do a dry run of the code so that you can understand and visualize how all of this is actually working in action without further Ado let's get started first of all let's make sure that we are understanding the problem statement correctly in this problem you are given a m cross n integer Matrix it simply means that you have M rows and you have n columns correct now this array is sorted in a row wise manner so a 2d array can be sorted in lot of different ways you can sort it row wise you can sort it column wise and you can also have a spiral kind of sorting correct so when it asks that okay this Matrix is sorted in a row wise manner what does it mean it simply means that you will find your least element as the first element and your maximum element will be the last element correct and also there is one more condition you already know that all the rows are sorted correct but the first element of every row this element is greater than the last element of your previous row so this gives you a very big Hint it tells you that if you are at Row 2 then surely all of these elements they will be greater than all the elements in your previous row correct so technically if you are going from the least element to the greatest element then you will have to Traverse your array somewhat in this manner right and this is how you define this array so once this array is defined you are asked that okay can you find a Target 3 or can you find the target 13 so for example these two test cases you can find three over here right so you simply return a true in your first test case and you can see that you cannot find 13 anywhere over here right so for the second test case you simply need to return false as your answer now the interesting part about this problem is that you are expected to provide a solution that works in a Time complexity of log of M into n correct so how do you go about doing it before diving into the solution if you feel that you have understood the problem statement even better now first feel free to try it out otherwise let's go for it so once again I have a sample 2D array with me that has M rows and M columns correct and you are given a Target value of 30. you can see that all of my elements are sorted in a row wise fashion correct so how can you approach this problem as a developer you will try to first come up with a Brute Force approach right so the most naive way is that okay I will iterate through each element of the array and find if I can find it hurting so I can see a 30 over here and okay I will return a true right yes this solution works but it will have a worst case time complexity of order of M cross n because you may have to iterate through the entire array right and that will end up taking a lot of time so this gets you thinking okay how can I improve upon my solution if you think about it you never take any advantage of the fact that all the rows in this Matrix are sorted correct and whenever you see a array that is sorted you can apply the binary search algorithm correct so one way to solve this problem could be that okay you iterate over each row instead and for every row you apply the binary first algorithm so one way could be that okay I will iterate over my first row and then I will try to apply the binary search algorithm on this row right and if I find it Well I'm good otherwise know so what just happened if I'm applying the binary search algorithm on my first row then the time complexity would be order of log n right because you are finding it in just one row correct if you do not find it what do you go on to the second row and then once again you will apply the binary first algorithm that will be again login if you find it good otherwise you go on to the third row and once again you will apply the binary fetch algorithm and this will keep on happening for every row so what is your result and time complexity your resultant time complexity would be the number of rows multiplied by log n so this is your time complexity if you are going through each row and then applying the binary fetch algorithm so you if we let okay this is a good valuation and I also took advantage of the fact that all my array is sorted but still this is not the desired time complexity you want a Time complexity of log of M into n correct and certainly there should be something which we are missing out and that should be the thought you never take any advantage of the fact that if I am at Row 2 then all these elements these are smaller than 10 right so you need to leverage this fact as well and that will help us to build an efficient solution let us see how that looks to make things interesting let us take up a bigger example this time so I have this giant 2D array in front of me and I have this target element 71 correct so if you recall what we were doing in the last approach we iterated through each of the rows and we were applying a binary search algorithm right try to think that what did we miss out we never take any advantage of the fact that the first element of each row this will be larger than the last element of your previous row correct so what does this mean it simply means that all these columns they will be also sorted right so what happens if I try to find this target element 71 in my column first so just try to apply the binary search technique on the first column so what happens for this particular test case when I have the value 71 you will apply binary search on this array and you find a 71 right over here correct so you can see that okay I found it and that is true but what happens when the target value now changes let us say instead of 71 you have to Now find 66 what will you do will you start iterating through every column now sure if you do it you will eventually find the value 66 and you can say that hey I found it but doing this will again change your time complexity to M multiplied by log of n because you are doing the same approach right going over each column now and then applying the binary search technique so this is literally the same as going over each row and applying the binary fetch technique so this is where you need to make so try to find the element 66 in the first column you will say that okay I did not find the value 66 but you will find a very important piece of information so you know that 66 will surely be greater than 59 and it will surely be less than 71. correct so while applying the binary search algorithm try to find a potential row where you will be able to search for your Target element so with this particular condition you can be sure that okay my target element can only lie in this row correct so as a first step you have to find a potential Row in which you can find your target element to find this potential row you take up a time complexity of order of log of M right because you have M different rows and you're applying the binary search algorithm so this makes your problem so much easier right now that you have found the potential row you can just apply the binary search algorithm only on this row itself you don't have to apply it on any other rows and once you are applying this binary search on this particular row you will have an additional time complexity of order of login right and this will give you a total time complexity of log of M multiplied by n so you see how we took advantage of the fact that this array is sorted in a row wise Manner and we were able to arrive at a desired time complexity now this problem becomes so much easier right let us quickly do a dry run of the code now and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right once again I have a sample array and a Target value that are passed in as an input parameter to the function's first Matrix oh and by the way this complete code and if test cases are also available in my GitHub profile you can find the link in the description below moving on with the dry run for all let me give you an overview of what we are doing over here so I may remember what it refers to first of all we identified a potential row correct okay that this is the Rope where my solution could exist or where I can find my target element but what happens if I am searching for element LED for 99 or if I am searching for minus 11. these elements do not exist anywhere right so I will not find any potential Row for it so first of all in my driver what do we do I will try to find a row correct if I find a row well in good I now need to apply the binary search algorithm on this row itself otherwise I know that okay this element will not exist and I can simply return a false correct so that is exactly what we do over here try to look at this dry run now so first of all I try to find my potential row correct and to identify this row I will perform a binary search on this first column itself so I try to look for the element 16 in this first column I do not find a 16 over here but I find a potential row since 16 is smaller than 23 and greater than 10. it simply means that this Row 1 this is my potential row and once I exit out of this function I will get my potential rho F1 now that I know that okay I have to find my element only in this row I will use this index and once again call the binary search algorithm over the row this time I will have one more binary search implementation and I just try to find out this element 16 in this row if I find it yes I will return a true otherwise I will return a false so you can see we just applied binary search algorithm two times and we were able to arrive at our answer the time complexity of this solution is order of log of M cross n and the space complexity of this solution is order of 1 because we do not take any extra space to arrive at our solution I hope I was able to simplify the problem and its solution for you the thoughts I just want to say that whenever you see problems where your input data set is sorted then you have to take advantage of the fact and try to come up with a solution that is working in an order of login time complexity and the reverse is also true whenever you are expected that okay provide me a solution that works in an order of log and time complexity that certainly means that you have to approach this problem in a binary search fashion or rather a divide and conquer approach because at every step you will have to divide the problem into two segments such that your solution is simplified think about it even binary search trees you take advantage of the fact that one portion of the tree is smaller than the node and one portion is larger so effectively you are breaking your problem into two parts at every interval correct so just keep this in mind and take this as a hint when coming up with Solutions so while going throughout this video did you face any problems or have you seen any other problems which use the binary search or the divide and conquer technique underneath its Shadows so tell me all about it in the comment section below and it would be helpful for all of us I will be more than happy to discuss all of it as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where assembly by programming for you also let me know what problems do you want me to follow next until then see ya | Search a 2D Matrix | search-a-2d-matrix | You are given an `m x n` integer matrix `matrix` with the following two properties:
* Each row is sorted in non-decreasing order.
* The first integer of each row is greater than the last integer of the previous row.
Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_.
You must write a solution in `O(log(m * n))` time complexity.
**Example 1:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-104 <= matrix[i][j], target <= 104` | null | Array,Binary Search,Matrix | Medium | 240 |
1,971 | foreign welcome back to the channel in this video lecture we'll be solving this problem find if path exists in graph or not which is the lead code easy problem in this problem there is a bi-directional graph so what is a bi-directional graph so what is a bi-directional graph so what is a bi-directional graph a graph which has bi-directional graph a graph which has bi-directional graph a graph which has two way edges it has n vertices or nodes and each vertex is labeled from 0 to n minus 1. the edges in the graph are represented in the form of 2D array where each element in the 2D array is a pair of integers denoting a bi-directional edge between those bi-directional edge between those bi-directional edge between those vertices so every vertex pair is connected by at most one Edge and there is no self Edge for any node so what do we have in this problem we want to determine if there is a valid path that exists from vertex source to destination so we are given edges and integers n source and destination representing the number of nodes Source node and the destination node we have to return true if there is a valid path from the source to destination or false otherwise so let's see the constraints of the problem the number of nodes may go up to 10 raised to the power of 5 while the number of edges may also go up to 10 raised to the power of 5 and the nodes are labeled from 0 to n minus 1 if there are n nodes and node 2 and there is no self Edge for any vertex and there are also no duplicate edges there is exactly one Edge between each pair of vertices so let's better understand the problem statement using an example so here we have our exampler test case which has been taken from the problem statement itself we have three nodes and we know that for n nodes they are labeled from 0 to n minus 1 so 3 nodes will be labeled from 0 to 0 1 2 we have Source node as 0 which is this and destination node as 2 which is in order to find if there is a path from 0 to 2 let's see how we can see that so you can see that the there is a direct Edge from 0 to 2 so we can see start from 0 we just jump to 2. hence the answer for this test case is true there is one more path from 0 to 2 which is move from 0 to 1 then from 1 to 2. hence there are total two paths for this particular test case we have two parts to move from node number 0 to node number two fine so how we can solve this problem this is a very easy problem let's try to build the solution for this problem so let's take this example we have Source node as 0 and the destination node as four you want to start from the source node I want to reach to the destination node using some set of edges and check if it if we can reach the destination node or not so how do we do that we know that we have a graph we have some graph traversal algorithms like BFS and DFS we can use BFS or DFS to solve this problem so this simple graph traversal algorithms what do we do in VFS we start from our source vertex and we push its addition nodes into the queue so nbfs we Traverse the nodes in a level wise fashion so first we explore the node number 0 let's say it is at level number zero then we explore the nodes which are at level number one or one Edge away from the source node let's call it level number one similarly we keep exploring the nodes and whenever we reach the destination node that means we have a path to move from The Source node to the destination node and we return true there and first time we reach the destination node then the path along which we have reached the destination node first is also the shortest path but in the problem statement we are not asked to retrieve or print the shortest path we just want to check if we can reach the destination node and whenever we find or encounter the destination node while performing our BFS we just returned true right from there fine so similarly we can also use depth first search but in depth first search we know that so we can also use depth first search for performing the same task we'll start from Source node we can recursively Traverse the vertices from 0 to 1 then to 3 then we backtrack to the previous nodes and explore other children whenever we reach the target node we return true so this is the second approach to solve this problem here I am assuming that you are familiar with these algorithms in this video lecture I will be using BFS algorithm to solve this problem let's drag on our BFS for this particular test case Okay so this is my queue where I push the source node initially which is node number 0 this is the back of the queue and this is the front of the queue and this is my visited array which will be used to check if a particular node is visited or not so initially we have Source node which is 0 it is visited then I pop this node out of the queue and I explore its adjacent notes which is node number one and non number two so I marked them visited in this visited array and I push them into the queue then I pop the next front load from the queue which is node number one and I explore its additional node which is node number three so we Mark node number three as visited and we push it into the queue okay so then we pop node number two out of the queue and we explore its neighbor nodes which is node number four so we mark it as visited and we push it into the queue so here I check that node number four is encountered which is same as the destination node that means we have arrived at node number four along sum path and hence it is reachable so we return true right there and we break our while loop because I found my destination node and there's no meaning in running the BFS so that's how the BFS algorithm works for this problem and let's see the implementation of the idea explained here which is just a plain BFS so this is just a plain BFS we have this valid path function which takes in the number of nodes edges Source node and destination node I declare a graph so it will be used to create or generate the graph from the given edges then I generate My bi-directional Graph so I generate My bi-directional Graph so I generate My bi-directional Graph so I generate two way edges here then I create a visited array or a scene array which will be used to keep track of the visitor nodes I Mark The Source node as visited so this is Source node then I declare a queue and I push the source node into the queue then I run my while loop till the queue is not empty I pop the front node from the queue and I check if the node which is present at the top of the cube is the destination node if it is the case then I return true otherwise I explore its addition nodes and for all the addition nodes which are not visited yet I visit them and push them into the queue to explore them in the next iteration finally if I do not find my destination node while running this PFS that means there is no path to reach the destination node which starts from our source node hence a return Falls from at the end of the function because I haven't find any such valid path fine so this is how the algorithm works it is just a simple BFS we can also solve this same problem using depth first search approach let's discuss the time and space complexity for the idea explained here okay so this is the time and space complexity the time complexity for the given implementation is we go of n plus 1 where represents the number of nodes M represents the number of edges while the space complexity is also big of n plus M and the time complexity is same as the time complexity for running a BFS since we are exploring all the edges and all the nodes that's why the time complexity is bigger of n plus M while the space complexity is also big of n plus M because we use a q data structure to store those nodes and we explore all the edges for each node fine let's see the code implementation of this okay so this is my valid path function which takes in the number of nodes and the edges The Source node and the destination node so first declare my graph which will be used to create the graph from the given set of Edge and nodes then I generate my graph from the given edges array so I simply iterate over the edges and create bi-directional then I declare my visited bi-directional then I declare my visited bi-directional then I declare my visited array of size n and my mark all the nodes as unvisited of the source node as visited and I declare a queue as well and I initialize this queue with the source node then I run my BFS search then I pop the front node from the cube and then above the friend node from the queue and I check if this node is the destination node if it is the case then I returned through otherwise I moved to the neighbor nodes and I pushed all the Unseen nodes into the queue so if I encounter a node which is not visited I mark it as visited and I push it into the key finally if I do not arrive at the test station node while running this loop I return false right at the end of this function fine so this is how this is the implementation of symbol BFS algorithm it checks if there is a valid path in the given graph from the source to destination this is the implementation in C plus lets the implementation in other languages so this is the implementation in Java and this is the implementation in Python language so that's all for this video if you like the video then hit the like button and make sure to subscribe to my YouTube channel and give your feedback in the comments below I'll solve this problem with disjoint set Union in my next video so stay tuned with me I'll see you in the next video till then take care bye thank you | Find if Path Exists in Graph | incremental-memory-leak | There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself.
You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`.
Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2
**Output:** true
**Explanation:** There are two paths from vertex 0 to vertex 2:
- 0 -> 1 -> 2
- 0 -> 2
**Example 2:**
**Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5
**Output:** false
**Explanation:** There is no path from vertex 0 to vertex 5.
**Constraints:**
* `1 <= n <= 2 * 105`
* `0 <= edges.length <= 2 * 105`
* `edges[i].length == 2`
* `0 <= ui, vi <= n - 1`
* `ui != vi`
* `0 <= source, destination <= n - 1`
* There are no duplicate edges.
* There are no self edges. | What is the upper bound for the number of seconds? Simulate the process of allocating memory. | Simulation | Medium | null |
221 | hi everyone today we're gonna solve question number two 21 maximal square I'm gonna give you three solutions we're gonna dive deep into all of them so we understand the thought process of coming up with these solutions and evolving the solutions I think this is a critical step to make you succeed so let's dive into it given a 2d binary matrix filled with zeros and ones final largest square containing only once and return its area essentially you're given a matrix filled with zeros and ones and your goal is to identify a collection of ones that form the largest square all right let's look at an example so given a matrix here how would you identify the large square so one of the first things you probably want to do is identify if that particular cell contains a 1 right once it contains a 1 you might think about alright is this one part of my square now if I look at it this way the brute force way to solve this would be to hmm check my partner see if it's equal to 1 or go up to the part where equal to 1 and then if it stops at this point I know that this can be potentially a size 2 of 2 therefore my next iteration will check well I'm gonna check my rows now to see if this and this is gonna be equal to 2 in this case it doesn't because the zero throws it off so therefore this is invalid 2x2 however yeah it is a valid one by one right so we go and iterate and do this operation over it and over again until we reach to a point somewhere like this right where we could go and check ok I'm gonna go here up to the point where it ends right so this is a size 3 and can potentially be a 3 by 3 but once over here we know that then we're gonna check 3 at the cut back my first coordinate okay that's valid and then I'm going to check my second oh wait I got rejected by the third element right so this is probably not gonna be a 3 by 3 so what do i do I resort back into my 2 by 2 a penitential 2 by 2 and I check whether or not is a 2 and yes it can be a two by two so therefore this two by two can potentially be a positive solution right and you continue this algorithm and you'll probably get three different sets of two by two but since this problem involves only one solution you could just take the first one or any of these and return it and should be fine this method is probably called if you think about it's really brute force II right you're basically reiterating and recalculating a lot of steps over and over again and it won't be as effective because when you think about it in the worst case scenario you're gonna be iterating through all columns and rows causing a table complexity of oh of row and column squared this is pretty bad right so why don't we think of another potential solution and see if we can get any hints from the actual questions again so if we looked at the question briefly for a sec one of the key points in mention here is find the largest square so if you start doing these questions quite often you'll start noticing some small slight patterns if something that talks about largest maximum minimum that type of nature you could almost think about or at least consider using dynamic programming as a possible solution why I say this it's primarily driven by dynamic programming is essentially using your history or a cache of some sort of knowledge that you know to build up your current solution right so we could try to break this problem into sub little problems or little smaller things right so let's look at this problem here and instead of like factoring or finding that the biggest put the possible square why don't we isolate like it's the one of the one possibility which is a two by two a simple two by two right if you look at this quadrant right here all right I'm gonna cup here we're given basically a left top a left quadrant and a top part and a bottom part bottom right now bottom right so we have like these four quadrants right so if we look at this question we almost think about all right if we wanted to apply I don't know what to do I know that's longest so somewhat dynamic programming ish um what can we do such that when we iterate through each item we're gonna actually have a ability to view or historical basically patterns and apply to our future outcome now let's assume that okay well if we're gonna do dynamic programming maybe something we can do is maybe create a duplicate copy of this particular this matrix but like this copy doesn't have to be actual values could be like all zeros we just saw it although at least as of the same size right so when I in rate through this table of this matrix as long as it hits one we're gonna do something on our cache right and what does this cache can really represent because we want to use as we iterate through all these elements we want to make sure that as we iterate you know we capture certain elements over again so we could use to our next problem one of the things I like to think about is that okay so the first approach we took we talked we essentially assume that the first variable is the left top option right because we're saying that okay on the brute force method we're gonna go in here top left and then start going searching right so let's think a little bit outside the box if we were to continue use the top left portion the minute we go to the next box here we lose track of pretty much what's a little bit of our history right so what we want to do potentially here is actually assume this particular quadrant to be potentially the bottom right but assuming that this can be possibly a bottom right solution then the problem becomes as we iterate through these questions we get a suit like okay well this quadrant so let's do an example for example if we go here all right what is this right we hit one and we're gonna see like okay well my top by top my top left my left they're all an unidentified however it says is one right size one so we know for a fact that the maximum size this particular square on this particular space can be only one right so the bottom right corner of this imagine there's a square here the bottom right would be one right same thing applies here we're gonna assume that okay well although my left is gonna be at one my left top or top left I think we call this top left because what's easier my top left is unidentified my top is also unidentified however this is still one so I could you know take the minimum of these three elements plus a 1 here so my maximum size over here is 1 we're gonna repeat this going on and up to here it's also gonna be 1 and we continue to go on and on this will also be a 1 because if you look at the top left here this is gonna be 0 and this will be a 1 this could be a 1 0 and this will be a 1 because we're doing the same thing again now when we reached at this point it gets slightly interesting because when we look at what was our bottom right corners of the previous pretty boxes around us there are 1 and ones these are 1 by ones because I movie here I could take the minimum of these 3 elements which is gonna be 1 and add to itself over here so this is saying that ok since my father this is a storage of all the bottom rights this particular box at this particular point is part of it 2 by 2 right so we know that there is a point over here that's a 2 by 2 so we can store this as our maximum for now because you know this is the biggest box and we continue to do this algorithm go here same thing again minimum of these three is 1 and you add yourself will be equal to 2 all right we go down here you know - I all right we go down here you know - I all right we go down here you know - I don't know unidentified in a zero well that's gonna be 0 and this will be a 1 right same thing here because of the 0 this is gonna be a 1 0 1 over here and of course this is the same pattern as the top one Oh be a 2 right so now we saw see a way of effectively identifying the maximum size of the potential square it can be by identifying or storing bottom right quadrants right or bottom right segments that they indicate how big the box can be right but what we really just did here is you know trade off a little bit of time complexity but increased or juice stuff or space complexity right this is cool sometimes you know in the interview they're cool with it you know storage is cheap they might not care however you have you if you ever noticed that this question if you think deeper there might actually be a way to optimize this just ever so slightly as well because the nature of the problem asked only for the maximum square just ask anything else storing any like where all of them locate etc it only asked for one number we can start thinking about potentially optimizing it even more now before I go and talk about that particular problem I just want to reiterate that I'll probably after this segment go and code up this particular solution because a lot of the time we may not even have the time to think about this deeper problem right and order the deeper solution right so sometimes you want to like this is already optimized enough we want to get to whiteboard talk to the interviewer see if they're cool with it most likely they'll be like yeah cool with it and then we can start building up okay maybe you could optimize that at a later time right so I'm after this particular solution which I'm gonna discuss we're gonna go and code up pretty much two solutions right this one and I'm more optimized Ellucian so on this one just for the career reference this would be a you know hole of basically columns times row time complexity right with a storage space of O or column and M as well right so when we look at this question the slightly deeper we can actually identify a small pattern because as we look at through these elements we actually don't need to track all the matrix itself if you think a little bit slightly more we all really only need to know what the size or create an array are a cache that is of size the column length now let's look at how I'm gonna explain this so what we when we go through the exercise of looking at things we can actually just create a cache of size of the same size of the column and this will effectively be able to keep capture our previous elements and also as long as we store the top-left corner somewhere the previous top-left corner somewhere the previous top-left corner somewhere the previous element then we can pretty much formulate the expected bottom right corner right on here so maybe it's a little bit convoluted I can't explain it that detail right now but maybe wise we go through an example here and how the computer can compute it you'll probably catch on so in this particular algorithm it's really it really talks about the whole concept oh okay you know I'm gonna go and try to do and look at my you know what was my historic what did I see before right and compute okay what I've solved before and also my neighbor and what the neighbors before was do they form a square for me right in this case it will not it would just be a 1 and a 0 right when it hits one in one zero so what we will probably do it hits one the first thing you want to do is like your previous one I'm gonna store this as a temporary value first right because that's mine that's my value here and then I'm gonna go okay because my temporary value I'm gonna start checking my these elements which right now they're not set to anything because I'm looking at the top-left quadrant so I only know that I top-left quadrant so I only know that I top-left quadrant so I only know that I couldn't set myself which is gonna be a 1 well that's fine and before we move on to the next element I'm gonna make sure that I store this particular element as a call it as a previous because now if we look at the context of this particular square right this is gonna be previous to it right so let's go continue on if I go to this next square right here right we're gonna basically ask ourselves all right what was the previous we're gonna go through this again post or this one in here as a temporary value and we're looking at this particular column we're gonna look at what was stored on the top which is nothing on the left is a one and the previous to the one was a one the lowest because of this unidentified these three will cause it to be only a one so that's fine and then of course this one is a zero and a zero right so this is like the first row right now let's look what happens on the second row because we're looking at it zero here and we're gonna set a temporary bout to be zero there we know for a fact that okay this is not gonna be square anymore right because you're starting at zero so actually what we're storing here bottom right it's gonna be a zero which this will become a zero as well and zero so actually let me make this as more clear this like step one right and there's step two would be a zero right so this is the size step yes again step over the second row and then a third one would be like okay well now I'm gonna go to my fourth case right here so I reach up to here right which is mirror at this point and these three over here obviously is my previous value was a zero and my temp value is a zero and my next door neighbor's is zero and itself is a zero then therefore this is gonna be only a one right because I'm not we're on this row right now right so let me repeat that so over when we get on look at the matrix and look at the number one what we want to do is effectively look at what we saw in the past right on the past at the existing same position over here the past was what was this is like our past here before I started editing anything else in here this was the past right we're just overwriting the past so in the past this was a zero it didn't mean anything however when I look at my past plus my previous pass or like my partner's past to see if there's anything that has a 1 in there and there's nothing so therefore it's the same concept right this is only gonna be a 1 same thing goes into this case and this case right because if we look at our history you know they're all zeros and we look at our neighbors in this case though they're yeah our neighbor is a 1 however it's past was like only a 0 right so therefore and my pass was also a 0 so therefore looking at these consideration this is only gonna be itself which is 1 right and then we move to the next cache remember these are not creating new instances of the Ray all we're really doing is actually you know just I want to show you each step of the process why this would work right so on the next phase we're moving on to this row right so in here it's a 0 doesn't do anything but on here this is where it gets interesting right on here we're gonna look at okay what was my before we start it'll be like okay I'm going to temporarily store my one here right I'm gonna start looking at okay so on this particular value what was my partner here inside it's a zero right and what was my partners his past right that was you know previous right here so that was a zero here and what was my past was a one right but when I take the minimum of these three elements right so we know that my one is you know I mean zero is the minimum so therefore this whole thing is comebacks won't be a one-by-one so I'm going to put a 1 here one-by-one so I'm going to put a 1 here one-by-one so I'm going to put a 1 here right now if I do that I make sure i got obtain my previous not because this is becomes my previous now we look at this particular element this is the one that's very interesting because now when we go and enter this particular quadrant we put the one in your temporary storage and we start looking at okay well what about what is my left partner but left part is a 1 right and because this is a little bit lagging we can check what was the previous to this left partner which is this element which is a 1 that's great and what was my historical value well it's right there right it's this is this was what was my past right well we looked at before so therefore I have three of them that equal to one so what I could effectively do is like take those want to minimum of those three elements and add one to it so this will be a two and then same case for here another two right and then we move on to here of course is a two you can always put a value on the side saying like what it's a solution you know store that so your maximum solution right now via two and then we go to here in this case is gonna be like okay well one it's gonna be a one here over here because you're looking at your past I'm not keeping track of this but in my one here that's great we're looking here effectively it was your passwords like zero and a one and one so this will be just a 0 over here so max is gonna be a 1 and on this element oops I actually let me create this new one because that's not the new instance this is the new instance so this was zero sorry apologize for that I'm not gonna edit this out so this is the process this is the row that we're gonna look at for this particular element right so we look in here that's a 1 because we look at our previous history boom there's nothing there our partner is nothing it's nothing there in a previous is like the only wine which is doesn't mean anything so this is a b1 we could continue on this we're gonna look at our previous historical value which is a 1 that's cool check box our next door neighbor that's cool however our previous which is zero that's not cool so therefore my minimum will be a 0 and this will be defaulted to 1 now let's take a look at this one is kind of interesting because it's a zero right so we can't really do anything with if this is zero then there can't be a box bigger than that right so this will be aught of defined by zero and zero so our previous letters ero now yeah it was Yoda and now for the final step we go move down boom we start modifying the same array but we only have like a couple of values right so on here we're gonna look at it's gonna be a 1 again because the same logic applies well but when we get to this point we look at 1 & 1 point we look at 1 & 1 point we look at 1 & 1 right this one doesn't this one number this is only instance of itself so this one is equivalent to here right so we this is cool left is cool and our previous is should be a 1 because we were here before we look at previous cool so this will actually be a 2 right so effectively doing this you'll find the solution again right I know this is slightly a bit confusing but when we look in the actual code it probably make more sense but let's just recap real quick because right now we've just eliminate all of the rows and times complexity wise and only kept up with the in the column size right so all you're really doing if you've done a question like the histogram problem before this is very similar all you're really doing is taking layer by layer and using the layering as you go iterate through each row that has your historical point right like at that particular first layer this is my history right and then I go to my second layer but that was my past right before I'm gonna overwrite things with zeros and then so on and so forth and that's only really updating right so as you go boom update look at your past and form the squares you can find the maximum of squares and therefore you could you know report and get the right solution so let's dive into code I've been talking too much and let's see if we get start actually start solving this okay all right let's finally gets into some coding so the first problem gonna code up is well not problem solution is the dynamic programming using dynamic programming and it's the matrix solution first long we don't convert this back into function matrix syntactically I like this more and I'm gonna start creating a couple of variables so let's create a cache you know that stores our stuff and we're gonna call this crash I'm gonna actually spread make the cache a duplicate copy of our existing matrix you don't need to do this you could simply get a new cache of 0 values it's the same thing but I just feel like filling things in there and replacing it's not doesn't harm it you could always do it either way I'm gonna go create a height so not the reference it all the time will be matrix top like a whiff will be equals matrix-matrix at a whiff will be equals matrix-matrix at a whiff will be equals matrix-matrix at with zero top length right and I'm gonna create a solution for now I'm gonna call it zero right and okay cool so actually let's pick a pause here we can't actually put it as 0 because there is a case where what if we don't get a matrix that beyond that is a you know more than two rows right what if it's only in one row and if it's only one row then we really only need to consider if that row contains you know a1 because the maximum square you can have in a one by one oh one row was one right so instead of 0 I'm gonna actually make it such that I'm gonna go math dot max and spread the matrix at zero so for those who don't know what the spread operator does all it effectively does is like take your array here as an example it takes this array of arrays you know ray right oh this really does is like this is matrix right so I'm doing is just taking everything in this element and copying it or spreading it into here into this array so effectively you know you're just taking this the guts of this inner part of the matrix and plopping it in here alright so same thing in here I'm just taking the guts of the zeroth element right I'm gonna take the maximum value of that element so in here could be like 0 1 X etc all I'm doing is just taking that the guts of this and putting it in here so you'll see that the maximum value of those right ok so that's all I'm really doing this is always deal with the edge case of the first if your inputs gonna be like of size 1 right so I'll deal with that's great and I need to also consider some elements that because we're doing with those cigar boxes we don't actually deal with the first row so I'm gonna make sure that I capture that so for that I equals to 0 is less than matrix length right and is plus all right so what am I doing here all I'm doing here is to check whether or not my sidebars here like if I were to give like those odd cases where you know everything else is 0 and on my side my first initial bar is 1 I didn't make sure that hey does that contain a 1 all right so all I need to do is like same solution these like dealing with those edge cases math.max it's gonna be edge cases math.max it's gonna be edge cases math.max it's gonna be compared to your solution and I'm gonna look at the matrix at either position but I'm only looking at the first value so this all deals with that really unique case of ok what if all of these inner elements were zeros and everything else is 0 but you have this like one little awkward one on the top on the bottom left corner right then this one's gonna be very difficult to solve so that deals with that case so all we have to worry about is like this inner box right here now right so let's go look into it I'm gonna first of all if writer mark you know bring back the old school for loop let Rho equal to 1 because I want to start by start at this position because I've already dealt with the ones on the edge and it on the side edge as well put these two additions remember started with 1 so Rho is less than height right and Rho will be plus right for every row I'm going to check for every column let call them equal to 1 and column it's gonna be less than width right and then column is gonna be plus so what do you do here all right so as we iterate through each element or three to number I'm gonna check if my matrix major matrix at that particular row and at that their column does that equal to t1 right if it does then we better do something with it right in here remember what I mentioned before in our corner quick example here we need to ensure that we're looking at the top left and that those three numbers and take the minimum of it right so we're gonna do that here so here we're gonna go and say our cash at that particular session row and column type right now getting late roll a column will equal to mass dot min right and then go to make sure to check out the minimum of the cash write a position of roll minus 1 and of column right and I'm gonna make sure I go of cash at row and by column minus 1 and my cash at row minus 1 all the minus 1 right and I believe that's cool and I need to make sure I add 1 to it right to itself because that's what you do and then from here I'm going to make sure that my solution is equals math.max of what was stored in the cache math.max of what was stored in the cache math.max of what was stored in the cache at row and column and of course compared to itself like which is the maximum and then store that cool so when we look at this have we solved the problem yet we're missing some elements what if because there's no ed they never put any notes here saying that okay what if I give you like these edge cases which is you know what if the matrix IQ is null or what are the matrix that give you as like has nothing right so I'm gonna put a condition to check those conditions so I'm gonna make sure that my matrix actually does exists right if it doesn't exist or if my matrix at position zero does not then I'm just gonna return back to zero so it's getting late all right it's cool let's see if this solution works or not let's run the first case oh one thing I almost forgot I forgot to return the solution or turn solution times solution great I'll submit it and bam ooh this is terrible timing but it solves the problem right let's run in a gun let's run again just to make sure I like to take a heat check oh well you know this is really leak code you really reliable um so let's so this is the answer to the first solution which is goes into you know creating squares and eccentric cetera now let's dive into a little bit more deeper question here like how to solve that one so when we talk - solve that one so when we talk - solve that one so when we talk - interviewer we're like okay how can we optimize this right what's the big bottleneck that we're trying to optimize so what's really what we're trying to optimize is pretty much our storage layer right so in our storage layer we're actually optimizing this is the cache itself and this syntax down here right so actually and we look at this particular problem we don't actually have to edit that much right all we really need to do is effectively create a cache you know change the cache - now to be of size you know it's gonna - now to be of size you know it's gonna - now to be of size you know it's gonna be a new array of size with oops move this down here cuz with us hasn't been defined yet very cool okay we're gonna make it size with and I'm gonna add one to it the reason I want to add one to it if you guys didn't know the subtleness I had here if I didn't add a one here it's gonna be unidentified which it's not cool guys I'm gonna check on this top quarter what was my previous partner it was nothing just for arguing to say I'm just gonna make an irate that's what sighs one bigger and so I could check the next side and they slowly exists so that's we're gonna do save that unidentified problem so that's why I put the plus one and I'm just gonna fill it with zeros you know how talked about how you don't have to carbon copy you could just fill there you go you can fill it so we're not I just filled it up that's great the same condition still applies you know those edge cases still apply however now we don't have to check this anymore because we don't have to go check those edge columns this still applies because we're still iterating through everything right but now one thing that is changing is that we're gonna make sure to start at position 1 but our matrix is gonna actually be minus 1 because we've already grown this particular cache to be puff plus 1 more so we need to make sure that we get back to 0 all right cool so now I'm not dealing with rows I'm dealing with caches and I'm only gonna have columns right so that's all yeah I don't deal with columns right so one part we need to change is this formula right instead of looking at the 2d matrix that I have I need to make sure I'm looking at a couple other elements so remember what I mentioned earlier before how I need to you know before I do anything I'm going to check my value or buddy's created temporary value temporary well equal to effectively my cash right now the column right and if it equals to that you do something in here else I'm gonna make my cash at that column equal to 0 right to clear it out and make sure that my previous equal to my oh I didn't define my previous let's define it here previous equals to 0 for now so video this will be equal to temporary bool and over here I am going to change something in here right the thing we change in here is that we're not referring to a full two dimensional array anymore we do it by one and what we actually have available instead to us are these variables that we store that are available to us so in here I'm simply just gonna go and check let's delete this all I'm really gonna check is my first one my previous value which is available here that talks about this is the top left corner right and then I'm gonna compare it to my cash at column minus one which is my next-door neighbor minus one which is my next-door neighbor minus one which is my next-door neighbor I call it and I'm gonna call it check my previous one which is gonna be my top right cash at column right we'll check these three values and then I'm gonna +1 these three values and then I'm gonna +1 these three values and then I'm gonna +1 to it as well right and let me just get this to column and effectively by doing this we saved a lot of rows we don't do that much now let's try to submit the solution and see if it actually solves the problem Oh No it failed hmm what did I do wrong here something failed here well this is where you have to sometimes troubleshoot and see what you've done wrong okay cool let's see uh see if I follow through my question here and see if I've got the right okay that's fine oh ha so we never actually go end because we created that extra space here I forgot to go all the way to the end where here you go and now we should be good all right see this problem this new solution it beats 100% of storage space solution it beats 100% of storage space solution it beats 100% of storage space because the store not much anymore and it's also you know pretty fast just change a couple codes so some of these questions are relatively typical to be asked on an interview because all you need to do is change a couple of elements on your existing code when you optimize things and yeah hopefully you find this useful I know this is a little bit more drawn out of video but I think if you spend some time to understand this particular concept and this particular question you're gonna be able to solve a lot of questions anything relating to like histograms anything relating to front maximum square or finding the maximum rectangles maximal stars on grids this is very important so hope you like it if you liked it please subscribe please hit the bell it's getting really late here it's like 1:00 getting really late here it's like 1:00 getting really late here it's like 1:00 a.m. and I'm getting tired and I'm a.m. and I'm getting tired and I'm a.m. and I'm getting tired and I'm probably didn't explain stuff at the end that well but please bear with me let me know what's improvements and we'll stay tuned for the next video thanks everyone | Maximal Square | maximal-square | Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_.
**Example 1:**
**Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\]
**Output:** 4
**Example 2:**
**Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\]
**Output:** 1
**Example 3:**
**Input:** matrix = \[\[ "0 "\]\]
**Output:** 0
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is `'0'` or `'1'`. | null | Array,Dynamic Programming,Matrix | Medium | 85,769,1312,2200 |
235 | hey everyone today let's go through another classic lyrical problem 235 lowest common ancestor of a binary search tree first we need to Define what is a binary search tree all of the left children nodes are exactly smaller than the parent node this is the left tree it is also a tree a sub tree but all of the nodes on the left side of this root node they are all exactly smaller than the parent node which is six right two four three five zero they are all exactly smaller than six and then all of the right nodes are the right subtree they are exactly greater than the parent node 879 they are all exactly greater than the parent node 6. that's the definition of binary search tree our Target is to find the lowest common ancestor so what's the definition of LCA that is the lowest common ancestor is defined between two nodes p and Q as the lowest note in t is the tree that has both p and Q as descendants we allow a node to be a descendant of itself saying two I'm saying 8 could be a descendant of 8 itself we need to find the lowest common ancestor for example in this case given the root is this which basically is using level Auto traversal to describe such a tree p is 2 is here and Q is 8 is here so we can see the lowest common ancestor for this given example is the parent node itself six and then another example here is given the exact same tree right exact same tree and P is still two but Q is 4 now so in this case the lowest common ancestor LCA for these two nodes is two right because 2 is allowed to be a descendant of itself or a common ancestor of itself the reason it's very classic it helps us to understand what is a binary search tree and how can we use the feature of binary research training to find the lowest common ancestor of course they are at the more regular trees the method that we are going to apply here doesn't really apply to other General trees which is a different topic while covering another video given this example this is a binary search tree all of the left nodes are exactly smaller than the parent node also all of the right nodes are exactly greater than the parent node this is the current route 5 is the current route and then p is one Q is seven we're trying to find the LCA of these two nodes we can use the feature of binary search tree which is always everything is sorted the given root is five and our Target is to find the LCA of one and seven what we can do is we compare the value of the two nodes always with the current root note so 5 is greater than one right but five is smaller than seven so that means the current root is actually the LCA of these two nodes by looking at these three this three we can tell that is the case so in this case we'll just return root right all right let's take a look at one more example using the same tree but p is still one Q becomes three so how do we do in this case will continue in the beginning were given to the access only of the root node and then the two other nodes that were trying to find an else so root is five We compare these two notes value against five to see if the root node is greater than or equal to or smaller than 5 is greater than 1 which is the first node that we're trying to find a match against and then the second note is also smaller than the root node so in this case because binary search tree has such a nice feature all left subtree is smaller than the root node in this case both p and Q the two nodes were trying to find an LC A4 they are both exactly smaller than the root node so we know if an else in a exists which this problem assumes it always exists is going to guarantee to be existing on the left subtree so in this case what Traverse will use a recursion chord recurs to the left side that means we should move the current node from 5 to root dot left which is 1 here because root is both greater than p and Q so we know it should be home in root dot left Now we move we use the recursion column to move the root node to root dot left which is this one now so now the current root is one and then we do the same thing the same logic We compare the values right so now we compare the values against the current roon which is one using these two nodes one is equal to one which in this case a node is a descendant of itself right so in this case we'll just return root because the other node is guaranteed either on the left side or on the right side of this root node but this root node is a descendant of itself so we'll just return root all right this is one more example another example is that we use the same tree but we'll see how it's going to Traverse to the right side in this case p is 6 and Q is 8. in the beginning we're only given to the axis of the root node which is five now five y will keep comparing 5 is smaller than 6 and 5 is smaller than 8. because of the nice feature of binary search tree everything is sorted we know all of the if this LCA exists for these two nodes it must exist on the right side of this current root node so in our recursion call we need to do root dot right which moves our root node to 7 right now 7 is here is which is our current root node we keep comparing 7 to 6 and 8. so 7 is greater than 6 but 7 is smaller than the other node that we're trying to find an LC A4 so that means we find it this is the LCA of these two nodes all right these are the three possible cases anal also one more fourth case on the base case is whenever we encounter it an empty nodes or a null for example when we try to recurse to the left side on the right side of this zero note is going to be a now node in that case we're just going to return root which means we'll let the recursion to continue to do its work this is the other base case which is we have traversed to this node as our current root node and then root node equals to P so we know if P equals to the root node or Q equals to the root node would directly just written root this is another base case it's not a long recursion column and also one of the color cases with that said we can quickly turn the logic into the actual code about five or six lines that's it let's see so first we'll use recursion to do the job and for any recursion there is always a base case in this case the base case is if root equals to now all root equals to P all root equals to Q in which case we'll just return root as we just discovered it could be the root matches P or q that means a node is a descendant itself or if we encountered a noun node like say that's this node is the leaf node already so it doesn't have any left or right children what we need to do is that we just return the root itself in this case we just let the recursion to continue to pick up where it's left off all right and then we'll take care of root if in that after it has gone through this if case we know none of these three nodes are now so we can safely use dot val to access the value of these three nodes to do comparison if root Val is greater than P dot val and root Val is greater than Q donvale in which case we know the LCA if it is if it exists it must exist on the left side or in the left subtree of this current router right so what we do is we use recursion here root left p and Q in another case which is else if root Val smaller than P dot well and root well smaller than Q dot vowel in this case we know if this LCA does exist and must exist on the right side of the current root node so again we'll just use this recursion and we'll change it to be right in all other cases we know this is the root that which this is the LCA that we are trying to find to return for these two notes what are the all other cases it's basically run is in between the value of p and the value of Q now let me hit run you see if it works accept it I'll just quickly submit this all right accept it yeah this is the entire algorithm and how we come up with this algorithm and how this algorithm makes sense to solve the lowest common ancestor LCA of a binary search tree I hope this walkthrough does make sense um if that's the case please do me a favor and hit that like button that's going to help a lot with the YouTube algorithm and I really appreciate it uh dropping any comments feedback any questions that you might have um I'll check out everything I'll make sure that I read every comments thank you so much I'll see you guys in the next one | Lowest Common Ancestor of a Binary Search Tree | lowest-common-ancestor-of-a-binary-search-tree | Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)."
**Example 1:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8
**Output:** 6
**Explanation:** The LCA of nodes 2 and 8 is 6.
**Example 2:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4
**Output:** 2
**Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[2,1\], p = 2, q = 1
**Output:** 2
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` will exist in the BST. | null | Tree,Depth-First Search,Binary Search Tree,Binary Tree | Easy | 236,1190,1780,1790,1816 |
1,286 | Hello hello everyone welcome to my channel it's all the problem vibrator for combination 100 designer tractor subscribe english letters and number combination like comment subscribe combination length subscribe indian subscribe combination form of channel subscribe tab 2525 vid oo dushman bhi return gift for The Countries In This Problem Is Per Combination Lines Between One 250 In The Year Will Be The Most Difficult Tasks Kids Guarantee The Causes Of The Function Next Valid Sources Of Batsman Virat Call 100 This Is The Class B Happy Designs How To Solve This Problem Solving Is Problem World Record Room First of all will generate all the combinations from the given string so let's also say just ABCD that generate all the combinations of length hair combination institute solve which will be Idris subscribe to this channel Indian 2nd generation from this subscribe to Has 1957 Lexicographic Lee The Order Ki Subansiri Generate Will Stop This Combinations In Tourism Detector List Of You Want Something Which Will Return Every Time From Here Liked The Video then subscribe to the Page if you liked The Video then Will Give The Started 1st 2nd K MD Result Lights Of Spain Team Which Will Vanish From Subscribe Like This Will Start From 0001 To 9999 200 First From Where I Wish I Will Get Also First Index Character Subha Hafta And Inspectors ABC Soft Will Get Liye Information Will Update N X Dash Vikram Vansh Ke Veer Vikram 151 ka dahan after exactly the ball spins Vikram start for connect with two and you will be amazed i will give this vikram 2010 2011 this is our fennel is the combination will be similar i will give you a between candy toffee prelims paper will come Again From Abroad And Withdraw Cases Against Will Surily Be Quick Subscribe To Shyam Channel One Father And Mother Left To Right A Process That Bihar Doing Vikasvar Oil Character Se Seedhi Problem Jo Ladies Sot And Twisting Short And Twisting Subha Aap Roli Creative All Information From Left To right similar how will generate and all the combination and enemy is our combination free combination idea also in lexicographical order delicious also can keep in our latest tubelight phase-iii dowry bc young man youth B.Ed phase-iii dowry bc young man youth B.Ed phase-iii dowry bc young man youth B.Ed first black president subscribe Video instead of subscribe Tutorials Little Bit About How To Generate Combination So Cute Office Treatment In This Thank You To Let's Start Doing His Eyes Give Into The Constructor Was Usually Ships In 9 We Need To Generate All the Channel and Share subscribe and subscribe the Channel Please subscribe and subscribe the Channel Thursday Start Tiger Start End Jaw During This Time Which Software Platform And Definition In College And I Will Give You Will Check Subscribe Will Definitely Give Soft Return From Obscurity Tractors Subscribe Not At All That Generate Method Can For This and start Vikram I plus one from in this phase will guide character plus start a resident of b id m id subscribe The Channel Please subscribe and Share subscribe and subscribe the MP ki anomaly all returning officer implementation let's compile record incident compiling and possibly Watch this video 123 Accepts What is the time complexity of this code so isi next and his next is the time complexity of wave constructor in generating combination there is the time complexity selection list for the spelling of three lord and discrimination and his to 16 track call History of land which gives in the formation of this after a few years in waiting Total 6 possibilities for the time complexity and plus or minus way subscribe to subscribe my video and subscribe Channel press The Bell Icon is festival function for thanks for watching the | Iterator for Combination | constrained-subsequence-sum | Design the `CombinationIterator` class:
* `CombinationIterator(string characters, int combinationLength)` Initializes the object with a string `characters` of **sorted distinct** lowercase English letters and a number `combinationLength` as arguments.
* `next()` Returns the next combination of length `combinationLength` in **lexicographical order**.
* `hasNext()` Returns `true` if and only if there exists a next combination.
**Example 1:**
**Input**
\[ "CombinationIterator ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[ "abc ", 2\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, "ab ", true, "ac ", true, "bc ", false\]
**Explanation**
CombinationIterator itr = new CombinationIterator( "abc ", 2);
itr.next(); // return "ab "
itr.hasNext(); // return True
itr.next(); // return "ac "
itr.hasNext(); // return True
itr.next(); // return "bc "
itr.hasNext(); // return False
**Constraints:**
* `1 <= combinationLength <= characters.length <= 15`
* All the characters of `characters` are **unique**.
* At most `104` calls will be made to `next` and `hasNext`.
* It is guaranteed that all calls of the function `next` are valid. | Use dynamic programming. Let dp[i] be the solution for the prefix of the array that ends at index i, if the element at index i is in the subsequence. dp[i] = nums[i] + max(0, dp[i-k], dp[i-k+1], ..., dp[i-1]) Use a heap with the sliding window technique to optimize the dp. | Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue | Hard | null |
92 | Hello everyone welcome, you are going to do video number 17 of my channel. Okay lead code number is 92. This is a medium level question. The name of the question is reverse link list. If you are ok then see, this is a medium mark but actually I will solve it for you in any way. I will teach you how I solve such questions, it will become very easy, then okay, I always tell you that I make the diagram first, it is okay in the linky description and I make the diagram, then what changes have to be made, I will tell you. Let's take these two notes, it will go here, first do it and then write the code accordingly. Today you will know its importance, how important it is to solve the problem of link from diagram in general. If you go and watch the video or even the story in the tutorial, they will tell you that yes, this is a note, do its painter here, do its point here, do it like this, but I never tell you like that, I will never tell you the reasoning of everything, why. We got this point pointed to this point, there should be some reasoning behind where the note is going from where all the link lists are going, okay just writing it won't do, okay let's move ahead, the question is very simple, I have given you a link, see. Here a simple link has been given and it has been told to you that one has given a left position and one has given a right position, it is okay and you have to reverse all the notes between left to right like I did here. But look, this is the first note, the second node is the third, fourth and fifth, the value of left is two, the value of right is tax, the value of left is two, do you know what is the meaning of this first note, this is the second note, okay, so this is my second note, then the third note. Chauth note, this is my Chauth note, okay, so look, it is left, this is equal, you are right, this is equal, you are four, so this is left, this is right, okay, so if you want to reverse all these notes, then what? After one will be reversed, then four will come here, 3 then 2 will become 14325, look at this 14325 and so on, the questions are simple, so simple, now just understand how we can do this in the best way, today I will tell you the method. Now today I want to tell you the importance of making a diagram, okay I will tell you, I will not tell you, but first of all, it is a big conjuring thing which you generally see in many solutions and people do it. But very few people tell its reason, I understand you whom I am talking about, you must have seen the solution of many links, people make a separate dummy note, by doing this the dummy note is equal, you have made a new note and put some value in it. Given minus one or zero, you have to enter it, okay, then you know what do next n of the dummy, put the value of head in it, mother takes this link, its head is this, so what did I do, there is the next point right there, this is of this head. Value has been entered here, value of head has been entered. Okay, let me tell you the reason, why is this done, why do people do this in general? Look, pay attention. Whenever such a question comes in which you feel that your head can also change. Any such question in English like Maa Lo, if the value of left was one and if you have to reverse the value of right then look here the head is changing, here the head is changed, brother, it will come here, still there is change here again. Okay, so whenever such a question comes that the head is changing, then I know what we do. Look, one way is to make a dummy note without any other method, you keep track of which brother is the actual head, when your Any solution, what should I do? Return dummy's next is always pointing to what? It is pointing to the head of this link list. What will be its head? Okay and why did we do this because we know that if the value of left is one. If this is done then the head will also change. It is okay if done in reverse. Only region is okay. There are many other ways to do it. The butt dummy note that people make is a very good way. Okay, so we will do the same. I just wanted to tell you the reason that we keep the cute land and we generally keep it, till now it is clear, so okay, this one, we have learned it, yes brother, now we will also do the same, okay, so what did we do with it, next I head. Okay, I will write this equal to you head, so when my solution is finished, then to whom will I return. Return is the dummy's next. I am telling him that it is important to understand the story that I will tell you. See, I have taken this example. He said that if you have to hit reverse from 2nd note to 4th note, then what will be its output, see, it will be ADCB, neither will the middle one change, nor should it be pointed in future, so that means I am standing here. I will have to stay right, so I am the previous mother, okay, and from where I have to start the reversal, my hand should also be there, so there I am staying with the current painter, okay, you should understand, I will tell you again that it is obvious. It's a simple thing, see, this part has to be reversed, so for this part here, you will have to hire a painter, name him whatever you want, I have named the current, okay who is the current pointing to, yes the part has to be reversed. It is okay to first point the note, whatever note was there before the current one is pointing to it now, but later it will point to someone else, that is okay, so obviously you will have to stand here and here too so that it can be changed into a painter and get relief. Okay, so these two points are going to come short for me, so first of all we will have to bring the previous till here, like mother, take an example, if mother takes this relief, then it is obvious that if you have to consider the relief as reverse from here to here, then it is obvious. I will bring the previous one till here, first of all, this is the first one, this is the second one, this is the third one, this is the fourth one, that is, from the third note to the 55th note, if you want to hit the reverse, then you will have to bring the previous one till the second note, this is the second one. The note is this, you will have to bring till then the previous one, next I will take the current mother. Okay, if I am cleared till this point, then what will I do first. I brought the previous here and brought the current here, what is current is that part, that is that. The non is from where the reversal part is starting is fine and the previous one will be the note just before that. Okay, so now you must be knowing the importance of why dummy note is necessary. If mother take, if mother take, let me do the reversal from here. If it would have happened then it is fine, I am saying that if the reversal had to be done from here instead of from here then Ishq, what would have been my current would have been this, then whom should I keep, brother, whom should I keep, how would I keep the previous in the dummy, that is why the derm is here. It is also less and till here, let's make it first because there can be a change, if earlier they were asked to reverse from the note, here we have to do the second one, okay, so this is my current and this is my previous, okay till here. So it must be clear that I have come to know that the notice of the part which is to be reversed is first done by doing its notice and the notice of the one which is just previous is correct then see how to reverse it, first of all we have to see that let's go Look, A is its place, A is happy, it is fine, after that look, what am I seeing first, I saw B first, after that came C, which is wrong, right, if you look at the answer, first C was A, it should have come after that too, I know. First there is A but now we do n't see it, first in front of me is the first I am looking at that, in front of me there is B and C, I saw that first B was A, then again it is A, which means it is messed up here already. Right should have come even after that, so we have to fix this first, then we will go ahead and fix the DB, first let's solve the problem that is in front of us, so first of all see what seems to be my biggest problem, after brother C. It means that if C had come here, then I would have been happy, because I should have come after this also, so see what I would do, what does it mean, if C had come here, then A would have been the next C. If it happens then B would have been right, so I know what I will do, I will tell A that you will start pointing at C because Idli is on you, who should have come to you, that is, who should have come before this and after that too, so I told the previous What did you say to the previous one, you should change your next, what should I do, make it equal to the current next one, then see if I changed the previous one's next, instead of doing this, I got the current one's next one pointed to. The line is cleared, first line was mine ok now after this see what was the second problem, first problem I solved that brother after A I am seeing B here after that C is A but first C came after that. It would have been better if you had given it, that's why I said that brother A, you have already pointed to C and made the previous connection, so after A, C went to A. Okay, now look, after A, C went to A, but after C, B should come. That was right because look, after C, there is B, but here after C, there is D, so we have to change that is, we have to change the next C, so I have to write, C has become the next of the previous one. Next we have to change whose net we have to make equal to and B. Do you remember what was the next of the previous? B, but now connect the previous. Look, it has been changed in step one, that's why what will I do? Do n't store the next of the previous one and keep it. I will take what I did, I stored the next one of the previous one, this is my step zero, okay, the previous connection is in a mess here, it is visible that look, after A, C will come, after C, then after B, C will go, this is a cycle. A cycle has been formed here, right, so what will we have to do, we will have to break this cycle, that means whoever is on the current painter, his painter will also have to be changed, right, then to whom will his painter be pointing, it is obvious that this cycle is You will have to take it out. Okay, who is out of this cycle? Di is mine, she has given me the narrowest reachable di, so di has to be pointed, what I am saying is that the current will have to be changed to the next one, di has to be equal to the right but pay attention. Current's next to whom to make equal to di and di's, remember what was earlier, what does it mean that before changing it, do the current's next's next here's ok, current's sorry ok, this should be my step you. Cannot be done later, I am removing it from here, after that what happened to the previous connection current next means this cat's I got the point pointed to di, it is fine, it is solved, after B, di A. Look at the last one, what did I do with the previous one, the next one with the next one, what is the next one with the previous one, C is the next one, so I pointed to B. Till now the problem has been solved, okay, so look, our problem is not completely solved yet. Our problem has been solved so much that it was shown to us in the beginning. What was our problem in the beginning, brother, still we have solved that problem, now repeat the same steps from the beginning, otherwise the further problems will also be solved. It will be done, okay, now see how it will be done, as of now, how is our link list looking? First there is A, after that there is C, this was the previous one, okay, after that it is C, right we because ours, look, it is like this. Na after that, what is there after C? What is happening right now, after this is what is happening right now, my status is this, okay, now I will apply these four steps again on this, see how it will reduce the IT bill, that's why I said that first of all, the problem of starting once. Now I have solved the E problem. Follow the steps in the next problem. See what will happen. I have stored the next of the previous in the temp. What is the next of the previous. So, I have stored the C in the temp. Okay, pay attention to this. Okay, the previous one. What is the next of the current? What is the next of the previous? What is the next of the current connection? Next of the previous has been made equal to the current connection. Now look at the answer, you will see it divided. What is the next of the current? Next of the current. What is the next of the current? Next means this, look now, next connection of previous is equal to 10, meaning of previous next sorry temperature, pay attention to this now, our solution has been found, see what is A after A, Di A is after Di, C is C After B, after B, there is A, and this was also our solution. Look, okay, so two things, I want to repeat to you, two things are most important, that is why we have done the next to the previous, from here to here, sorry, to the next to the previous. It was made equal to temp and not equal to current. Remember this was the next of the previous one. Why was it not made equal to the next current. Actually it was the next of the previous one and the current is also the same so why was it not made equal to the current. Because look here, that thing does not reduce, if you had connected the next connection of the previous one, it would have started pointing to B whereas the previous connection would have been wrong, it is fine till now it has been cleared, first thing is that the reason of everything should be known, second thing you should pay attention to. Given, how many times did we do this operation? How many times did we do it with these four? Only twice, only twice. Now see why we had to do it twice. Understand why we had to do it twice. Look, pay attention. We were asked to reverse from where to where. From the first note to the tax, from the first second note to the first note, how many painters are visible, brother, if two painters are visible then it means that there will be a diamond exchange of 2 painters mostly. Okay, so what does it mean that we are doing these four steps. How many times will we right - you will right times? I will right - left hand twice. Okay, - left hand twice. Okay, - left hand twice. Okay, we do not visit any note multiple times. We are visiting the entire English only once. Okay, so I. Hope it is clear to you have to do this step only, okay let's finish it by coding quickly, so we have almost written the code, let's finish it quickly, okay, so first of all friend, I always do this Always check if the head is equal to this is equal to null or the next of head is equal to this is equal to null. What does it mean to know that either the empty link list is empty or there is only one note. He does n't pick it up even after reversing it, so how can I return the head till it is clear, after that remember I told you why we are taking dummy notes, it is okay, it is necessary, what will we do in the end? And where to take the previous one, remember I told you to take it equal to one i, take it from the left to the first one, na i plus, till now it is clear, now see, you have to do the same by doing the same, only i plus. I have explained to you why we will store the Sorry Previous K Next in the stamp. After that, according to the diagram I was making, I had equated the Previous K Next to the Current K Next Sorry Previous K Next. Bill be equal to current connection, did you understand this thing, this was my step zero, this was my step one, after that remember the current's next, bill be equal to current's next is ok and now the previous's next to next is this. Equal tu 10 these 10 which we stored above we wrote these three tax steps na we just in the last what we had to return domin's next ok submit let's see if you are able tu pass which d test cases and we I have understood the reason of each line, date is more important question, it was not too much, you could have done it even with very long code, is n't it, by handling it, but this is the cleanest code, I thought it is ok, any doubt, comment area, next video thank you | Reverse Linked List II | reverse-linked-list-ii | Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], left = 2, right = 4
**Output:** \[1,4,3,2,5\]
**Example 2:**
**Input:** head = \[5\], left = 1, right = 1
**Output:** \[5\]
**Constraints:**
* The number of nodes in the list is `n`.
* `1 <= n <= 500`
* `-500 <= Node.val <= 500`
* `1 <= left <= right <= n`
**Follow up:** Could you do it in one pass? | null | Linked List | Medium | 206 |
303 | hello guys in this video we are going to discuss problem 303 from lead code which is the range some query immutable so the question is pretty simple given an array of integers like this we are to find the sum of elements between any two given indices so we are given in the index I and J and we are guaranteed that I would be less than or equal to J and we have to find the sum of all numbers from index I to index J inclusive so in the example test cases you have 0 2 which is this is index 0 index 1 and index 2 if you add these numbers up you get 1 similarly from index 2 20 X 5 0 1 2 3 4 5 so it's this part of the array 3 plus -5 is minus 2 plus 2 s 1 is minus 1 plus -5 is minus 2 plus 2 s 1 is minus 1 plus -5 is minus 2 plus 2 s 1 is minus 1 and so on so the thing to note here that is the array does not change and there are many calls to sum range function so the brute force solution here would be to just in the sum range function we would just go to index I up to J and keep adding the numbers from I to J but however they say that the sum range function will be called many times so we should probably make use of that fact to optimize the code in here wherein for example if we are called with the same I and the same J twice then we should just be able to return it in hole one instead of recomputing the whole thing so let's say we had an array of like a thousand elements and we frequently get inputs like I equals two and J equals 900 every time it is called we're going to be i trading from two to nine hundred and summing it up which is not efficient so what we're gonna do is find a way where then we are able to reuse the previous results and make it more optimized so the approach that I'm gonna go with here is to use a prefix sum and pre calculate the prefix sum and use that pre calculated prefix um to return this so the way that's going to work is we are going to calculate the sum from element zero to every other element and the way we're gonna return ranges is going to go it's going to be the prefix sum of 0 to J minus the prefix sum of I so for example sorry of J by definition its 0 to every other element so for example in this case summing all the numbers from index 0 to 2 is 1 and summing all the numbers from index 0 to 5 is 1 plus means 1 minus 6 is minus 5 plus 2 is 3 right so then 1 minus sorry I might have miscalculated that so let's see minus 2 and 2 cancel each other out - 2 1 - 1 year minus 3 so from 0 to 2 we - 2 1 - 1 year minus 3 so from 0 to 2 we - 2 1 - 1 year minus 3 so from 0 to 2 we have yeah from 0 to 2 sorry from 0 to 1 because we have to include 2 in the Sun so we the I here is actually gonna be I minus 1 so it's gonna be the prefix some of J minus the prefix some of I minus 1 so then you go from 0 to 5 you get all this and then you subtract 0 to I minus 1 so then you're left with this right so 0 so that the whole from 0 to 5 is negative 3 and then we subtract this part which is negative 2 so we end up with negative 1 which is what this answer is so we're gonna use that idea and implement so since we're using a minus one there's one edge case we need to consider if I is 0 right so if I is 0 we're gonna end up doing prefect sum of negative 1 right and what we want that to be is simply 0 because like if you get the sum of the 0th element inclusive it should just be that element right so that means we want the previous thing of this to just be equal to 0 so that we don't add anything to it so I'm going to go and implement this so we're however gonna store the prefix sums are in a hash map when the key would be the index and the value would be the prefix um so here we're gonna store a hash map of integer to integer prefix sum and here we're just going to return prefix some get gay - prefix some get I minus one so this would be a oh one lookup and we can keep calling this and this code here in the constructor would only execute once and what we do here is we going to initialize the attachment and then we're going to go like for each element in the mums array for each element in B or actually we need the index so we have light break so what we're going to do is for each element in this array we're going to have a running sum so let's see our sum would be equal to 0 and then we're going to make it sound equals now I so we're gonna keep adding the Sun each elements as we go and we're gonna insert the Sun up to that element into the hashmap so we're gonna put I and so on and we need to take care of one place which is this one so before we initialize it we're gonna put negative 1 0 into the hashmap yeah so this solution should work and the only drawback is that we actually go ahead and compute everything even though if it's not needed so one optimization that we could make is only insert it in the hash map so we try to lazily we look in the hash map and if it's not yet there then we compute it but that would be a little bit wasteful since you'd have to go and look if you've already had a previously computed value so for example if you're trying to find the prefix sum of like 900 and you already have a prefix and then the next time you get like a prefix sum of 8 9 and if you lazily computed you're gonna go from 900 to zero and then next time you're gonna go from eight nine to zero when you've already been there once so then you can't kind of optimize for that case so potentially you'd be doing a lot of going through the same array so unless you try to find a smarter way like if I get 900 then you look around if you've seen eight nine or if you get eight nine you look around if you've seen eight nine eight or nine hundred and just add one or minus one but that could get really complicated so I think this solution is a little bit 'space and sent intensive a little bit 'space and sent intensive a little bit 'space and sent intensive and there's all the work upfront but the calls to the sum range function would be optimized as this would just now be like an o1 lookup so let's run this code or it compiles okay so the result is the same that's submitted all right we have a pretty good result so yeah that's all for this video I hope you enjoyed it and I'll be look out for my other leave code videos | Range Sum Query - Immutable | range-sum-query-immutable | Given an integer array `nums`, handle multiple queries of the following type:
1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`.
Implement the `NumArray` class:
* `NumArray(int[] nums)` Initializes the object with the integer array `nums`.
* `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`).
**Example 1:**
**Input**
\[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\]
\[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\]
**Output**
\[null, 1, -1, -3\]
**Explanation**
NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
* `0 <= left <= right < nums.length`
* At most `104` calls will be made to `sumRange`. | null | Array,Design,Prefix Sum | Easy | 304,307,325 |
76 | okay so today what we're going to cover is a fairly challenging question which is called minimum Windows substring so what am i given I'm given two strings I'm given a search string or a string s whatever you want to call it this is the string that I'm going to need to search in and I'm given a character string a string consisting of a certain amount of characters right but this is what all I care about do you see these counts right here the string has 1a it has 1b and 1c and my job is to find the smallest window in the search string that has at least all of these characters in their respective amounts so what the answer is you see is this substring right here the substring that says B a and C do you see how it satisfies one a it satisfies one B it satisfies at least one C it could also be this do you see how I added to C at the end but the problem is that yes we have two CS and yes it still satisfies but it's not the smallest window that satisfies that window that you see satisfies but this window also satisfies and it's smaller so what we're looking for is the smallest window that satisfies this character chart mapping however you want to call it so first let's look at the brute-force approach let's look at the brute-force approach let's look at the brute-force approach which is a sort of complete search to this which is probably the first thing you would think of and I'm going to decompose it and walk you through exactly what it would look like okay so what I wrote for you here is if you did a decomposition of every single possible window what would that look like so this is a form of a complete search on the whole search space which is every single window and this is a valid way to do it's a very inefficient and very bad way you would never settle on this solution but this is something you could jump to immediately if I want to find the smallest satisfiable window try all the windows and take only the ones that satisfy and find the smallest of them so here we have the decompositions if my left equals zero I have four windows that can be like that if my left equals one I'm going to have three possible windows if my left equals to two possible windows and if my left equals index three that's the one possible window so let's look at each of these windows these are all the windows we wanted we would just do some sort of double for loop the code is in the description for this approach and the optimal approach code in the description and well you can see here is each of these windows we would have to check is it satisfying the constraints so what is our constraints that's our constraint the character t1 occurrence in my window all I want to do is ensure is there one or greater occurrences of T then that window satisfies so we see here first one does that satisfy no it doesn't second one does it satisfy it doesn't and then the third one does it satisfy it does not and then the fourth one does it satisfy and we see that it does have the character read one yes it does satisfy and now let's remember the best we've done is for length four okay so we kept note of the best so let's keep going does this satisfy no does that satisfy no does this one satisfy yes what's the length of this three does it beat the best we've done yes it does update our best okay and we continue now our left we plant it at 2 and we explore all the right windows so now hey does that satisfy no 80 does that satisfy yes it does did it beat our best yes a length of 2 so it becomes 2 okay and then we have just the left of 3 and then just this string so does this satisfy yes it does it beat our best yes and in reality the way the code it does it in the description and the way you would actually do it you would keep the left and right boundaries of where you found the best so you could chop a substring and return it to your caller so that's just a detail but this is the brute-force approach right this is the brute-force approach right this is the brute-force approach right we go through all the windows but - in we go through all the windows but - in we go through all the windows but - in order to see the problem what we need to do is do an analysis on this approach so let's analyze why this is a less optimal solution and see how that leads us into the way of thinking that brings us to the final optimal solution ok so to see how bad the solution is and see where the duplicate work is remember when we're optimizing an algorithm we think of the bottlenecks we think of unnecessary work and duplicate work this is not my own thing this is from cracking the coding interview so why don't we find where we're duplicating work and if we can find that maybe we can use some auxilary space to improve the time you know what I mean so if our time is high maybe we could lower the time by increasing space keeping auxilary data that lets us have more information during our search so we don't go back and investigate things we've already touched so we're gonna do is we place our left on the first window and we're also going to place the right on this first indicee and i want you to notice how many times has each of these indices been touched so what we're going to do is just loosely look at how many times do we conduct a window search at any given write boundary or any given right planting so right now we're gonna check the window from left to right which is this window so that's one window search conducted at this boundary and then we're going to advance again and then we're going to do another window search and then this boundary has been touched again and we'll increment this number right here and then now our right pointer sits there we're still exploring with the left pointer in an index zero so this window right here entails another search and we're willing to say that we've done another search up to ending at this index another time so we increment that and we'll do the same thing right here for the tea so now the right pointer has exhausted itself and we need to increment the left pointer and reset the right okay so now what we're gonna do is we're gonna do another window search with our right ending right there so let's increment how many searches ending at this index have happened so we'll increment that one to a two and then let's increment this because we do another window search increment that and then we also increment right there the right has exhausted itself we move the left forward we do another window search ending at this right boundary so we increment that to three and then another search increment that to three and then what we do is we do another search so increment that to four and then we do another search at this right boundary and increment that to four so what do you see here what you should notice is how much we're duplicating work how many times were Reaper forming searches with our right bound ending at these indices at this indicee when the right bound ended there we did one search we did two searches total with the right end to see ending there we did three searches for searches so that's a problem why are we repeating looking at the same elements these same characters when we don't have to do that if we actually looked at an in-depth analysis actually looked at an in-depth analysis actually looked at an in-depth analysis of this what we could do is we could provide a lower bound for how much work we're actually doing so this is how we can lower bound at the least work we're going to do okay so we're going to do a lower bound which that's the symbol for lower bounding big Omega it's the same thing as Big O except Big O does an over bound and upper bound and big Omega does a tight lower bounding I don't know how tight of a bound this will be but let's continue with it anyway so imagine we want to lower bound this so how many left points can I choose well I can choose and left points if n is the length of the search string so let's just say I can choose n ending points okay we have end points where I can put in L like this like that and like this so as you can see if the length of this is n so let's write that we can do that n times you can choose and left points so if I plant myself at a left points how many right points can I explore at the first iteration how many right bounds can I explore well I can explore n right bounds so let me show you that like that right there this and that so that was four right bounds we could do so why don't we plant the left at the first in to see the next one how many right boundaries can I plant one two three but three is a fraction of this but what we're going to do is we're still going to be doing an upper bound of and work we're still going to be upper bounded by the length of this string in terms of right points I can choose so let's express that right here as an upper bound of the right points we can choose so we're upper bounded by N and I honestly don't know how formal of writing this is I don't even know if you can actually do that but it makes logical sense we can choose and left bounds and for each of the N left bounds how many right bounds can we choose were upper bounded by the length of the array so that's an upper bound of N and when we have this upper bound of n in the worst case we will have and right boundaries we can choose when L is right sitting right there so does this make sense and left points we can choose and an upper bounding at each of those left points of and right points we could choose and again it will be a fractional component if L is over here I'll have a fraction of n that I can do for my right boundaries so what does this become what does this lower bound us two we know the least work I'm doing here I'm not even worried about finding whether that window satisfies the string I'm not even worried about seeing whether this matches against the string that would take linear work and if you check the code in the description it does take linear work with respect to each string but what you see is that the least work I can do here is N squared and work so if you're in an interview it's a good idea to analyze this tell your interviewer well I don't know how to optimize this right now but let me tell you the least work this will ever do let me tell you the upper bound of work it would be fairly easy to give the upper bound but I think it's more exemplary of seeing the lower bound so that we know that maybe this could be done in linear time right so this is the least work we would ever do this is a loose lower bound on this so what we can do now is we can see how do i improve the way that I'm doing this so it takes a little case analysis to actually see it and that's why this problem is considered hard because it's not the most intuitive thing but when you see it makes sense so what we need to do is we need to take an intellectual leap and what we need to do is let's plant a left and right pointer right at the beginning of the array we've been using pointers the whole time that came intuitive to us we already know how to use two pointers but what we're gonna see is two pointers can actually bring us to a linear time solution with respect to both strings so what we're gonna do first is we're gonna put a left and right pointer here so what I really want to show you is how can we get to this understanding without having seen it before because if what I'm about to show you is fairly it seems obvious when we see it but in a high-pressure situation see it but in a high-pressure situation see it but in a high-pressure situation you probably would not come up with it but how can you think about it the way in an in a natural way right so we had our pointers before we've been doing that and what we want to do is find a window that satisfies this guy right here so what I'm going to do is I'm going to try to expand my window what the heck why not try to expand this as far as possible until I satisfy these requirements so why don't I move this forward and again this is in the description the code is in the description commented fully so that you can walk through this walk through that but either way let's walk through this so does this window right now satisfy again we're using pointers just like before it does not so what can I do well I can add a character how do I add a character do I move my left backwards well I can't go backwards well why not move the right forward so let's try that let's move the right pointer forward and add on this character so what I just did is I added a character on so okay I have two choices here I can keep moving my right points or forward or I can move my left pointer forward but would it make sense to move my left pointer forward this window does not satisfy so if I moved my left pointer forward it would make it even worse it would not help me satisfy right so what that tells us is I need to keep searching my left is fine my left is just sitting there I need to expand my right pointer until I satisfy and then I can worry about minimizing and then I can worry about that but first all I care about is satisfying my constraints my requirements so let's satisfy the requirement so let's move right forward again does that satisfy we see that it doesn't so we're going to continue on moving right forward now does this satisfy and we see it has an S it has the Z that we want so this window does satisfy so what do we take a note of the indices so we would take note of zero and we would take note of three zero one two three but I'll just write the string okay so this window satisfies but my problem does not ask for the window substring it asks for the minimum window substring so my window satisfies write and if I keep expanding it will keep satisfying because if I keep adding characters I already know what I already have is satisfactory it satisfies if I keep adding characters I'm just getting longer I'm getting farther away from the answer so what I should do now is now our branching goes back to the left pointer so okay I know I could move the right or left but it would not benefit me to move the right now if that makes sense before the Left who would not benefit us now the right has no benefit to it because we have the window we want so what we do is we will move the left pointer inward and we'll see does the window still satisfy if it still satisfies then that's great we beat this string and that's our new answer so that's kind of how this is going to work so at each point we're considering what is the most beneficial choice for me should I move the left or the right at this point we should move the left so let's move the left to one inward does this window satisfy Z and an S Z N and s it satisfies so what we do is we can shorten this that is our new answer so what I'm going to do is I'm going to try to move inward again does this window satisfy no it doesn't we're missing a Z so what we need to do is we need to make a choice do I move my left inward or do I move my right outward left inward will not benefit us we're right back to square one because this window does not have what I want if I move left in I'll continue to not have what I want so what we need to do is we need to move the right forward and put us into the possibility of satisfying move ourselves forward in progress right so let's move the right forward we see the window is still missing a Z move right again we're still missing a Z move right again and now this window satisfies but it's longer than the best window we've had I don't really care about this window so now that we've satisfied let's try shortening it and let's move the left pointer because this window satisfies we want to shorten it so move the left inward this window is still satisfiable but it does not beat what we already have so what we do is we are going to move left in again okay and now we see that this window is missing an S so we need to expand again so expand the right pointer ok the window is still missing it s so expand the right pointer and now the window has everything we want this is satisfying so right there it's longer than what our best has been so we don't want to take this but what we do want to do is try to shorten this and keep it satisfying so let's shorten it by moving L in the window still has all that we want and now we have this but it doesn't beat our string and now let's move L in again ok and now we see ZTS okay we satisfy the s in the Z we're good but this is the same length as this either could be the answer so we just move left inward again because these are both the minimum length so we move Elin and now we're right back to square one we're missing a Z and we need to move right forward so let's move right forward we need to satisfy now and the only way we make advance progress towards that is by moving right forward so now let's move the right forward and now we see I'm out of characters that can put me into a position to satisfy the requirements and therefore my search is over and that means my answer sits right there that is the answer because what we did was at every single step we made a decision what is the best choice for me if this window does not satisfy I need to keep moving this way if my window is already satisfactory I want to minimize by moving my left inwards as soon as the window stops satisfying my requirements I'm back to expansion and that's basically how this works that's how the two-pointer approach works there's a two-pointer approach works there's a two-pointer approach works there's a tiny tweak and optimization you can make which is explained in the LI code solutions but this is the basic approach to this problem and why don't we do an analysis of how this improve what we saw before so let's try that right now okay so let's do what we did before with the same string and let's see how many searches we do at any certain indicee so let's put my left and right so what I'm going to do is I'm going to do work at this window position so let's put a 1 there and I see that this does not satisfy so I move right forward and then we would entail work at this positioning as well so what we would do is put a 1 there and then we see this window still does not satisfy and we move forward and again we mark 1 as doing work at this window and then we move right forward and we see now we have a winning window and we did work at this indices so increment that to 1 ok so now our job is to retract the window this was our best answer but we'll try to bring left in so let's bring left in words so what we're going to do is we're going to bring left in so let's do that so we brought left in and this entails more work so we're gonna increment that ok and then we'll try to bring left in again and we're still satisfying and let's increment the work done there right now and then we're gonna bring left in again and then that's going to entail more work and another check so this is a rough mounting of the amount of times we're gonna do work at any certain indicee so this is much better than what we were doing before what were we doing before is many touchings of a certain indicee and doing much a lot of work at each of these indices but as we see any indices at maximum can be touched once by the left pointer and once by the right pointer so that's what this solution provides to us it tells us that any element is never going to be touched more than twice so that is the key to the solution and what keeps it linear in time so let's look at the time and space complexities for this so it's a lot more straightforward to analyze the time in space when you see the code and the code is in the description you can look there but we can actually conceptually just think about this so the time complexity as we saw the traversal itself is going to be linear in time any single indicee can only be touched at maximum two times if we go all the way down with the right pointer and come all the way to the right pointer so what we see is that entails a linear time the amount of work we do is going to scale in a linear fashion as the input gets very large with our first approach what we're going to do is for every left boundary will have even more right boundaries to do and then that's why that's N squared work instead of this being linear in work so what we also need to take into account is the hash table I had right here takes time to build and it would take the length of T the length of the character string t to build that hash table that requirements hash table so it would become the traversal time plus the time it takes to build a hash table for the time complexity and then the space complexity is going to be O of s plus T here's a worst case we need to consider if every character in T is unique we're going to have T hash table mappings every single character will be a map to one be map to one see map to one and they're just going to have a key for each of these characters so in terms of when would we have s but why is s in here as well as we're keeping our running window as you'll see in the code we need to keep how many characters are in the certain window we're considering so if you see this example right here we would need to do the whole string as our window if the window is ever the length of the whole string s and every character is unique as in this case right here then every one of the characters in s is going to have a hash table mapping so that's why we get S Plus T for space and AZ plus T for time and those are the complexities and the explanation for them so that is all for this video if you liked this video hit the like button and subscribe to this channel I want to build one of the world's largest platforms for software engineers to learn because we need more resources we need more clear explanations to these topics that are often not intuitive and not easy to understand and if I made any like small mistakes I probably had it off by one or something just let me know in the comments I know there's going to be mistakes because I'm doing so many problems and I can master every single one but I'm okay with that as long as I can cover more problems so | Minimum Window Substring | minimum-window-substring | Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`.
The testcases will be generated such that the answer is **unique**.
**Example 1:**
**Input:** s = "ADOBECODEBANC ", t = "ABC "
**Output:** "BANC "
**Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t.
**Example 2:**
**Input:** s = "a ", t = "a "
**Output:** "a "
**Explanation:** The entire string s is the minimum window.
**Example 3:**
**Input:** s = "a ", t = "aa "
**Output:** " "
**Explanation:** Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
**Constraints:**
* `m == s.length`
* `n == t.length`
* `1 <= m, n <= 105`
* `s` and `t` consist of uppercase and lowercase English letters.
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time? | Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.
L ------------------------ R , Suppose this is the window that contains all characters of T
L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T
When the window is no longer valid, start expanding again using the right pointer. | Hash Table,String,Sliding Window | Hard | 30,209,239,567,632,727 |
343 | so lead code problem of the day and here we bring the one more solution for you that is the integer break believe me this is the most interesting question we will come across today again we are going to solve this question in three important steps so I highly recommend you to watch till my third step so that you can come across detailed solution and most interesting fact we are going to learn the two important Concept in this question so stay till the end of the video and just in case if you're new to our Channel I request you to subscribe our channel so let's get started integer break so what does this question says that we have given an integer n and we need to break that integer into K positive integer such that my K should be greater than equal to 2 and when we divide that integer n into K positive integer we should get the maximum product we can get for example suppose I have five in how many ways I can divide this five so I can have the 2 + 3 = 5 and what will be it have the 2 + 3 = 5 and what will be it have the 2 + 3 = 5 and what will be it product so product will get six again we can divide it as 4 + 1 so it can give us five and it as 4 + 1 so it can give us five and it as 4 + 1 so it can give us five and it would be product what will be its product it would be 4 I can divide at 2 + 2 + 1 is equal to 5 and it product + 2 + 1 is equal to 5 and it product + 2 + 1 is equal to 5 and it product what it product so product is 4 so out of this which is the maximum product so six is my maximum product so I need to return six so I hope so you understood this question here we have given the two so two can be divided as two itself or 1 + 1 so it would be 1 itself only and I + 1 so it would be 1 itself only and I + 1 so it would be 1 itself only and I can divide 10 in number of way for example for 10 I can divide as 7 + 3 it example for 10 I can divide as 7 + 3 it example for 10 I can divide as 7 + 3 it would be 21 I can divide 5 + 5 it can be would be 21 I can divide 5 + 5 it can be would be 21 I can divide 5 + 5 it can be as 25 or I can divide as 3 + 3 + 4 it as 25 or I can divide as 3 + 3 + 4 it as 25 or I can divide as 3 + 3 + 4 it would be 36 which is my maximum product and this is what we got the answer so I hope so you understood the meaning of the question now let's move towards our first step of our solution so let's jump to our first step of our solution so what we took is here I took the number as for you and I need to divide that number in such a way that I get the maximum product so what are the different choices we have I can have 1 + different choices we have I can have 1 + different choices we have I can have 1 + 1 + 1 + 1 + 1 is equal to 5 but its 1 + 1 + 1 + 1 is equal to 5 but its 1 + 1 + 1 + 1 is equal to 5 but its product is 1 itself right again I can have a 2 + 3 = 5 and it's product so have a 2 + 3 = 5 and it's product so have a 2 + 3 = 5 and it's product so product is six again I can have 4 + 1 product is six again I can have 4 + 1 product is six again I can have 4 + 1 whose sum is five but it's product so product is for itself or I can go as 2 + product is for itself or I can go as 2 + product is for itself or I can go as 2 + 2 + 1 whose sum is for but I can get the 2 + 1 whose sum is for but I can get the 2 + 1 whose sum is for but I can get the product as for itself and which one is the maximum so maximum is this one that is six so from this what I can say you can see over here I have took all the ones but I don't have I haven't took two 3 4 5 I haven't took anything if you come across over here I have two and I have three but I haven't took one four and five and if you come across here I have four and one but I don't have two and three and five itself I have two I have one but I don't have 3 4 5 so which means can I say for every single element that I have the two choices I should pick this or I should not pick this which means for every single element I have the two choices that is to pick and to not pick right so these are the two choices I have for every single element now whenever we have the choices what comes in our mind for sure the one word that comes in your mind is recursion because what we need to do is we need to carry out all possible choice for every single element for every element I got two choices pick don't pick so I need to make sure for every single element I carry out all possible choices so for that purpose only one thing that can help me that is recursion so this is the first step we come across that we came to know that we need a recursion right now the second important thing we need to notice over here is you can see that I have took all the ones I have took 2 * 2 which means is it there any took 2 * 2 which means is it there any took 2 * 2 which means is it there any kind of limitation that we have that I can't take one more than one time or I cannot take the two more than one time no which means I can take these elements any number of time I can have 2 I can have 1 I can have two 2 3 1 so which means every single elements can be taken any number of times so can we relate this question to something else yes the one thing that comes in my mind is for sure unmounted napsack because what we did in unmounted napsack is we are supposed to get the maximum profit by taking the item and in napsack also we are supposed to take any item any number of times right suppose these are my items I can pick one any number of times two second item any number of times three any number of times so this is what we need to carry out same way for this question only with a slight modification with slight modification so we came across the two thing over here that is the first one that we need to carry out all possible choices so for that purpose I need a recursion then I need the unbounded nap sa unbounded napsack concept so these are the two important things we came to know so let's try to implement this question by taking the help of these two things that is recursion and unbounded naps act so let's try it so as we are going to look for the recursion make sure that first step that is Express in terms of index what we need to do is Express in terms of index Second Step carry out your task and the third step return your answer return your required answer right so these are the three steps that we need to look while solving this recursion so let's try to implement this so what I will do is I will have the function f was taking as array and what does this array is so I took all the number from 1 to 5 see for example if I have one if say for example I have Nal to 10 then I will take all the numbers from 1 to 10 itself so this is what my AR says it this is my index that is I'm starting from zero and this is my size of an array or the sum which I want so what I will do is I will first decide not to take that element because what we have over here is we have the choices to pick this or don't pick this so first of all I will not pick this element right so I will take this so I will say not take so what I will do is I simply move ahead I'll simply move ahead that is one and Y will remain as it is so this is my index I have moved ahead now again I'm going to pick that element because I decided not to pick now I decided to pick so I'm going to pick that element so for that purpose what I do is I will declare the variable take now I need to make sure that before I select this number has to be less than equal to 5 because say for example my n is equal to 2 and you are deciding to choose the element 3 is it possible no so whatever I'm number which I'm taking to subtract or add in the N I need to make sure that number is less than or equal to N I need to make sure that number is less than equal to n so the same thing I would like to take if my a of I right is less than or equal to n then and then only I need to take so I would say take equals 2 now what I will do is I need to multiply it because what we are asked we need to ask the product so this is what we need to return so in napsack problem what we did is we did the addition but here we need to have the multiplication because we need a maximum product so what I will do is I simply do a of I into again I'm going to call my function a r of I now the question comes should I move ahead now I suppose I have took this element should I move ahead or I can stay over here most interesting fact that is I need to stay here only because I can take one number any number of times there might be a possible that if I take this elements all the time I can get the maximum product or if I take this element exactly one time or move ahead I can get the maximum element so same thing I would like to do is so what I will do is I will simply keep my index as it is and I will subtract that value from my sum so what I will do is I'll simply do is a of n minus one so and finally what I will return so I will simply return the max out what Max take and not take so this is what I will return now we'll go to the B base case now base case we will Shi to say for example currently we are over here okay I came here now I'm taking it out of bond now what I will return say for example if my index is greater than or equal to n then what I will return should I return zero no because if you return zero my product will be zero so I need to make sure I return a valid answer so what I will do is I will simply return one I simply return one because if you multiply one with any number that number remains itself so this is my pseudo code for my required solution so this we did in recursion so I hope so you understood this so let me raas this so I hope so you understood this so what we did is what we did this we started with the index zero then I decided the two option not to pick and we perform the same way even if I'm picking it I'm remaining on the same index because I can take the same element any number of times and this is what we learn in unbounded napsack so I carried out same thing only the slight modification we had that we got a multiplication over here and make sure for this take you initialize to in mean because we need to return the maximum value so I need to declare it to int mean so this is the sudo code even if you submit the recur code it will get accepted it there is no issue for it but we will try to optimize it using the DP because from this we can come across there is a overlapping sub problems because we have more than two functions called so let's jump to my second step let's get C the Second Step that is solve equation using the DP now before we solving using DP let's understand why do we need a DP because in the recursive Cod we saw that there are the two function call that is one and the two and with help of because of these two function call there might be a overlapping sub problems right in order to remove this overlapping sub problems what we need for sure we need a DP and this is the reason why we come across the DP now question come how much DP it would be whether it would be 2 DP or it would be only 1 DP how we will come to know that so from the recursive code we can come to know that there are the two parameters that is index and my y so these are the two parameters that are changing here you can see this my n is changing and here you can see this my index is changing because what we're doing here simply I'm doing i+ one over doing here simply I'm doing i+ one over doing here simply I'm doing i+ one over here so there are the two parameters that are changing so there would be 2 DP right so I hope so you understood how much DP it should be understood with the help of how many parameters that are changing so here two parameters are changing so we need a 2 DP so what I did is what I will do is I will simply declare a DP of two Dimension that is what I do simply in DP of N and all are initialized to minus1 so again going to do is this is Sol by using memorization right memorization so what we need to do is in memorization we keep the recursive code as it is just we need to add two more sentences so we added this so what we did is if the value is called if already calculated for this particular indexes then we need to Simply return because there is no any point calling the function for the same value so we simply return it and whenever we calculate the values we store it in that particular index so that whenever we need that value further we can directly return it rather than calculating it so this is the dynamic programming code using the memoization so if you talk about it time complexity for sure it would be big of n² and my space complexity would be big of n for my functions called plus big of n Square because I have declared the two Dimension DP so this would be my solution for using the dynamic programming now it's time to check the code for both CPP and my Java code so let's check out the C++ and the Java let's check out the C++ and the Java let's check out the C++ and the Java code so let's check out the code this is the CPP code and this is my Java code you can see according to your own convenience so what we did is first of all I have declared this base case so what does it says that say for example my value of in is 2 how can I divide it 1 + 1 so what will be it product so 1 + 1 so what will be it product so 1 + 1 so what will be it product so product will be one say for example I have three I can divide 2 + 1 or I can have three I can divide 2 + 1 or I can have three I can divide 2 + 1 or I can divide 1 + 1 + 1 so which is the maximum divide 1 + 1 + 1 so which is the maximum divide 1 + 1 + 1 so which is the maximum so maximum is 2 so if I have three I will return two and if I have the two I will return one so this is what I did if my value of n is less than equal to three I will simply return n minus one then here I declared the dynamic programming that is of 2dp I declared using the vector and here in Java I declared using the array that is this one so you can check according to own convenience and here I have filled all the values of DP by minus one and same thing I did over here now what does this array says that as I told you if my value of one is five what I need all the numbers from 1 to five that is 1 2 3 4 and 5 so this is what I did over here if I created an array and I declare all the vales from 1 to Y now I pass this array and my sum and my index as one because I'm starting from one why I'm starting from one because as it is mentioned in the question we can say that we need K which is greater than equal to 2 and this is the reason why I'm starting from 2 because what I'm doing is 0 1 and 2 I'm starting from over here because I need to K which is greater than or equal to k i don't need one so that's the reason why I started with one then I come across the function then I check the base case if my index is greater than equal to N I need to Simply return one because if you return zero what will happen it will give all the product to zero but we don't want a product to be a zero and here using the dynamic programming what I checked is I checked if that value is already calculated or not because if it is not equal to minus1 then which means it has already calculated so we simply return it rather than calling to that function and again I call the two function not to pick this and to pick this but before picking up I check whether that value is less than equal to n if it is then and then only call that function and finally I return that value that by taking the maximum of take and not take the same thing is done in the Java itself so I hope so you understood this today's lead code question of the day or the daily challenge of the day if you want to know more about lead code questions do subscribe the runtime error | Integer Break | integer-break | Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers.
Return _the maximum product you can get_.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** 2 = 1 + 1, 1 \* 1 = 1.
**Example 2:**
**Input:** n = 10
**Output:** 36
**Explanation:** 10 = 3 + 3 + 4, 3 \* 3 \* 4 = 36.
**Constraints:**
* `2 <= n <= 58` | There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities. | Math,Dynamic Programming | Medium | 1936 |
283 | everyone so today we are looking at lead code number two eight three question called move zeros and what we wanna do here is we're gonna have an array and we wanna move all the zeros to the end of the array but we want to do this in place without making a copy of the array so we can't just make a copy of this we have to do this all in place and you can see on line three here we're going to return void so it doesn't return anything we're just modifying this array in place okay so there's a couple different ways to approach this you could use javascript methods that kind of make this easier you could filter out all the zeros then what you could do is you could shift all the numbers to the beginning and then throw the zeros on the end and uh so that's one way you could do it just using built-in javascript methods using built-in javascript methods using built-in javascript methods but i don't know if that's going to work in the context of an interview so another way we could do this let's just jump over here to the conceptual so if we have 0 1 0 3 12 0 1 0 3 and 12. another way we could do this is using a two-pointer approach okay using a two-pointer approach okay using a two-pointer approach okay so we can create a variable and we can call it last non-zero index last non-zero index last non-zero index last non-zero last non-zero last non-zero index and we'll set that to zero okay and so now what we're going to do is we're going to iterate over this array and we're going to have a variable i okay and we're going to check does it not equal zero no it doesn't it does equal zero so we're going to go ahead and move forward okay now we get here and we say does this value at the ith index does that not equal zero it doesn't okay and last non-zero index is going to okay and last non-zero index is going to okay and last non-zero index is going to be set to zero initially what we're then going to do is we're going to set whatever the index is at last non-zero index to the current non-zero non-zero index to the current non-zero non-zero index to the current non-zero number so this will get set to one and then we're just going to leave that one as it is okay and then we're going to go ahead and increment our last non-zero index i is going to our last non-zero index i is going to our last non-zero index i is going to continue forward i equals zero so we don't do anything i continues forward i now does not equal zero so what are we going to do we're going to replace whatever's in the ith whatever the value is at the ith index with the last non-zero index okay so we're the last non-zero index okay so we're the last non-zero index okay so we're going to go ahead and replace this one with a three we're going to increment this last non-zero index this last non-zero index this last non-zero index and then we're going to go ahead and increment i okay and so now what are we going to do we're going to check does the i-th element equal does the i-th element equal does the i-th element equal does it not equal 0. it does not okay and our last non-zero index is at 0 okay and our last non-zero index is at 0 okay and our last non-zero index is at 0 1 2 this is where it's at we're going to go ahead and replace this with 12 and we're going to um we're not going to do anything there and now we're out of the loop okay and so now what we have to do is our array now looks like this it's going to be 1 3 12 3 and 12. and our last non-zero index is going to and our last non-zero index is going to and our last non-zero index is going to be 0 1 2 it's going to be we're going to increment this one more time because we did switch it at the last one it's going to be 3. it's going to be right over here and so now we just do one more pass in this array we start at this 3 and we replace everything with 0. okay so that's the idea behind it let's go ahead and jump into the code before we do that let's just look at time and space complexity so we're making essentially all we're doing is we're making two passes through this array so our time complexity is going to average out to o of n okay and our space complexity we're not creating any more space relative to the size of the input because all we're creating space wise is this last non-zero index variable last non-zero index variable last non-zero index variable and then you know our if ith variables so our space here is going to be constant space so that's actually really good let's jump in here into the code so what we're going to do here is we're going to go ahead and create our variable let last non-zero non-zero non-zero index equals zero and now we're just going to iterate over the num so we're going to say four let i equals zero i is less than nums dot length i plus and what we're going to check is if nums at i does not equal 0 then what we want to do is we want to set the value set that value at i at the last non-zero set that value at i at the last non-zero set that value at i at the last non-zero index at that place so we're going to say nums at last non zero index is going to equal nums at i and then we're going to increment last non-zero index last non-zero index last non-zero index all right so now what we have is we have this array right here but we need to fill in the rest of these with zeros so we're going to go ahead and do a 4 let i equals and we're going to start at last non-zero index non-zero index non-zero index i is going to be less than nums.length i'm going to do an i plus okay and now all we're going to do is just set the value at i to zero and then we just go ahead and we don't even have to return anything we just return void because it's going to be done in place okay let's go ahead and run that and we're good okay so that is lead code number 283 move zeros it's a fun little problem and hope you enjoyed it and i will see you all on the next one | 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 |
714 | hello and welcome to another leak code video today we're going to be doing the problem of the day for June 22nd best time to buy and sell stock with transaction fee and actually in this problem I'm going to go over uh all of the solutions so I'm going to start with the memorization then do the bottom up and then finally do the optimal on bottom up solution and this is going to be kind of similar to my house robber problem that I've done so you should be familiar a little bit with dynamic programming and I'm going to go over the problem okay so we have a prices array where we have one three two eight four nine and then we have some fee and we are allowed to buy and sell stock as many times as we want but every time we sell stock we have to pay the fee we're trying to figure out what's the maximum we can make here okay and so they're saying the maximum is if you buy it one and then you sell at eight right so then you would make seven profit minus two then you would buy it for so buy four for four and then you sell out nine so you'd buy for four and actually be like this so if we buy it four and we sell at nine we would make a five profit minus two and so here our total profit is five plus three which is eight okay so the main thing you have to notice with all these buy and sell stock problems I've done a few of them is pretty much all of them are either Dynamic for I think actually pretty much all of them are dynamic programming and that's because we have a series of states right and basically just like all of these problems just change in like how many states you have like some of them have a delay some of them have a fee but all of them are kind of boiled down to the same thing and then what they boil down to is you have some index that you're in and then you have some other state and in this case so if we're buying and selling stock well we don't really want to obviously we're never going to want to buy and sell the stock for the same day right so like if we buy here we're never going to want to sell for that same day because then we'd make a zero profit so we're always going to want to buy and then sell sometime later so we have to have an index where we're at and then we have to have a some kind of variable to show are we holding or are we not holding stock so let's call that H so like when we buy stock we're going to be holding it in the future and when we sell stock we're not going to be holding and so these are going to be the states for our dynamic programming and it's pretty straightforward if you think about like what we have to do at every state right so let's say we are at some index and we are holding stock well what are the options we have for holding stock we can either sell the stock if we sell the stock our profit is the profit at this index minus the fee plus the next day and so the next day it would just be DP of I plus one and then so if we're holding it we sold then we're not going to be holding right so we'll just call it maybe not NH or something okay and so that's one thing we can do we can either sell a stock or we can choose to keep holding the stock and then check the DP in the next day right so that's pretty much our dynamic programming relationship for holding stock so the other case will just be DP of I plus one and we are holding the stock again okay so that should be pretty straightforward like yeah this is like a pretty simple Dynamic program from like if you've done something you know that should be understandable and so this is going to be and then we try to get the max here right so we try to get the max of these two and then that is if we are holding stock now let's say we're not holding stock okay what are our options and this is kind of what you want to do for DP um you want to figure out like what are all the states we're in and what are all your options for each state and what are you trying to maximize so we're trying to maximize profit which means we're going to try to maximize this if we're holding stock if we're not holding stock what are the options we have well we can either buy the stock right so if we buy the stock then what's our profits profit is negative P of I because we are buying it so we lost some money plus DP you know when you keep going to the next index and now we are holding the stock and then the other option is we just don't do anything for the day and we just go on to the next date we are not holding and we try to maximize here and so that's pretty much the whole DPS you just try to figure out what state you're in are we Holding stock are we not holding stock and then what are the two options we have so we can either do nothing or we can sell if we have stock where we can buy if we don't and our base case is on a pretty sure Ford as well once we reach the end of this P array then what should we return right regardless of if we're holding or not holding stock we're going to return zero because we can no longer buy or sell and so that's going to be basically all for the DP so I'm actually going to code up the top-down problem and then we're up the top-down problem and then we're up the top-down problem and then we're going to try to figure out how to go the next part to the problem I don't want to focus too much on how to code the top down because there's like a ton of you know this is like a pretty straightforward top-down problem so I'm straightforward top-down problem so I'm straightforward top-down problem so I'm going to focus most of my time on figuring out how we actually get the bottom up and then how we get the next uh how do we get the optimal solution so we have a visited here and then remember our states and our DP are index and then if we're holding or not holding so we can just call that holding and so here we need to Define p now what we need to do here is we need to say if the index equals the length of the prices then to return zero because we can't do anything else and then as always if index holding in visited return visited index holding and then uh so now we have our two states right so if we are holding what can we do it's pretty straightforward so we are going to actually that here so if we're holding we can do one of two things right we can either do nothing in which case we just move on to the next index and we are still holding so we'll call that holding and then the other case is we can sell so if we sell what's our profit well it's price is at the index minus the fee plus DP of the next state and now we are not holding so we can just say no now we can just put it into zero right so our holding is going to be a one or zero so now we can even put a one here everyone and so now what are we doing next well let's think about it so our next state is if we're not holding so else and then this is going to be kind of similar as well so if we're not holding then first we can just do nothing in which case we would just pass a zero again right if we're not holding we want to be not holding again and then the second state is we buy so if we buy then we lost money how much did we lose we lost the price that we bought it for there is no fee now and now we are holding and so that's pretty much that now we just return and then we can simply call our DP and so like I said as far as um the complexity of like the dynamic program solution this should be pretty straightforward if you want to say some dynamic programming it's not tricky at all I guess now we just return the DP what index do we started next year and are we holding at the beginning no actually we could optimize this a little bit yeah so let's do that so it's actually optimize this a little bit and let's use a Boolean instead of an integer I guess we save a little bit of space there so let's just say false and let's just say if holding then we could do holding do something otherwise you can do uh holding and we can do not holding it should reverse it I think okay let's try that okay so now we have one solution and as you can see it's not super efficient like so time and space complexity actually it's pretty efficient however just because this problem's been out for a while like the other solution does a lot better and so let's think about what that would be like and let's see the timing space for this one so here the time is pretty straightforward we have how many states we have index times holding state so that's going to be length of prices let's just call that P times two because holding can either be one or zero so that's just going to be o of P or o of N and then space is also going to be o p r o then because it's going to have index times holding states where holding can either be zero one now the nice thing is we're actually going to do the bottom up here and what we're going to do is for the bottom up it's really easy to tell the space and time because you literally have a raise and so you can just say like okay if I have one-dimensional like okay if I have one-dimensional like okay if I have one-dimensional array then like I know I'm I know on Big O of N and so on or for this it's a little bit trickier so definitely when you do the bottom up it's a lot easier to do the space and time so we can actually do by looking at this code right so let me uncommented actually so we can actually do it at this code is we can see this recursive State and we can actually build a bottom-up solution using these exact bottom-up solution using these exact bottom-up solution using these exact like ideas like as you can see that something at State I takes the items at State I plus one right it just takes the max of the two things that state I plus one so we can literally do this the same way as we did this only now we could use arrays and so we could use arrays and we can have an initial State and that's going to be pretty straightforward all we're going to have to do is we're gonna have to make two arrays right because we have a holding and a not holding so we're gonna have folding equals an array and this is going to be length prices plus one and then we are also going to have a non-holding array which is going to be non-holding array which is going to be non-holding array which is going to be the same thing and the thing you want to notice is our base case is going to be when prices is out of bounds that's why we have this plus one so when prices is out of bounds they're going to both be zero now we just simply go from the end to the front and we just use this exact pretty much this exact code to make these two arrays and that would be the bottom up solution so let's do that so it's going to be for uh I in range length of prices and then we're going to be going backwards here right let's bottom up so minus one now we just do folding equals we can literally copy like this code and just change instead of DP we can change it around a little bit right so what is this going to be so for holding this is just going to be holding at the next index that's going to be one and then it's literally the same thing right so if we're holding we can sell and then this is going to be not holding at the next index so that's literally the bottom up and then let's we have to do that for the other one too so and we're literally going to copy this code again and like I said it's pretty much the same thing so instead of this DP index plus one now it's just going to be not holding index plus one and then it's literally going to be the same thing where if we're not holding we can buy and then now we're in the next index and in the whole thing holding as this should be I plus one by the way not index plus one so they need to change so I this is a plus okay and so now that we have these two arrays recursively made so let's actually comment out this code so from the memorization like I didn't even draw the bottom up because it's literally the same code like you can just figure out that like okay we're literally taking like the next element so we can do the same thing here except now instead of taking the next element we're taking the pre we're going backwards now well what do we need to return well we actually need to return not holding at index zero because we're not holding to begin with so just return not holding at index zero let's hopefully I did that right um see here um I won plus one okay uh let's see prices I know all right so this should be holding I and this should be not holding I so while this does run a little bit faster it's actually the same time complexity and so this is actually going to be the time complexity of ofp and space of p and now you can clearly see that like we have two arrays of length p and so that's going to be o of p and then we're just going back through them one time so now last step finally now that we have this memorization solution we have this bottom up Solution that's pretty much the same as the memoization solution now you can recognize just like in the House robber that actually holding and not holding it every single index relies on holding and not holding only at the next index and so when that's the case when you have a bottom-up solution that when you have a bottom-up solution that when you have a bottom-up solution that you only need like next index or the next few you don't actually need to store the entire array right we can just store the we can just store one value and then we could base the previous value off of that value right so we can just store something like let's say we have holding I and we have not holding hi well now to get the value before I right so now for at index I minus 1 we can just use these two values and then store that and so yeah we only need to store like we don't need to store the entire array because both of these are only dependent on the value after them so we can just refactor this code to instead of using this whole array we can just use just one number for each and so let's do that so we're going to initialize them to be zero and this is literally going to be the same code so we're doing all this is all the same now instead of using this index all we have to do is I'm actually going to write it like this because in Python otherwise I'd have to make a temporary variable so I'm actually going to initialize them at the same time because then otherwise I'd need a temporary variable because they're going to get overwritten otherwise so I'm going to do something like this I'll have a little comma here and then something like this where I initialize them like this and so instead of these indexes it's literally just going to be holding not holding and let's see if and now this is just not holding let's see okay let's give me this in the initial let's just so it's kind of long code but it's okay I'll just do this oh let's see okay so let's not remember this is not an index it's just the value now we're just gonna we're just initializing them right away and so now you can see that this works as well and so this is like the optimal solution because now we are still ha we are still doing this length P for time but now we have space of one because we just have these two variables and so that's a kind of a common technique and it's going to be common in harder problems because in harder problems let's say you have an array of like length a thousand right of the dynamically programmed like bottom-up dynamically programmed like bottom-up dynamically programmed like bottom-up array but you actually only need like the previous 10 elements or so well to save space instead of have instead of storing the array of lengths a thousand you can just use that small array of length 10 and just make sure you Loop enough to get to the first element so that this is going to be like and I think in like Stone game or something this was used in combination with a bottom-up dynamic programming so if you bottom-up dynamic programming so if you bottom-up dynamic programming so if you could do this for a simple solution where you only have you know the next index that you're using you should be able to do it for the next couple as well and so hopefully uh that makes sense to you and this is kind of like how you go from the top down to the bottom up to the you know optimize bottom up you probably want to code the top down because that's going to be the easiest then like if you can't code the top down at all you're going to really struggle so I usually code the top down then I kind of figure out okay what's their recurrence relation and what's that going to look like in the bottom-up going to look like in the bottom-up going to look like in the bottom-up array and it's pretty similar like you might have to Traverse backwards or forwards but it's pretty much the same code and then you can figure out okay can I optimize this even further to not even hold the array so this is basically like the House robber for this and all these stock problems are pretty similar where they all use that dynamic programming and so it's going to be all for this problem hopefully you liked it and if you did please like the video and subscribe to the channel and I will see you in the next one thanks for watching bye | Best Time to Buy and Sell Stock with Transaction Fee | best-time-to-buy-and-sell-stock-with-transaction-fee | You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `fee` representing a transaction fee.
Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,3,2,8,4,9\], fee = 2
**Output:** 8
**Explanation:** The maximum profit can be achieved by:
- Buying at prices\[0\] = 1
- Selling at prices\[3\] = 8
- Buying at prices\[4\] = 4
- Selling at prices\[5\] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
**Example 2:**
**Input:** prices = \[1,3,7,5,10,3\], fee = 3
**Output:** 6
**Constraints:**
* `1 <= prices.length <= 5 * 104`
* `1 <= prices[i] < 5 * 104`
* `0 <= fee < 5 * 104` | Consider the first K stock prices. At the end, the only legal states are that you don't own a share of stock, or that you do. Calculate the most profit you could have under each of these two cases. | Array,Dynamic Programming,Greedy | Medium | 122 |
18 | hello and welcome to another Elite code solution video this is problem number 18 for some we are given an array nums of n integers return an array of all the unique quadruplets nums a nums B num C numbers D such that zero is less than or equal to a b c d Which is less than n and a b c and d are distinct numbers a plus nums B plus num C Plus numbers D equals the target you may return the answer in any order for example one nums is one zero negative two and our Target is zero so our output for this would be negative two negative one two negative two zero two and negative one zero one as each one of those quadruplets added up equals zero which is our Target for example two nums is two and our Target is eight so our quadruplet would be two adding up that quadruplet would equal our Target of eight let's go through an example for this example our input array is one five two negative two zero three and negative four and our Target is zero this problem is very similar to another problem we've looked at previously number fifteen threesome so we're going to follow a very similar pattern to that the first thing we're going to do is sort our array so now our input array is negative four negative two zero one two three five and we're going to iterate through our input array and keep track of Four Points in our array we're going to have our first index our second index then we're gonna have our left point and our right point and we're going to iterate through our input array moving our left and right Corners towards each other attempting to get our quadruplets sum equal to our Target value so for this first index we're going to have minus 4 plus minus 2 plus 0 plus 5 and that equals minus one which is not equal to our Target sum and since our sum is less than our Target value we want to move our left pointer to the right to increase our total sum so now our four points are negative four negative two one and five and adding those up our sum is zero so this is a valid foursome so we'll add this to our output so now we'll move our left and right Corners towards each other and now our quadruplet is minus four minus two and three adding those up our sum is negative one which is not equal to our Target and since our pointers are next to each other we can now move our second index up and start the process over again and now our quadruplet is negative four zero one and five adding that up our sum is 2 which is not equal to our Target this 2 is greater than zero we'll move our right point to the left now our quadruplet is negative four zero one and three adding that up it's zero which is equal to our Target so we'll add this quadruplet to our output and at this point moving our left and right pointer towards each other will make them overlap so we'll move on to our next index our new quadruplet is negative four one two five adding that up our sum is four and that is not equal to our Target since this greater we'll move our right pointer in our sum is now two which is not equal to our Target and if we move our left and right pointers they will overlap so we will move our second index again our new sum is now six which is not equal to zero and now that our second index and our left and right pointers are all right next to each other we now want to move our first index point and start the process over again our new quadruplets sum is four not equal to our Target so we'll move our right pointer to the left and now our quadruplet sum is two not equal to their target so we'll move our right pointer to the left again now our quadruplet sum is one still not equal to our Target and our left and right pointers are about to overlap so we will move our second index our quadruplet sum equals six not equal to our Target so we will move our right pointer in again our quadruplet sum is four still not equal to our Target and our left and right pointers are about to overlap so we will move our second index again our quadruplet sum is eight and our second index left and right pointers are all about to overlap so we will move our first index again our new sum is eight and that is not equal to our Target value and at this point we can see that all of our values are positive and our Target is zero so none of these combinations will add up to our Target value so I'm just going to quickly show the rest of all of the quadruplets in their sums so these are the remaining quadruplets and their sums none of these are going to add up to our targeted because they're all positive numbers obviously but in our solution we'll go through the rest of these and verify and at this point we'll output the two quadruplets we found while iterating through our input array let's jump into the code the first thing we're going to want to do is sort our input nums array then we'll want to Define our result output now we'll want to create our first Loop which will keep track of our first index point and this Loop will only need to go to the length of our nums minus three since we'll have those three other points we're keeping track of in our quadruplet and we can add some checks in our solution just to make sure our current index and our next index are not equal just to remove any duplicate quadruplets so if our current index value is equal to our next value in the array we'll just skip the first one and move on to the second one since they'll be the same quadruplets next we'll want a loop to Loop through our second index points in our array and this will Loop to the length of our nums minus two since we'll have our left and right points after this and we can do the same duplicate check here to see if our current second index value is equal to our last second index value and if it is we'll just skip it to avoid duplicates and now at this point we'll want to Define our left and right points so our left will be equal to the next index in our array so J plus 1 and our right point will be equal to the last index in our array and the reason right is the length of our nums array minus one is because arrays start at zero so we have to just subtract one off our length to get our index of our last value and now we want to Loop while our left point is less than our right point and in this Loop we'll want to add up all four of our points to get our total and check it against our Target value so if our total value is less than our Target value we will increase our left point if our total is greater than our Target then we'll decrease our right Point otherwise we'll have a valley quadruplet and we'll want to add that to our result and if we have a valid quadruplet we can also avoid further duplicates by increasing our left point until we reach a new value in our array and we can decrease our right point until we reach a new value as well and while doing this we'll just want to make sure our left is still less than our right and they're not overlapping and at this point we will want to increase our left by one and decrease our right by one to get our next quadruplet and now at this point we can just return our result that's it for the code so let's run this all cases passed so let's submit our solution was accepted so that's it for this problem if you like this video and want to see more content like this make sure to check out my channel thanks for watching foreign | 4Sum | 4sum | Given an array `nums` of `n` integers, return _an array of all the **unique** quadruplets_ `[nums[a], nums[b], nums[c], nums[d]]` such that:
* `0 <= a, b, c, d < n`
* `a`, `b`, `c`, and `d` are **distinct**.
* `nums[a] + nums[b] + nums[c] + nums[d] == target`
You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,0,-1,0,-2,2\], target = 0
**Output:** \[\[-2,-1,1,2\],\[-2,0,0,2\],\[-1,0,0,1\]\]
**Example 2:**
**Input:** nums = \[2,2,2,2,2\], target = 8
**Output:** \[\[2,2,2,2\]\]
**Constraints:**
* `1 <= nums.length <= 200`
* `-109 <= nums[i] <= 109`
* `-109 <= target <= 109` | null | Array,Two Pointers,Sorting | Medium | 1,15,454,2122 |
382 | uh today we're gonna be working on lead code question number 382 linked list a random node okay we have been given a singly linked list okay return now so we cannot go back uh i mean yeah so we're given a singly linked list return a random nodes value uh from the linked list each node must have the same probability of being chosen so we're going to have initializes the object the solution uh list node head initializes the object with the head of a single linked list and get random is just gonna choose a node randomly from the list returns its value all nodes should be equally likely to be chosen okay so in this one the way we're gonna be doing is like we're gonna have some globally available uh list node we're gonna call it head and then we're gonna have our random okay yeah uh and then inside the solution we're gonna initialize it both of them head is gonna be equal to head let's just call it h so that we can say that h is equal to the head okay and our random is gonna be equal to new random so the way we're gonna be doing it is going to be we're going to have a copy of the head i'm going to call it list node c which is equal to our head and then we're going to say that uh and r is going to be the value of that c dot value right so this r is the basically going to be the randomly selected value so initial we're going to initialize it to the first head but then we're going to go through and i equals to 1 and we want to make sure that the c dot next is not null until it is not null we can keep incrementing i right and then c is going to be every single time c dot next and if the random dot next end of i plus 1 uh if that value has it comes out to be whatever the current index of the current value of the i if that is the case we're going to update our r as equals to c dot value so that should do it once we come out of that we can just return the value of r yep looking good and it works | Linked List Random Node | linked-list-random-node | Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
Implement the `Solution` class:
* `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`.
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
**Example 1:**
**Input**
\[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 3, 2, 2, 3\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
**Constraints:**
* The number of nodes in the linked list will be in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* At most `104` calls will be made to `getRandom`.
**Follow up:**
* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space? | null | Linked List,Math,Reservoir Sampling,Randomized | Medium | 398 |
242 | okay guys let's solve 242 valid anagram so we're given two strings s and t and we want to return true if T is an anagram of s and false otherwise so an anagram is a word or phrase formed by rearranging the letters of a different word or phrase typically and I don't know why they say typically it means literally using all the original letters exactly once so we have S is equal to the string of anagram we have t is nagaram as we see this is the exact same letters as anagram it's just that they're in a different order and so it is true whereas we have S as rat and T as car there is clearly a t in this and there's no T over here so that is false and we have an extra constraint s and t consist of only lowercase English letters now if you have two words that are anagrams of each other well that just means that there exists in ordering such that they are equivalent to each other and we have a way of forcing and ordering we can actually just sort them if we sort anagram we'll have our Three A's at the beginning will have g m n and R and if you sort T you will have our Three A's at the beginning g m n and R and they are exactly the same and therefore that would be true whereas if you had s is equal to rat and you had T is equal to car well if you sort them you'll get this as a r t and if you sort car you will get a c and clearly the sorted versions are not the same and so it correctly outputs false there's nothing wrong with this solution if you sort both s and t that will take well o of n log n time where n is the length of the S string or n is the length of the T string and that is just a little bit slow now instead of sorting the two strings you could instead get their frequency counts so if we got their frequency count is a dictionary f well that's going to be well we'd have a as three of those there's going to be 1 g 1 m 1 n and that's going to be the frequency count of s and if you also got the frequency count of T well we'll call that G and we know that g is going to be exactly the same as F it'll have the same keys and the same values and therefore if you check if f is equal to G well then you're good to go now checking if f equals g is very simple in Python but it's a little weird behind the hood of How It's actually comparing the two dictionaries basically what it would do is it goes through all of the keys in F it'll say is that key also in G it'll do that for each of the keys and also whenever we see a key it's also going to make sure that the values are the same for that key so we need to go over all the key value pairs in F and then you'd also need to go over all the key value pairs in G because there might be a key in G that wasn't in F luckily this operation is linear because if you go through all of the keys you are going to go through in O of n basically and when you go and check if one of the keys is in G or you check its value that is going to be an amortized o of one so that's still an O of n operation so that makes the code for this very easy and to make it super simple I'm also going to do from collections I will import counter which gets you your frequency counter as a dictionary if you want to write out the dictionary by yourself I encourage you to do so but if the length of s is not equal to the length of T there's actually no point of checking this at all because they better be the same length if that is true we can immediately return false otherwise we'll get our two frequency dictionaries we'll get S dict which is a frequency count so we'll just make it a counter given the string s we will also get the T dictionary which is a counter of T and then from here we can simply just return that s dict is equal to T dict and that is the solution if you were to run that you are good to go I hope that was helpful guys and have a great day | Valid Anagram | valid-anagram | Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "anagram", t = "nagaram"
**Output:** true
**Example 2:**
**Input:** s = "rat", t = "car"
**Output:** false
**Constraints:**
* `1 <= s.length, t.length <= 5 * 104`
* `s` and `t` consist of lowercase English letters.
**Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case? | null | Hash Table,String,Sorting | Easy | 49,266,438 |
504 | all right guys so welcome to the lead code series so the question today we are going to solve is called base 7 so the question statement says that given an integer return its base 7 string representation okay so in order to understand base seven let's first understand what's actually base seven and other bases as well so we have the numbers we study is called base 10 okay so base 10 has 10 numbers which is 0 1 2 3 4 up to 9 and now in order to get the next number what we do is we take 1 and we take these 0 and then we move ahead so we get 11 so we keep so in starting basically 1 is actually we see 0 1 0 two zero three zero four and still zero nine so first we take zero and then we put all the numbers then we take the next number so this will go up till nineteen so once we reach the 19 and we have tried one with every other combinations we move on to the next number which is 2 and we hence get 20. so this is basically a base 10 so now if you have understand base 10 so it will be easy for you to understand what's actually base 7 so base 7 will have 7 numbers which will be 0 1 2 3 4 five and six and in order to get the seventh number what we'll do is we'll take this one and we'll add zero so the seven in base seven is actually called similarly 8 will be called 11 12 will be called 9 and 13 will be called 10 and as we move on once we reach 16 the next number will not be 17 but will be 20. so this is the way we move and this is actually base 7 representation of any number so now let's take a look at the example and try to figure out what's actually written over here so let me erase this and i'll take the pencil again okay so the number we have given is 100 and it's base 7 representation is as you can see is 202 and we have to return it in string representation okay so now if you have been given any decimal number so 100 input is actually a decimal number and in order to get the base 7 representation what we do is we take 7 we divide by it and we take the remainder and write it over here so first i'll get seven then we get seven one two seven three zero seven four is the 28 and we get the remainder two so we take the remainder two and we write it over here then we again divided by 7 we can divide it by 2 and the remainder this time will be 0. now again we can multiply this by 0 and the remainder will be 2 so once my number is down to 0 my answer is actually the basically the 7 base 7 representation will be this remainder but in reverse order so my base seven representation will be two zero two although in this case uh taking looking at uh in the downward and upward direction the both are same but for the other example let's take the other example which is minus seven so i'll take minus seven so first i'll just take seven for you so i take seven ones are seven remainder zero and this number is still not zero so what i'll do i divide multiply this by zero again my remainder will be one so my answer will be from downward to upward which will be 10 so my 10 is the answer but here you can see that for minus 7 the answer actually is 10 but we also put a negative sign over here so in program while we'll be writing this what we'll do is we'll take and save the number which we have we are given as input in this number variable and what we'll do is actually you know save this number in another variable and when we get the answer we'll check that if my number is negative number what i'll do is i'll just take the base 7 representation and add minus 1 ahead of the number so i'll get the negative representation of that decimal number in the base 7 form so now let's start writing it and let's code this now okay so the first thing i'll do is i'll create an empty string so as you can see that we are required to return the answer in a string representation so i'll take an empty string and i'll add the numbers to it so as i told i'll first be saving my number in a copy variable so my copy variable will have the same number that we have we are getting as an input in this function then what i'll do is i'll check that if my number is equal to 0 then we simply need to return 0 and that's that would be my answer but if my number is less than 0 so what i'll do is i'll change my number to absolute so this function basically acts as the mod function we have in maths so what this does so this function what it does is that if we have minus 7 it will simply convert it to positive 7. so if we have any negative number so let's say minus 100 this will give us this will be converted to plus 100 so this is what the absolute function does so this is what we'll do and now we'll change my number to the absolute of number so if there will be negative number it will be changed to positive and later when we you know return our answer will check if our answer so if a number is actually the negative number we'll just add uh the minus symbol ahead of the number ahead of the answer so now i'll write the loop so while my number is greater than zero so remember when i was dividing this i divided until my number becomes zero so that's what this loop will do and will run until the number is 0 so my remainder will be number modulus 7 so this will give me the remainder my number will be changed to integer division seven and what i'll do is in my string i'll concatenate the string of that remainder so this loop will run until my you know the number becomes zero now while returning now whenever so i told you whenever we'll return it in the upward direction so from down to up so what i'll do is i'll just invert the string so whenever i write this means we are reversing we are actually reverting the string so this will be returned if my copy which is the number i saved in the variable so the original number so if my number is greater than zero then i'll just need to return this but if it's less than zero what i'll do is i'll just simply add minus to it plus the reverse of the answer so i think we should you know walk through this with an example and you'll better understand this so let's take this okay so let's start let's do the example two so this example and you'll better you know you'll understand the question better so we have this so first we have this uh s which is an empty string right we have this copy variable which has the same number so our number is minus seven so copy will have minus seven now i'll check whether if number equal zero so this is false so we won't be going through this condition we'll move on to the next so if my number is less than zero so yes my number is less than zero because my number currently is actually minus seven so if my number is less than zero my what we'll do is we'll take the absolute value so my number becomes now plus seven so it's plus 7 okay so while my number is greater than 0 so yes 7 is greater than 0 we'll move on to this condition my remainder will be 7 modulus 7 which is 0 okay my number will be integer division 7 so 7 integer division 7 will give us one so our number is now changed to one and in string what we'll add is string of remainder so our remainder is zero so we'll add this okay we go again to the loop we check okay our number is still greater than zero so let me move this okay so my number is one it's still greater than zero my remainder will be number modulus 7 so it will give me 1 because 7 into 0 and then 1 all right my number will be one integer division seven which will give us zero and what we'll do is in string we'll concatenate the remainder so it will be now zero one that's okay so we have the answer in our string but here we return this if our copy is greater than equal to zero but our copy is not greater than equal to zero so we'll move on to the else condition so in else condition i add minus to it first and then the reverse of the string because as i told the answer will be not 0 1 but will be 1 0 so we'll need to reverse the string it will be minus 10 and that's what we are returning over here so this is the whole solution let's try running it and see whether it's working or not and let me clear the screen again as a syntax error which says number a number okay so we didn't we put the space away that's why it wasn't running and yes now it's running and let's submit it and it runs so it's faster than 95.19 of and it runs so it's faster than 95.19 of and it runs so it's faster than 95.19 of the other python users so yeah this is pretty much the solution uh it wasn't that intuitive but yes it was an easy question and this is the code over here you could write it you could practice it and if you have any query you could you know write your query in the comment section and i'll try answering it and trying you know explaining it more efficiently so that's it from my site thank you for watching and please subscribe | Base 7 | base-7 | Given an integer `num`, return _a string of its **base 7** representation_.
**Example 1:**
**Input:** num = 100
**Output:** "202"
**Example 2:**
**Input:** num = -7
**Output:** "-10"
**Constraints:**
* `-107 <= num <= 107` | null | Math | Easy | null |
454 | Ko WhatsApp Ka Screw Driver Not Talking About Talent Problem Name For Song To Mukesh Do Medium Kar Koi Problem Inheritance Statement Piece Ki Jeevan Four List On Abcd And Interior Fruits Computer How Many Top Pochha Ghar Ke A Actually Dheriya A Plus B Jazba Shade Plus Serial 200 I will run into a sophisticated problem stand attacking a single element from every are them training institute for a limit is equal to zero and note book which if sampa chittor what is the myth and you have some problem what is kapil which are agri b printer oil to And friends, amazed and quite different from a given for abuse and store arrangement, we have given them a live map to where a Gyanpeeth years, even one plus minus two is equal to two minus one, our getting this new year status indexes already in the map and note that it is not Dinoy Set 20 Years Will Address Which Okay That Your Bad One And - 151 That Your Bad One And - 151 That Your Bad One And - 151 A Plus Minus Aur A Hai That Guddu Zero Sonth And Is 90 Solution 2012 And Right The Neta Edition You Will Get Back To - To - To - 121 Is 2012 0 Should Have Already age 40 index in the map shoulder improvement in the law of medicines will be to you that you rather to and minus one to a plus minus time we will give e will give up and they will on ok remo indian safa flash light ko on shoulder You Guys Want U 27 Chapter 2 Of Different Too Complicated Our Who 2010 To Rock Fill Very C Edification Ask School Tag Confirm SC Panel For Energy And Friends Will Give Power Index Right And Academic Those Check Put Friends Indexes Arm Rests With Synopsis Of And Not Right history's was Todd West friend index content Abhiru of examination from a given from her a b ok so this flower alleges that flower want to two a metacarpal confirmed 20 minutes its readers bhairu pride a minus one a plus which witch will Give talk - 1m a plus which witch will Give talk - 1m a plus which witch will Give talk - 1m is but e feel warning whole me 40 whole needed to indus river 108 dual that invited on 200 ko dogs school bus in who were presiding line is hello viewers account and then that will start in the index sohard account a plus Equal ki the index record year result kaun ki aapke kne dho entries send - awal aapke kne dho entries send - awal aapke kne dho entries send - awal a plus to ki vich will give us porn and wool inverted solid will be - song solid will be - song solid will be - song 200 gr hai par - kaun index advocate anil 200 gr hai par - kaun index advocate anil 200 gr hai par - kaun index advocate anil contestants will take bhi sperm count vivo Plus Hua Sushil Ki Object Hai How To Rate People Consider Hadith Winters Sandeep Index Plus0 Useful Object Ki Invited With - To But In The Giver In The Map Of But He Did With - To But In The Giver In The Map Of But He Did With - To But In The Giver In The Map Of But He Did Not Worship In The Railway Minister Who Can Ni Hai Then Us Hai Udan Hai That Blast which plus well maintained boat lift in world best in the taste will get - in world best in the taste will get - in world best in the taste will get - for birthday gift in Delhi in this map is done and hydration is power and then control system is the right of an elderly white is this problem and waste that new lets Go for the code that obscene stunts flavor finding exposed officer how to get google take a nodal map on torch light walnut you want to offer a tour inspector drink it like on one October and Bibi Ajay who is the inventor of the The Ministry of Water from this thank you, so let's make 12th of the schools till the day complete to the same MP3, now half of the brightness index of this is to echo show of plastic and that is important to me, sona lootne date country's index. Tha Aunty Chabilon Is Contest Pin Number Pound Map Of History Who Is This Index 168 And Telugu Absorption Ko Pooja Africa Shanti Om Plates In This Quote A Cup And Plate Is Included That Express Handed Over To Siddha Jhale Village Quote For This Problem Hello Friends for watching this video | 4Sum II | 4sum-ii | Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that:
* `0 <= i, j, k, l < n`
* `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0`
**Example 1:**
**Input:** nums1 = \[1,2\], nums2 = \[-2,-1\], nums3 = \[-1,2\], nums4 = \[0,2\]
**Output:** 2
**Explanation:**
The two tuples are:
1. (0, 0, 0, 1) -> nums1\[0\] + nums2\[0\] + nums3\[0\] + nums4\[1\] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1\[1\] + nums2\[1\] + nums3\[0\] + nums4\[0\] = 2 + (-1) + (-1) + 0 = 0
**Example 2:**
**Input:** nums1 = \[0\], nums2 = \[0\], nums3 = \[0\], nums4 = \[0\]
**Output:** 1
**Constraints:**
* `n == nums1.length`
* `n == nums2.length`
* `n == nums3.length`
* `n == nums4.length`
* `1 <= n <= 200`
* `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228` | null | Array,Hash Table | Medium | 18 |
784 | hi guys welcome to algorithms made easy in this video we'll go through the question letter case permutation given a string s we can transform every letter individually to be lowercase or uppercase to create another string return a list of all possible strings we could create you can return the output in any order so in this example one you can see we have two characters in the string and we have both the permutations for both the characters so we can get four permutations that is two raised to two now in the second example you can see we have an input which has one character and it can only have two permutations in the example three every character present in the input is a digit and so the only permutation we can have is all the digits exactly in the same order similar with example 4. in the constraints we are given that s will be a string with length between 1 to 12 and it will only contain letters or digits so now there are many approaches you can solve this question one is by using a recursive method one is by using an iterative method and even bit manipulation but in this video we'll just see the iterative method let's go ahead and see how we can solve this question considering this string as an array let's start with the first character we can have either a small case a or a uppercase a and then we take these two combinations and move ahead with our second character in the string so till this point this character over here is fixed so this becomes our left this becomes our right and this is the character we are working on and since this is a digit we cannot do anything but we can just keep the characters as it is and move ahead for the other character so here we have a character and so we can have both the combinations lowercase and uppercase for this character so this one string can be written into two ways by using both these characters now again we move ahead by making this as fixed and so over here when we see this 2 is now a digit so we cannot do anything but we just need to return this 4 characters because there is no other character left in the string for us so this is the graphical representation of what we would be doing or what can be done for this question so here one thing to note is that every time whenever we are looking for a character a left part is there and a right part is there and left part is generally a fixed part while right part is the one where we'll be moving and we are currently checking for the character in the middle so now let's go ahead and see the programmatical way of doing it so we'll take a q or a linked list in our case and we'll try to solve this question in an iterative manner so this is our original string and i have added that string in the queue or a linked list and i am starting from behind rather than starting from the start over here i see that this is not a character so i do not have to do anything but move to the next character now this is a character and i can have two permutations for this character so what i do is i pop the string and i take the two combinations for that particular string and i'll add it in the queue so this is what we'll do for a character now we shift to our left and now since this is not a character we do not do anything but move ahead so once we reach this a we can say that this is a character and so here we need to perform a permutation for each and every value that is present in our linked list and perform the character casing permutation on the current character which is a in our case so now how this character casing looks it would look something like this we'll take both the inputs and we'll do a lowercase a uppercase a lowercase a and uppercase a for both of them and now again we'll put that in our queue since this was the last character over here so we do not need to move any further and this becomes our result so this is what the iterative approach would look like when you do it you can easily change this code for a recursive one which would be a dfs solution and this would be a bfs solution that we have worked on so now let's go ahead and code the iterative solution so the first thing that we are going to do here is take a linked list this will act as our queue for bfs and also act as a result that we would be returning after that we will just take length as handy and after that we need to iterate over all the characters in the string so over here we are iterating from the last character and going towards the first character as we saw in our example so for that we also need to add our string in the linked list as a preparatory task now let's take the character handy and this character would be the last character or the character from the string after this we'll first check whether this is a digit or a character because if it is a digit we do not need to do anything if this is a letter we need to iterate over all the strings that are present in our linked list and add the permutation for the current character so in the linked list we have these many strings that are present and for creating the permutations we would do a while loop and permutate on all the strings that are present in the result over here the first thing that we always do in bfs is pop an element so that would be polling from the result and now we need the left and right part for the string that are static and just change the current character so let's take left equal to substring of the current string that we have found out for which characters for 0 to i and my right would be i plus 1 to n now one i need to add with a lowercase one i need to add with the uppercase for these particular left and right so we will add in result left plus lowercase of c plus right and similarly for uppercase so that's it now this for loop will take care of creating all the permutations for us in the linked list and at the end we can just return the result hopefully there are no errors let's try to run this and it's running fine let's submit this code and it got submitted the time complexity for this particular approach would be the number of permutations that we can have and that number of permutations would be 2 raised to the number of characters that are present in the string the space complexity if you are considering the result would be n into 2 raise to n to store 2 raised to n permutations for the in length string so that's it for today guys i leave the recursion solution up to you can make some modification and let me know that how you have written your recursion solution i hope you liked the video and i'll see you in the next one till then keep learning keep coding | Letter Case Permutation | insert-into-a-binary-search-tree | Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string.
Return _a list of all possible strings we could create_. Return the output in **any order**.
**Example 1:**
**Input:** s = "a1b2 "
**Output:** \[ "a1b2 ", "a1B2 ", "A1b2 ", "A1B2 "\]
**Example 2:**
**Input:** s = "3z4 "
**Output:** \[ "3z4 ", "3Z4 "\]
**Constraints:**
* `1 <= s.length <= 12`
* `s` consists of lowercase English letters, uppercase English letters, and digits. | null | Tree,Binary Search Tree,Binary Tree | Medium | 783 |
338 | hello welcome to my channel today we have leeco 338 counting beats so this question is often asked by amazon blizzard especially facebook apple and microsoft personally i see it from facebook and but i say it's a really good question but i don't know why it's not that popular here it could be one of the question that from the big company and people who like it a lot so you can see this is really good question maybe just this six months not that popular so for this question and you see we input this integer positive integer so the input will be fine where output will be uh array of integer that starting from 0 um to all the way to the number input so 0 1 2. so this number representing the binary representation of that number for example is zero and is zero so one we have one in the binary representation in order to saying this i will draw it out so we can understand better so now we have 0 1 2 3 4 5 right here and in this situation their binary will be like this and two we have one zero three will have one so four you have one zero five will have one zero one so now you see this is a binary one this is a uh decimal one so we have two here so we start from zero there's no one here it's only have one here so it's one so two i only have one so it's zero one for this question and if you want five is right here and we have to start from zero one will be the same as this one to find the representation so see how many ones in three so which is two one and then one two one again so we have all the representation in this array output this question is really good and uh because it's used to uh classic solution for in here which is binary sorry operation and also we use dp which is dynamic programming in here to solve this problem so now we know how to build this output now and that's one concept we will know which is you see uh we have the base case zero and we know there's something called binary operation which call right shift here if you y shift one that means this binary become one right shift one for this binary number is also one but right shift this number will be ten because you write one digit and they cancel this out so now we see this at zero 1 we keep building this up 1 here that's enough so now we see this number right here when we see 3 we make it three right shift one and we see right sheet one will find this which is one here because right shift one for this 11 here will become one so one will have one as a dp here and actually this one is built up from here you see uh is representing this one because right shift this will here and we need to add if the original binary have one so how do we need to check the last digit is this binary mod 2 which is the last binary digit right if it's one so this will be one so we add uh right shift one six current binary digit right shift one and find this uh how many ones in here and then we add if it's even or odd for this current binary that will be the current ones for this digit in this case the same if this is odd i'm an even number and when you write one which is 10 here and then we see this is the right solution because if you right shift this one this is also zero it's just nothing if you take out another zero it's still the one doesn't change in this solution so we get the answer from the right shape one which is one and here you know this is odd number for sure you get the one first in here and you're looking for the right shape one is a 10 for this number so this number at odd and even so it's 2 here so this is how you get the dp solution in here with the binary operation so it's really clever so now we take a look at the code so you see first we need to build up the um output array that is new and numbers plus one we need that much including the zero so we make in i starting from one i less than i'll put dot size high passwords look through the whole entire things to the end so every output i will be equal to output because you know um zero is start from zero it's default as a zero so recall i right shift by one plus whether i is odd or even not smart too so it's the last digit in here at the period uh right sheet once answer from the dp and we will see we will build up this output array and return output array at the end cool it looks good let's submit it and that's it definitely be 100 because it's really lightweight and it's only one time well uh i think and o n of space so that's it for this question uh let me know if you have another question or any concern comment below and i will get back to you as soon as possible until we see you next time bye | Counting Bits | counting-bits | Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)? | You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s? | Dynamic Programming,Bit Manipulation | Easy | 191 |
376 | today we're gonna be working on lead quote question number 376 a vehicle subsequence a vehicle sequence is a sequence uh where the differences between successive numbers strictly alternate between positive and negative the first difference if one exists may be either positive or negative uh a sequence with one element and a sequence with two non-equal and a sequence with two non-equal and a sequence with two non-equal elements are trivially vegal sequences so we've got this one seven four six four five and we're gonna say that the whole sequence is uh in vehicle sequence because it is increasing then decreasing then increasing then decreasing and then it is increasing again so yeah basically we are looking at the differences here uh decreasing increasing or increasing decreasing and then like look at this example where one four seven two five uh one and seven is increasing and then seven and four uh sorry there are two sequences one four seven two five and one seven four five are not wiggle sequences they are like one is increasing one and four if we remove seven or if we remove four then it becomes one seven and then two and then five then it becomes bigger sequence so we'll say that the total uh maximum length of the vehicle sequence can be four and in this case one four one seven four five up to this point now it was increasing then decreasing then increasing but then it stayed same so we cannot include the last uh element in the vehicle sequence so again as we're gonna make changes in order to tell that what is the maximum number of uh values maximum number maximum length of the meta of the matrix we can have uh which is gonna stay vehicle sequence or if we so in this case we can include everything it's going to stay wiggle sequence in this case uh our answer is going to be 7 because we're going to remove uh we're going to remove 5 and then we're going to remove 15 and then we're going to remove 5 again and we're going to end up having this sequence with the differences of this one which is going to stay wiggle so the total number of elements is one two three four five six seven okay that being said uh the algorithm is gonna be basically we're gonna have an up going uh array and a down going array which is gonna keep uh whenever we are processing uh and it's gonna keep the uh the index uh which we're gonna say that okay we're gonna include that index or not so if the nums.length the nums.length the nums.length is equal to zero we're gonna say return zero okay and then we're gonna have as i said two areas one is like gonna keep record off if it is still if that index is gonna add up uh in going up so new end nums dot length and end down is equal to new end num start length right so we're gonna initiate up of 0 to 1 and down of 0 to 1 okay then for int i equals to 0 sorry i equals to 1 i is less than our nums dot length i plus this is because we already started and we already included the first index so we know that at least even if it is one number in there uh the answer is gonna be at the minimum it's gonna be 1 so now based on if it is increasing right if the nums of i is greater than nums of i minus 1 and we know it's not gonna go out of bound because we're starting i equals to one so in that case what's gonna happen is gonna uh down is not doing anything down we're not going down we are going we're going uh we're increasing right we're going we're incrementing so we're gonna say that the down which is keeping record of the sequence which is keeping record of the indices which are adding up to go down is going to stay the same but the up of i is going to become equal to whatever the down was plus one as both of these uh matrices are as both of these matrices are keeping record of the indices num of i minus 1 and nums off yeah it should always be the number okay in that case when it is decreasing then in that case the up is gonna stay the same it's gonna be i minus one and then but the down of i would be equal to up of i minus one plus one else ah else if it is uh staying the same like else it would be when sequence is not increasing or decreasing in that case the down and up is going to stay there whatever we had in the previous at the previous index and once we are done with this loop uh the answer is gonna be whatever is the maximum value of the uh up or down math.max math.max math.max yeah because though it could be we the last underscore index could add up to either the down matrix or the up matrix so that would be down of nums dot length minus one or the up of num start length minus one looking good let's submit that and it works | Wiggle Subsequence | wiggle-subsequence | A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
* For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative.
* In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`.
**Example 1:**
**Input:** nums = \[1,7,4,9,2,5\]
**Output:** 6
**Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
**Example 2:**
**Input:** nums = \[1,17,5,10,13,15,10,5,16,8\]
**Output:** 7
**Explanation:** There are several subsequences that achieve this length.
One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8).
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6,7,8,9\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
**Follow up:** Could you solve this in `O(n)` time? | null | Array,Dynamic Programming,Greedy | Medium | 2271 |
234 | all right uh so we are live uh so today uh we're going to be talking about our palindrome uh linked list um which is a question on lead code uh let's go ahead so it's a given the head of a single thing uh a singly linked uh linked list uh return true if it is a palindrome or false otherwise so basically a palindrome is something that um a string or um in this case we have a list if you start from the end and you go all the way to the uh to the beginning it reads out the same way so we have one two one and then again one two one so basically all we have to do is to check if this is a uh is a palindrome and that's what is a palindrome this is not because one two then two one is false okay all right so this is what we have and they say could you do it in uh or end time and oh uh o1 space so that's what we're gonna aim at so we already have the implementation let's go ahead and do some explanation so we have uh we first thing we're going to do here we're gonna check if our head is not and if it's not then we're gonna return true because it's a palindrome in that case so here we have uh we're gonna have two uh basically heads a slow head and a fast head so I was a fasted it's gonna be like two steps ahead and slow one is going to be like one step behind and that's all we're gonna see here so while uh while fast dot next is different from null and fast dot next is different from no basically when it's different from now when we haven't hit the in the end then we're gonna set fast to fast dot next and slow equals to slow dot next this is where we Define uh basically like uh what is which one is fun which one is fast basically this one is fast like I said two steps ahead and this one is slow one step behind all right okay so if we come to the next one at least node uh second so basically this one you can say uh the second half head uh we're gonna set it to basically we have to like I said we have to reverse it uh basically to check if it's equal to the other one and there only then we can declare that this is a palindrome because the reverse has to be equal to the normal uh like the number one starting from the beginning so here we're basically gonna reverse it and uh here uh we're gonna set our hair our fast head to our first half Head to Head okay all right so let's go to reverse file so that we understand what I mean because this is a very important part of this question um so basically uh what you do here you're gonna reverse uh this node.list you're gonna reverse uh this node.list you're gonna reverse uh this node.list not so we're gonna have our head our list node here which you're gonna set to know and then we're gonna Traverse our head okay I want this note head here and then uh once we Traverse it and it's different from now then what we're gonna do is that uh we're gonna check um we're gonna set it to if it's different from now we're gonna take our head uh let's see we're gonna create a new node here and call it next and then we're gonna say to head.next right and we're gonna say to head.next right and we're gonna say to head.next right and then once we do that now uh we're gonna take this I mean we're gonna take head dot next and set it to our list node that we created here before okay so now it's pointing to this note right here okay and then once we set it that way um uh let's see now we can actually take our head always our head right we can just say a new head equals to head and then once we do that then we can just say head equals to next so now we're going towards the right um so and then after that uh you know that's we basically just reverse the this node and then we're gonna in the end we're gonna return our new head which is a one which is reversed and so if we come back here so first of all we check second half head uh if it's not null and fast half head is also different from null then if variable if fast half head dot val is different from I mean it's not equals to Second a half head or then we're gonna return first because that means the uh we checked and then the reverse is not equal to the normal one okay and then if they are then we're just gonna say second half head equals to second half head dot next and then first half head equals to fast half head dot next and then we're gonna end up returning uh true okay and so basically that's it and if we submit our code I'm sorry all right if you have any question don't forget to uh send me a question in the comments side and I will be doing uh one video about reversing uh list node and I will see you guys next time | Palindrome Linked List | palindrome-linked-list | Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_.
**Example 1:**
**Input:** head = \[1,2,2,1\]
**Output:** true
**Example 2:**
**Input:** head = \[1,2\]
**Output:** false
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`.
* `0 <= Node.val <= 9`
**Follow up:** Could you do it in `O(n)` time and `O(1)` space? | null | Linked List,Two Pointers,Stack,Recursion | Easy | 9,125,206,2236 |
1,845 | hey everyone today we are going to solve theal question seat reservation manager okay so if we only make our reservations this problem is very straight for right but the difficulty is we have unreserved function so numbers will have gaps so what is gaps so when we make a reservation we start from one and if we have another reservation we return two three four five and now we have five reservations but um some C customer cancelled reservation so which is let's say four in the case um this four is available again and uh if another customer canel three so three also available again so um to solve this question we have two points okay so first key point is how we can manage next number so this is a very easy right just create a kind of counters and when we have a reservation so we increment by one right so we can use like a simple variables so this is easy and the second question second key point is how can we manage and res numbers so description said um so Reserve function should return like a small number small available number so let's say now we have five reservation and some customer canel three and four so in that case so next number should be six right but we have like a three and four right in that case so next number our reservation number should be three and the next four then six so in that case um how can we manage unreserved un reserved numbers so do you come up with like a suitable data structure So my answer is to use mean he so because we can manage um undeserved numbers from small to large right so um when some customer canel the reservation and uh in the case we keep the reservation number um into Hep so Hep has now three and four and then next number should be six right and uh when we have reservation when we make a reservation so compare next number versus a minimum number in keep that means three and then if um three is smaller than six right so that's why we pop um three from Heap and then return so now we have four right only four and the next number is six so if we make a reservation again compare six versus four so four is a smaller than six right in the case pop four from Hep and then return right and then there's no data in mean hi so that's why next number should be six right so that's why um so count the return the uh next number yeah so that is a basic idea to solve this question so without being said let's get into the code okay so let's write the code first of all self do so next initialize this one and I create a heap o he and empty list yeah that's all and then implemental Reserve function so as I told you if self. Hep has data and self do Heap so zero so that we can uh Peak the minimum number in Hep so minimum number in Hep is less than self. next in the that case um we pop the minimum data from Heap so heapq do Heap pop and self do he if not the case um self. next so before we return add plus one for next uh reservation number and then um return so but so we add plus one here right and but we need um current next number so that's why um self. next minus one right this time and then next time we need a plus one next number but now we need to minus one next number right and then um let's Implement unreserved function so this is a very easy so just uh um push the seat number so Heap Q do Heap push and then say self do Heap and seat number um so that the Heap will reorder the seat number and the minimum seat number will be a like a root I mean top yeah so that's it let me submit it yeah looks good and the time complexity of this solution should be so for in function I think o1 and for Reserve function I think a Logan because of Heap pop and uh for unreserved function um I think a log in because of a heap push and the space complexity is I think uh in the worst case order of n um there is a case where all customers cancelled all reservation so in that case we have to push all seat numbers into Heap right so that's why yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next Qui question | Seat Reservation Manager | largest-submatrix-with-rearrangements | Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`. | For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix. | Array,Greedy,Sorting,Matrix | Medium | 695 |
1,675 | Hello guys welcome back to the another video of lit co daily challenge so today our question is minimize deviation in array this is a hard level question so let's read the question once to see what is said in the question at the end so our question is You are given array of numbers of any positive integer. We have to perform two operations which are given by us elementary So what is our first operation? If we have been given an even element then we have to divide by two. For example, we have been given 1 2 3 4. If our is called odd in these, if we get an even number then we have to divide it. If we have to divide by two, then what is our even number in this? Our four is two. If we divide this, if we divide two by two, then we will get one and if we divide four by two, then what will happen to us, it will become two, similarly. Here it has also been solved in the example and the second operation is what is ours? If our odd comes then it has to be multiplied by our two. For the example, our has been given a tooth and then if we see the odd, what is ours? One becomes three. Done, if we multiply one by two, here we will get two and if we multiply by three, we will get six. In the question it said that the deviation of array is the maximum difference between d of between any two elements in the array. Return the minimum deviation. Of array can have performing even number of operations. Okay, our co, where we find the minimum, we have taken out two differences, we have to do one of the maximum and we have to take out the minimum, where our co, we find the maximum, where we find the minimum, then we will subtract that from this. Which will be our final output, we have to print the minimum deviation output here, so what is our given input in the question, the input is given by numbering 1, 2, th and four and its output is given as one, so what do we have to extract? Wherever we see odd, we have to divide it by two and if we see even, we have to multiply it by two, so what is our question? First of all, whatever is given in our question, we have to do this. It is not necessary for us that in the question also we have to do the same operation, this one is that if we have to multiply even and divide only odd, then what is our interest in this, if we do it can be our wish that we want to do it. So you can do it and if you don't want to do it, if you can't do it, then for the sake of example, what is our four, our maximum value has been given and our minimum value, what will be our one, if we take it as a minus, then our three comes, then what do we do? First of all, first of all, we will multiply our given odd numbers by whatever value we get, then we will write down our value, then we will divide it by the even number which will be multiplied, if our whatever comes out of these, what do we do if by two? While multiplying, we will get this is given for Apple and then what will happen to us, we will divide it is not necessary to divide, it is not necessary, what I had told you and here we multiply the question by two. It is not even necessary to do this and what will we do with four, we will divide by x. If we see that our maximum value is g and our minimum is g, then we will subtract both of them, then our unit will be the minimum value which we have to find. Okay, and what is given to us? Okay, we can do this operation any number of times, we can multiply it any number of times and we can divide it any number of times. Okay, let's do it properly. Question What did I do? In the question what is our first? What is the number given on our? Let's write them down, th and four, this is our, what is ours, what is to be done with our, we have to divide our and if we have to multiply. What do we do first of all? First of all we see that we multiply d by t, then our decimal c value will be n and it becomes t. Okay, we first multiply it by x. If we divide it then how much will we get? This will happen if we don't divide it, so it is not necessary that we divide it, so we write it as it is and multiply it by two, make it six, okay and what is this here? What we had to do was to divide by 2. Here we divide it by 2. This is our number of even and odd which we had to multiply by t and divide by 0. How do we find the minimum distance? What we had to do was to subtract max from max. What is our max value? 6 If we do 6 minus two, then what do we get? If we do two, then we get four, which is our minimum distance, which is what we get in our output. It is not given like this, it is not necessary that what we have to do is exactly like this, as soon as our four comes, what do we do, then we check for the second time whether we come to the second minimum distance or not, if what we do? What we will do is if we multiply two by one, then we leave two as it is and we leave three as it is and here the last four we divide by two. Because it was given to us that when we divide one, our maximum and minimum are equal to one, our maximum is equal to two and minimum is two, if we subtract it then one is equal, as here our final output has come. And this is our final output. Similarly, we see in the second example, how we have given it to us, we have given the value of 10 and 8, what we have to do in this, what we have to do first in this. If we have to multiply d by 2 and divide it, then we have already given even in it, so we do not need to change anything else, what will we do, first we will divide it by 2, we will keep 2 in the same way. Let's leave it is not necessary to divide it can be our wish that we can divide it as many times as we want and can also multiply it. If we want to do one, we can do only one, so we can What will we do, if we divide 10 by two, then here it will be F, and what will we do here, if four is a set, we will divide 8 by two, then what will be our F, and what will be our maximum value here, F? And what would be our minimum value? If we had subtracted this, how much would have been ours, which would be three, which would be our final output. Well, this is our final output. I hope you have understood even the question. How to do the question? Firstly, this is There is another way, if we had divided it by two, then ours would have been two here too, so what would have happened here, if it had been two here, then also what would have been our minimum, what would have been f, the minimum would have been two, the maximum would have been f. If our output also comes through, then what do we do here? What do we do here, then we try to do it in a different way. If we do this operation, then we will know what is the questioning, what will we do to make it a little typical. We will keep checking again and again which of ours is odd and which is even and at which time and which output will be correct, then what is the best way to do it, what will we do before that, all our values will be given here. values will be given here. What will we do with our names? We can first make all the values even, so that we can values even, so that we can values even, so that we can divide the even value and tell it easily. We could also make it odd. This is our loss in doing odd. It will happen that our number of times will be more like our number will be 50, how many times can we divide 50 by two, we will have to divide our number of times by 250, just like this, so what do we do first of all? Whatever value we have given to it, what will we do with it, we will make it even, given the value of our, let's separate it a bit, here we will do this, but we will first make it even, to make it even, what would we have to multiply by two, only So let us turn one into two, the already even number becomes six and the four remains four. Well, all our values become even and if it becomes even, then all our values become even and if it becomes even, then all our values become even and if it becomes even, then what is our main task left? We have to get the value. If everything is gone then what will we do first of all we will find our even value, then we will find its max and minimum, max will be our six and minimum will be our t, then what will be our distance, four and this is our output will be four, okay What we know is that yes, its minimum output has come, okay yes, we can assume that this can be our output, like this, what will we do with this, we will divide this three by two to get six. If we divide by two, how much will we get here, now we check the minimum distance max, our how much will be four and the minimum will be three, so we will find out the minimum max of this, then how much will be ours, one will come and our output will go. Now we can assume that this can be our one output. Okay, this is our one output. Now here we see that from our values which were all even, one value has come out, values which were all even, one value has come out, values which were all even, one value has come out, so what does it mean which is our result? We have got the final output, so how much will our final output be? Similarly, our one final output has been done. Now let us look at the second example in the same way, so here we give the second apple. Ours is already one, so there is a need to do this. There is no need, so we take 10 and 8. After taking 8, what was our first method? First of all, we had to find out the minimum and max. Max, how much will we get, it will be 10, it will be Minimum, what is our difference, but we see that our A has come, then what will we do? We can assume that our output is, then what will we do, we will divide by two, let's do it, okay now? What will we do at y? Our max will be 8 and our minimum will be how many we will get at After this we see here that our maximum value will be our five and our minimum will be two. What will be its final output will be three. Here we see that our minimum value here which was our odd value has arrived. If we have got one, then what will be our minimum value? Three here, as soon as our odd value comes there, we get our final output in the entire array. I hope my question is clear, understand the code. If we look at it, here is the code, I have already written it, once you try it yourself, compile it is compiled, submit it and it has been successfully submitted. It's not done, it's not done, see you in the next video. | Minimize Deviation in Array | magnetic-force-between-two-balls | You are given an array `nums` of `n` positive integers.
You can perform two types of operations on any element of the array any number of times:
* If the element is **even**, **divide** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].`
* If the element is **odd**, **multiply** it by `2`.
* For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].`
The **deviation** of the array is the **maximum difference** between any two elements in the array.
Return _the **minimum deviation** the array can have after performing some number of operations._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 1
**Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1.
**Example 2:**
**Input:** nums = \[4,1,5,20,3\]
**Output:** 3
**Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3.
**Example 3:**
**Input:** nums = \[2,10,8\]
**Output:** 3
**Constraints:**
* `n == nums.length`
* `2 <= n <= 5 * 104`
* `1 <= nums[i] <= 109` | If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible. | Array,Binary Search,Sorting | Medium | 2188 |
288 | hey folks welcome back to another video today we're looking at question 288 unique word abbreviations the way we'll be approaching this problem is by using hashmaps the problem um the solution to this problem itself is relatively simple but the problem with this problem is being able to understand it because this part is quite confusing um so actually let's jump right into the solution and i can walk you through the requirements of the problem while we are solving the question um the first thing that we actually need is a hashmap and the reason why we need a hashmap is because um we need to have these abbreviations stored somewhere and they need to map to something so for example if they map to the same word so if you see here cake and cake right so cake and cake actually returns true but if there are multiple instances of that so for example uh deer and door right so in this case it returns false because they have the same abbreviation but they don't really link back to the same word so if you look at the explanation here it says returns false dictionary word dear and word dear have the same aberration d2r but are not the same so basically there's a you need to be able to track whether a given operation links to a certain word or multiple words and to be able to map anything it's really good to use a hashmap so let's initialize the hashmap and then let's call it string let's just call it map and within the constructor itself let's initialize it awesome so once you have that you want to somehow store all of the words in the dictionary into the hashmap so what you need is you actually need another you could also do it within the method itself but let's just call it create another method uh like a private method it would create all the operations for us right so let's say private string let's call it get um abbreviation again thing that we actually need to take in as a parameter is a word right um and what needs to be returned here what you need to return here is the first letter so word dot uh get character at zero um plus you need to tell us a length right so let's actually get the length of the word dot length right and so that would be a string dot value of and in so that would be l minus one and then you need to return what dot character at l minus one right but to be able to return this you need to return it as a string so concatenating it this way uh would actually return a string there i'm sure there are better ways of um concatenating it but this is like the fastest way that i could find and think of on the spot um all right so let's look okay so the word land right here you see that it could be the smallest one that we could get is uh the letter like it could be as small as one letter so what we need to do is that we actually need to accommodate for that so if it is one letters or two letters you can't really concatenate it because uh as like abbreviated because you need to have the number of letters in between so you would say if length is less than or equal to 2 you would just write down the word as is awesome so once you have the word um let's call it a 10 n which is like a perfect operation from here and then let's just call it let's just call this method on that particular word um oh we obviously need a for loop so for string word uh in dictionary right um we get the abbreviation of the word and then we check so for in sorry so if um map dot contains key um a 10 n um so that means the abbreviation exists already but you need to check whether it's the same word or not so if map dot get p10 n dot equals word so if it is the same word um you don't really do anything but if it is not the same word you need to somehow represent that um that it doesn't map back to the same word so a potential solution for this would be actually creating um hashmap that maps to a string to um to a hash set which stores all the words but the thing is we don't really care what word it is we just need a way to represent that abbreviation links to multiple words so what you would want to do is you just want to initialize um like map that particular application to something that you understand that hey like this maps multiple words and how can you do that so you would just say map.put say map.put say map.put a10n to like an empty string right um and if this does not exist if it doesn't exist you actually put it in so you would put map.map.put 810n and the word itself and the one question that you might ask is why am i checking the same word exists already right so if this condition works right as in like if it contains shouldn't we just um add this directly it turns out when i was running the test cases there are ones that are similar so one of the test cases that i ran into was one list that had a and a like the single letter um because of which the all of the test cases did not pass so there's a reason why you need to check if that word has been seen already um if you ask me that's sort of weird for a question especially because like it says that it's a dictionary that's being passed but regardless you want to make sure that your solution works so that's the reason why you need to check whether the word that you're looking at is equal to a word that's that you've seen previously um if it is um you don't really do anything if it is not then you uh put an empty string to signify that uh it maps to multiple words right um right so i think these two methods are good um we only need to work on the as unique method so uh what you need to do is let's do the same thing that we did right here right let's get the abbreviation of the word that we care about and then you need to return do we need to return mob dot contains key uh a tan n so if it is done if it doesn't contain um or if map dot get a 10 n dot equals what so let's check the conditions there's no one in the dictionary whose abbreviation is the same uh and for any word uh in the dictionary whose application is equal to the words abbreviation the word and the word are the same okay so i think that should be okay so let's try compiling it and see if it's okay if the first test case looks okay let's try compiling it okay that's awesome um so everything passes uh which is awesome so let's talk about the space and the time complexity right so the space complexity for this entire solution would be of n since we are using a hash map to store all of the words uh the time complexity for this is unique method would be of one since we're just looking it up in the hashmap um and the get abbreviation is also of one because it's uh this operations can be done in constant time and uh but putting all of the words in the dictionary is of time complexity of n um yeah so that's the solution if you have any questions about this problem that i just saw please let me know in the comments below um if you want any other questions to be solved on lead code also let me know in the comments below i would be more than happy to solve them for you um thank you so much for watching please don't forget to subscribe to the channel like the video it definitely motivates me to make more videos thanks so much and i'll see you all soon | Unique Word Abbreviation | unique-word-abbreviation | The **abbreviation** of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an **abbreviation** of itself.
For example:
* `dog --> d1g` because there is one letter between the first letter `'d'` and the last letter `'g'`.
* `internationalization --> i18n` because there are 18 letters between the first letter `'i'` and the last letter `'n'`.
* `it --> it` because any word with only two characters is an **abbreviation** of itself.
Implement the `ValidWordAbbr` class:
* `ValidWordAbbr(String[] dictionary)` Initializes the object with a `dictionary` of words.
* `boolean isUnique(string word)` Returns `true` if **either** of the following conditions are met (otherwise returns `false`):
* There is no word in `dictionary` whose **abbreviation** is equal to `word`'s **abbreviation**.
* For any word in `dictionary` whose **abbreviation** is equal to `word`'s **abbreviation**, that word and `word` are **the same**.
**Example 1:**
**Input**
\[ "ValidWordAbbr ", "isUnique ", "isUnique ", "isUnique ", "isUnique ", "isUnique "\]
\[\[\[ "deer ", "door ", "cake ", "card "\]\], \[ "dear "\], \[ "cart "\], \[ "cane "\], \[ "make "\], \[ "cake "\]\]
**Output**
\[null, false, true, false, true, true\]
**Explanation**
ValidWordAbbr validWordAbbr = new ValidWordAbbr(\[ "deer ", "door ", "cake ", "card "\]);
validWordAbbr.isUnique( "dear "); // return false, dictionary word "deer " and word "dear " have the same abbreviation "d2r " but are not the same.
validWordAbbr.isUnique( "cart "); // return true, no words in the dictionary have the abbreviation "c2t ".
validWordAbbr.isUnique( "cane "); // return false, dictionary word "cake " and word "cane " have the same abbreviation "c2e " but are not the same.
validWordAbbr.isUnique( "make "); // return true, no words in the dictionary have the abbreviation "m2e ".
validWordAbbr.isUnique( "cake "); // return true, because "cake " is already in the dictionary and no other word in the dictionary has "c2e " abbreviation.
**Constraints:**
* `1 <= dictionary.length <= 3 * 104`
* `1 <= dictionary[i].length <= 20`
* `dictionary[i]` consists of lowercase English letters.
* `1 <= word.length <= 20`
* `word` consists of lowercase English letters.
* At most `5000` calls will be made to `isUnique`. | null | Array,Hash Table,String,Design | Medium | 170,320 |
1,296 | hello friends welcome to joy of life so today we are going to look at a medium level problem from lead code the problem number is one two nine six it's a divide array instead of k consecutive numbers so the description says given an array of integer nums and a positive integer k find whether it is possible to divide this array into set of k consecutive numbers return true if it is possible otherwise return false so we are going to look at couple of examples given over here so here we see an array that has one two three four five six and we have k as four so we have to split this array but in the numbers are consecutive right so if i take this one two three and four and put it in one array so you can see that there are four numbers which are consecutive and the remaining three four five six if we pick them up and we put it like this then it is also consecutive right so both are of size 4 and k is also 4 so this array can be divided into two arrays of size 4 where the numbers are consecutive similarly you have a bigger number like three two one two three four three whatever and k is three so you can see that you can split it like one two three four five nine ten eleven like that so the important part is the size of this array should be three and the number should be continuous like 1 2 3 it should not be 1 2 4 it should be the number next to each other right so this is the problem all about and do give it a try as i always recommend that do give it a try to solve this of your own first and then you can look at the solution over here and particularly for this problem i would like to thank anish dube who has recommended me to solve this problem and thanks anish for your support for the channel i will try my best to capture all the scenarios in this problem for you so let's move over to the board and let's see how the solution looks i've taken the same example as we have seen in the lead code first example and we are going to solve this here you might see that i have depicted the array into two colors the yellow color forms one group and the green color forms the next group right where k is equals to four so for this particular input what we'll see is this output right one two three four being the first group and three four five six being the next group so as recommended by anish what i'm going to do is i am going to create this video where we will use a tree map data structure and a queue though there is a easy solution which is available using a priority queue as well but we are not going to look at the solution probably i'll make a separate video on that but this one is definitely much more efficient and the performance is also much better compared to parity eq algorithm but here the solution is a little tricky and we need to understand it in details so before we do a deep dive of the solution let's understand what a tree map is so tree map is a tree wherein the keys are basically sorted according to their natural order or what you can do is you can pass a competitor at the time of creation of the map and it will be and the keys will be sorted based on the same right where in our queue is a data structure wherein the first element that goes in comes out first so it's a fifo data structure whereas why we need the tree map is because its ability to sort the keys of the map so these are the two key elements that we need so first what we will do is we will first create a tree map so let's create a tree map and what we are going to do is we are going to iterate over our input array that is this array over here and we will store the keys so keys are nothing but these numbers that you see one two three four five six so for each one of the key we will store how many time we have seen this element in the array so one we have seen just one time two also we have seen just one time and similarly we will fill up the rest of the map so what will happen at the end of this loop is basically we will have this map created so that is going to be the first part of our algorithm right so let's put it down what will happen at the end of the first iteration is we will populate the map right my key is the numbers so these are the numbers and the value is the frequency how many times they have occurred one has occurred one time two has occurred one time three and four has occurred twice five and six has occurred only once right and now what we'll do is we will get the key set from this map so remember over here the key set will give us the keys in a sorted order right so let's say we get the keys into a variable and we want to iterate over this right we are going to iterate over this um keys that we have got so keys will give me this numbers right this one two three four and if i do a get on it i will get the corresponding values from the map right so before we proceed in further into the algorithm let's understand how our keymap is going to help along with the keys that we have got i have been passed past ks4 right that means each of the groups should have four elements present on it right so let's say i start creating my first group over here and i know that i have four placeholders over here i don't know much but i just know that there are four placeholders and also at the same time i know that the first value that will come and sit over here is nothing but the smallest key that is there right that's why we have used a tray map so that we get the keys it will come in a sorted order so i will get the lowest key over here so one thing i am pretty sure over here is that my group will start from one i don't know i can form the rest of the group or not at this point of time but i know that this group will begin with a one right and also at the same time i see that one has a frequency of one means one has been seen only one time so i know that there will be only one group starting with one had this been had this count been two over here instead of one then i am i would have said that there will be two groups that is starting with a one right but there is only one okay that i have started creating a group right so i'll say that this is my group in progress and i know i have started a group okay so what i will do is at the same time i will maintain in my queue i'll maintain in my queue because i need to track that at the first key how many group i have started right so what i'll be doing is i'll be using a queue in this case so here i have my queue over here and what i can say is that for the first key that i have seen that is uh let's put my keys over here for easier understanding so let's say these are my keys and my current key that i'm dealing with is a one for the first key how many groups i have started creating but didn't ended i have started creating one group so i will push that into my queue but i have started creating it but i have not finished it right because i know the size is k and i have not reached the size k yet right so what i'm going to do is i have to keep a track of the numbers right so i will say that let's take a variable over here last number scene so before i proceed with my iteration what i'm going to do is i am going to say that the number that i am currently at which is 1 is my last number seen and then i do the iteration okay we will complete the algorithm part later first let us do the try run complete the try down and understand the problem in details okay so this iterates and now what we get is one is done what we get is a two so here essentially i have to check a few things right so let's uh put those conditions over here that what are the checks that i am going to perform over here that i have the last scene number right so last in number plus 1 should be equal to my keys my key current key which is two so you see the last sin number is a one i do a plus one and i check is it same as the as my key yes it is same that means i am able to continue this group right so two can easily come and sit over here last scene we are checking and along with that we have to put and condition so if you have a group in progress and your last scene number plus one is greater than the key let me rephrase this one so it is better expressed as this so let's say if 2 is not there and 3 is there so my last scene number is 1 and the element that the key that i am dealing with is a 3. there are two checks over here so a group is in progress right so our group one group is in progress right and we do we did not see the two and we get a three our key which is a value which is three and our last scene is nothing but 1 plus 1 so 3 is greater than 1 plus 1 right that means i got a key which is not continuous right so in this case what i should be doing is ideally i should be feeling things right and say that okay i'm not going to continue let's proceed with this algorithm over here we are able to place this two properly over here but can i start a new group at this state so just think that here i could start a new group but can i start a new group over here so how would i identify that i'll be able to start a new group or not in this scenario so let me first remove this cross sign over here so what i get from this is account one right i get a count one and i know how many of my groups are open right i will subtract group in progress from this why i am doing this because i know a group is one of the group has been started which has not ended and i see there is only one two so this two will this two should go to that group that incomplete group right had there been two twos over here i could have said that okay one two will go to this group and with the other two i will start a new group so that's why what we are doing is whatever count i am getting from this element from this key i am reducing the number of groups that is in progress right so what will happen over here is for this index for this key uh which is a 2 i know that i cannot start any new group from this element can only contribute to a group which is already in progress okay so let's update this value so i know i cannot update my group in progress right because uh i cannot change it from one to two right it will continue to remain at the same value right and what i'll be doing is i'll be updating my last scene number so the last number for me at this stage is a 2 right and i iterate now i get the next key which is 3 right so for 3 you see how things are now fall into place so for three what i can say is that uh my key is a three my last scene is a two plus one so see this is false right false and group in progress greater than zero yes it is false and the true will make will keep this into a false state so it won't go inside to return a false what it means is basically i can still progress right so what i can see is now that i got a 3 and there are two 3's over here so 1 3 i can put over here and with the other three i can start a new group right so that's what i will do in do over here so for this guy what will happen is what we'll do is 2 minus group in progress right and what we'll get is 2 minus 1 right group in progress is 1. so i know that i can start a new group over here so this value will now be updated to 2 right so i know that at this point when i saw 1 2 and 2 3's i know i can continue my old group and at the same time i can start a second group over here and the second group also will have four elements over here so let me erase this and what i can say is that i will place a 3 in this group right which is the starting of this group so what will happen in this queue is what i am going to do is i am going to push a one meaning that i have started a group at the key three right and at the same time last seen number will be updated to three and i move on i get the next key which is a four and again you see first four how things will fall into place one four will go over here the other four will go over here so you see that over here now what will happen basically is when i do a 2 minus group in progress so i have 2 group in progress at the moment so i will get a 2 minus 2 which is a 0 right so i can say that i cannot start a new group at this position i can only use it for my existing groups so that's how these variables are keeping a track of things right so now you see what we'll do is our this group is now completed right our first group is now completed we will soon see how things will come into shape over here as well so what will happen is i'll uh i'll strike off 4 i'll update the lasting number to b4 when my q over here has reached the size of 4 or rather when my q is of the size of k what we should be doing is we will be re we will be reducing the number of open groups but how do i know how many groups to remove at this position right so i have my group in progress and which is currently at two but as you can see here one of the group has ended right so with the first k keys right one group should end right one or more than one group should end right i don't know how many groups should end had it been a two then there should be two groups that should have been ending over here so how would i update this so i will say so let's call it gip with love so what i'll say is whatever gip i have group in progress i will minus i will just do a q dot pool and remove that many groups so what will happen this will get removed right this will get removed and what will happen this guy will get updated to one right so we are doing a group in progress minus whatever the element i am getting from the queue now see with five in place what will happen again is i will put the five over here right and what will happen is ma now again for this guy what will happen it will be a one now my discount is one right we have changed this again back to one right so one minus one which is a zero so i am telling him no i am not starting a new group over here and as my size of the queue reaches k again i will do the same thing again gip group in progress minus q dot pool so what i'll be reducing is a zero because i know this key has not started a group so i am just removing those elements right so again when i uh change this and put 5 and i get a 6 over here what will happen basically is i'll put the 6 over here so again this will be 1 minus group in progress that is one which will be zero so i am not i know i'm not starting a new group over here right so what i'll do is i'll put a zero over here now you see group in progress will do again a group in progress minus q dot poll so group will progress will come back to zero right and we have exhausted all our keys over here now when we come when we will definitely complete this algorithm that we have started but what will be our criteria when can we say that we have successfully able to divide this so we will be returning group in progress at the end when we are done if my group in progress contents 0 that means no group is in progress all the groups has been completed successfully as we have done over here at in that case i can say yes i was able to put everything back into its place right and everything worked fine for me and so let me uh clear this board a little up and get the algorithm outside so that we can complete and also see at one of the few of the edge cases that there could be and how we should handle them right okay so i have got the algorithm over here for you so let me clear up these variables and we have a validate condition which is yet to be completed we have just put the bare minimum over here at the moment and we are going to see the few variables that we have used over here how we are going to put that so validate part we will complete we will keep some space for the validate part to complete and what we are going to do is um let's say we have a queue which is denoted by a queue so what we are going to do at every step that we did in the dry run is we have added to the queue right so we will do the same that we will be adding to the queue and what we are going to basically add is we have how we have found out the value we have used the key to get the value and then we have reduced the group in progress from it right so what we are going to do the same thing so we are going to do a map dot get by the key we'll get the value so that we get the value over here and what we are going to subtract this group in progress grp in progress right so this is what we are going to add and this will give me these values over here so we are going to continuously for every key we are going to say that how many groups we have started at this particular key right and also we are maintaining a last number seen so we will have that so let's say we initialize that with a negative value or something like that uh some irrelevant values and what we'll be doing over here is we will update it so this is this number is nothing but my key right it is just the uh just the value over here one two three four five or six this is denoted by the key so we are going to put that into place okay and also we have to uh have our group in progress thing properly in place so that value is nothing but the count of element at that particular key so if you see over here i know my group in progress is one group in progress is two but the moment i have two numbers that means my group is progress i'm dealing with multiple groups over here right we are going to look at the queue if my queue size so equals the key that is given to me right k is one of the parameters for our program that is four i am going to go ahead and update my group in progress right so how we are going to do it we are going to use the same formula so i'm just putting a shorthand over here minus equal to which denotes that you are going to do a group in progress minus q dot poll so the first element of the queue comes out and we reduce the size by that number right and we keep doing this again and again so we have seen one happy path example where things went fine and if this condition is ever met so let me get some space over here because our algorithm is partially incomplete over here so let me correct the indentation uh just keep in mind this everything that you that everything that you are seeing over here is inside this iterate of the keys right so let me indent it correctly so that it denotes that everything is inside properly right and what we are going to do if this validation fails is inside we are going to say that okay return or false so basically we are checking for the condition wherein things does not go fine right so if i am able to come out of this loop ever successfully so what i am going to return is how do i know that it's a valid case or not we are going to return that group in progress equals zero so basically when we are out of this loop if my group in progress is greater than zero i am going to say no boss i cannot split this array into eq like continuous size of key elements right i cannot because i have a group in progress which has not ended right if it is zero that means i have completed all the groups the way we have done over here right we have completed all the groups successfully right and uh now come now coming to some we have seen we have already seen one happy but uh now let's see some unhappy paths over here so far um we have just seen one happy path wherein everything was fitting in perfectly and we did it and we used the tree map and the queue in order to come up with the solution so there is one part missing to it so let's complete that part over here i'm going to cover a scenario wherein i can directly say okay no more going ahead we can stop it directly at this point of time so let's look at that scenario and let's get that fitted in our algorithm so we are going to see one such example over here so let's say i have k which is two so we need to do it for do group of two elements and we have an input which is like 1 2 right so everything is fine i created the tree map over here the tree map also looks good to me that we have one with the count of three we have two with the count of two so let's create the queue over here and take the variables that we have been using so let's maintain the last scene let's have our keys over here so for the keys we have a one and a two right and we have a queue over here a miniature version of the queue that we have used so this is my queue and what we'll be doing is we'll be start iterating and we'll be getting key one by one so we get the first key as one right so we get the first key over here and we see that okay everything is fine and uh we get account three we deduct the group in progress okay i have three groups starting over here so i put a three over here right so what that basically means is i have started three groups with one and one right these are my three groups perfect last scene is basically standing at one so i get the next value and everything look good right so it is not greater than key plus two group in progress is greater than zero everything is fine so when i use this key two to get the value from the map what i get is a two right can i go ahead with the 2 i have 3 group that i have started i can put it here and here what about this so the bare minimum number of values that i need at any point of time should be greater or equals to the number of group in progress right if it is not i cannot proceed further i can immediately say that boss it's not possible for me to go any further i am going to return a false right away to you okay so that becomes our third condition over here that we are going to put over here and that will be with our condition right because no matter what i am going to fail it so if that is true i am not going to check anything else its greater than whatever value that i am getting from the map for the current key if it is greater than that then i know that it's not possible for me to continue any further okay so in our happy path we haven't seen that right but when we take an invalid case that we see that it came to the limelight very fast right and it can happen for many of the situation right if you have a one two twos suddenly one three then a four you cannot proceed any further so you started two groups over here you continued the two groups over here and then you get a single three so this will fail if k is three right not when k is two if k is two then it's fine you will have one two and three four right so again this matters so that's why we are removing things out of the queue when we reach the desired size for one i'll put a two in the queue right and for two i will put zero because i haven't started any group over here right and the moment the queue size is equals to the size of k i am going to remove this two and i am going to do g i p equals to g i p minus q dot pole right which will reset my gip to zero right so when i get a count of three and the value of one at that time my group in progress is set to zero so this will take care of that condition right this is how this algorithm works this is very simple algorithm a little tricky but not difficult i hope you got the concept behind it you got the thought process of how every variable over here is playing a crucial role in order to control the output of the function right so let's head over to the lead code and implement this solution in the code and see how it goes we're going to check the code over here so first we'll have a preventive check wherein we can check the length and we can do a mod with the size k if it is not zero we can simply return a false right that means we do not have the multiples of k elements over here so we can just simply say that we are going to return our false okay otherwise we are going to create a map and it is going to have the integer key and integer values right and let's call this a map and let and this should be our tree map implementation right and we are going to have a loop over here and we are going to iterate over the nums and we are going to populate the map so we will put num and for each of the num what we'll do is we'll check in the map so we'll use get our default so that even if the key is not present we can get a default value from there and we'll default it to zero and we'll increment it by one right so at this stage what will happen is our map is now ready now what uh now we need a couple of variables and the cube so the queue will store the integer in the queue and let's call it q and let this be a linked list implementation oops sorry okay now the next thing is we need couple of variables one is group in progress okay which will be initialized to zero and let's say we have something called a last seen value which is initialized to minus one now what we'll do is we'll iterate over the keys and we will process the key one by one so and now once we have the key the first thing that we'll be doing inside is um implementing the checks that we have talked about right so the first check is so let me put it over here if group is progresses grouping progress is greater than zero and we need to take the key should be if key is greater than last seen value plus one that means something is wrong right we can just stop processing at this point so basically here we'll be returning a false right and along with that we'll have our condition wherein we talked about the other condition right the edge case condition that we need to ensure so we will see group in progress so let me get this conditions down for you guys if group in progress is greater than map dot get off key at the condition that we have already discussed and then otherwise you need to add to the queue and we will be doing a map dot get by the keys and we'll be reducing it by grouping progress so that's what we are going to add into group in progress and for group in progress itself so once we have updated it we are going to do a map.get to do a map.get to do a map.get by the key right okay and we have last seen value that also needs to be updated at every point so we are going to take care of that this is nothing but our keys or the key sorry okay so now if my queue has reached the size which is equals to the k then i need to pull things out and i what i'll be doing with that value is i will be reducing the group in progress let me get some space here that pole over here and when i come out of this loop over here what we are going to do is we are going to do a return off so if it is not zero then i cannot say that it is possible let me update this over here this type over here good let's uh do a submit and check for the broader range of test cases yep we are good so yeah it has been accepted it has um uh performance better than 50 of all the submissions so again i hope you got the solution over here how we are using queue and the tree map in order to come up with the solution so this solution is far better than the priority queue solution the other solution but the code is simpler to understand definitely so i'll try to make a short video on the same so once again i hope i was able to clear your doubt and this goes out to anish i think i was able to clear up the doubts the thought process behind the algorithm for the same so you messaged me 10 or 12 days back but i am not much active on facebook so i was not able to get the message but fortunately i came across your message and i hope i was able to clear your doubts so do let me know what you think about this video do give a like if you think this solution is helpful before we end this video over here so let's uh talk a little about the complexity part of the solution over here for this part of the algorithm where we are iterating the map what we are doing is we are iterating over all the n elements in the array and in the worst case this is your this is what your runtime is going to be right and for space also you are going to end up creating order of n space you are going to take in your map so just consider a map having values like this where there are no reputations so you will end up creating 10 elements inside your map right you will have 10 keys with frequency one right and then over here you are starting to iterate over the keys again so again i will say that this is going to give you an order of n in the worst case right you can have n number of keys where n is the length of the array and what you are doing is you are putting inside your queue every time you get a key right so again your space is going to be order of n space for the queue and this is for your iteration right so you can see that we are bounded by order of n everywhere literally everywhere so yeah this is the order uh this is algorithm which will have a order of n run time and order off and space as well okay i know that we are iterating multiple times so you can say that order of two n or three n but that two or three doesn't matter right what matters is you're the variable part the constant part never matters to you so yeah that is all from this video i hope you got the simplicity of the solution you understand every bit of the code or the solution that we have discussed over here do let me know what you think about this video do give a like if you think this video was helpful that will be of great motivation for me as well yeah so that's all from this video thanks anish once again for recommending this problem i think this problem was nice and one of the good problem to be to have in this in my channel and to others as well do let me know if you want me to solve any problem do reach out to me anytime for any problem maybe from lead code or from any other platform or any offline solution or even any concept related to data structure or algorithm i am free i am ready to create the videos for you so yeah that's it see you guys have a great day | Divide Array in Sets of K Consecutive Numbers | kth-ancestor-of-a-tree-node | Given an array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can be divided into \[1,2,3,4\] and \[3,4,5,6\].
**Example 2:**
**Input:** nums = \[3,2,1,2,3,4,3,4,5,9,10,11\], k = 3
**Output:** true
**Explanation:** Array can be divided into \[1,2,3\] , \[2,3,4\] , \[3,4,5\] and \[9,10,11\].
**Example 3:**
**Input:** nums = \[1,2,3,4\], k = 3
**Output:** false
**Explanation:** Each array should be divided in subarrays of size 3.
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `1 <= nums[i] <= 109`
**Note:** This question is the same as 846: [https://leetcode.com/problems/hand-of-straights/](https://leetcode.com/problems/hand-of-straights/) | The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way. | Binary Search,Dynamic Programming,Tree,Depth-First Search,Breadth-First Search,Design | Hard | null |
1,937 | hey what's up guys this is chung here uh so this time we called number 1937 maximum number of points with cost okay so you're given like i'm by an integer matrix right points and we want to maximize the number of points we can get from the matrix so the way we're getting the point is that we will pick each one cell obviously we'll pick one cell in each row okay and after that we'll get the points right of this row and column but you know but what there's a cost so what is the cost basically you know the cost will be after picking the difference between the column of the two of two rows so which means that you know if you for example you there's like this cell right if you pick this one right this one you pick this one and then the second time let's say you picked it this one then of course you'll get both of the points uh in the cell but since the column difference is what as you guys can see it's this one right so zero one two so there will be a p1 right plus p2 minus 2 in this case okay assuming this is on p1 this is p2 right so that's basically the cost and our task is to find the maximum number of points we can get right for example we have this uh this a three by three grade here a matrix so the answer is nine because three five three right and the column difference is between these two is one and between the third and second column third and second row is also one that's why eleven minus two will be nine right and here's another example right and there are some constraints right so both m times m n is 10 to the power of 5 and also m times n in total is also 10 to the power of 5 right so i mean for this one obviously this one is a dp problem right and i guess most of people can at least get the first uh solution not it's not a solution because it will tle which is the uh you know we define dp uh inj right the dpi in j means that you know the maximum right the maximum points we can get the maximum point we can get right uh ending right ending at this inj right so if we define the dp in this way right so how can we update how can we uh write the state transition function right i mean obviously the brutal force was like what it's like this uh so basically we have a we have this row right we have this row here and we have this is a previous row right so this is the previous row let's say this is i and j right so this is i and this is j this is i minus one okay right so let's say we're trying to get the maximum point for this cell right so the first approach is that obviously you know we just simply loop through everything from the previous dp right because you know from the previous dp you know we want to check each of the cell right we want to check each of the cell and then we want to see from that cell to here what's going to be the points we can get right and after that and that's going to be dp of what so basically dpi and j right equals to the maximum right the maximum of what of the dp i minus 1 and then k right here we have to subtract the absolute difference between the uh between the k minus j right so that's going to be the first dp transition function right where we have to check each of the previous uh element from the previous dp state right and then we compare okay which one can give us the biggest one right to the current one but as you guys can see right so to check to loop through everything uh so basically so the time complexity for this one is what so we have to go to uh i'm rows right we have m row and three for each row right sorry yeah for each row we have to populate n columns and for each column we have to loop through the previous uh the entire previous row which is going to be what n squared right so this is going to be the time capacity for this one but remember m times n equals to 10 to the power of 5 and n is also to the 10 to the power of 5 right so if it's this one it'll tle right uh that's why you know we have to come up with some improvements so what's going to be the improvements you know so if you watch this one close uh closer you know obviously you know the path right so the optimal path for this inj either comes from left or come from right or coming down below here right or from the cell above him or from the left or from the right and so basically in this case we can use another dp concept to calculate the entire row instead of uh instead of looping through instead of for each of the cell we loop through the previous state previous row again so how can we do it let me draw another let's say we have a dp uh this is dp right uh i minus one right so let's say we have like this i'll just draw a few and this is a dp dpi right have the same cell column right so let's say this is the one we're trying to get okay so this is the j right and from left okay so let's only consider the left side okay so we have what so let's call this one uh how cause p zero right it's not uh how quiet what so this is gonna actually the dp right so let's call it uh d1 d0 right d1 d2 d3 d4 and d5 right so from the left you know okay so for this dpj right so for dp i and j right so from the left side it's going to be the maximum of what maximum of as you guys can see we have d0 minus what minus -5 right and then minus -5 right and then minus -5 right and then d1 minus 4 right d2 minus 3 d you know what let's do this j so we can write the uh some shorter codes here d one okay so this is gonna be d zero minus four d one minus three right and d2 minus two right d3 uh minus one and then d and d4 itself right so that's the uh that's the max value we can get from the left side right how about the j minus one here how about this one so if we uh dp of uh i j minus one right so what's the uh so what's the value for this one from the left similarly we have max it's going to be d0 minus three in this case right and then d1 minus two d two minus one and then d3 right so this is the dpl of j minus one i think you guys already see a pattern here right so see this part and this part they're exactly same and except for what if we use this one the dpi j minus one do a minus one of this one we get the dpij right so that's why you know if we calculate as you guys can see right so if we calculate the uh the dp the new dp from left to right we don't have to compare everything from for the previous row all we need to compare i'm going to compare is the one above us right and the ones on the left and then we do a minus one for the ones um on the left basically these two right so which means we only need to compare two things now we have what we have dpf i j right this is going to be what max of dp i j minus one and what under the dp i minus one j right so now we have this uh state transition function so this is the one the this one from the left right this because we have we can use this one to give us everything we need right for this part and then the last one is this part which is this one right so now as you guys can see uh instead of n square to check the new row we only need n of n because oh one more thing we need to do this twice right one time the first time we scan it from left to right to get everything from the left side and then the next time the next one we scan from right to left because you know because the optimal path could come from the left will come to coming from the right and then we get uh between the left and right one we get the bigger one and then we use that one to populate the current dp yep so i think that's it right i guess then we can start coding right we have this one point uh m and n right point okay and then for dp uh you know since we only need the previous one row of dp so we can just compress the space complexity into one dimension dp right which means we only need to we only need the dp to store the previous rows uh result right so at the beginning uh it's this one right because for the first row right the there's no previous there's no cost right so we just so the dp value is the first row of the point okay and then i'm going to define the left and right okay so for the left and right okay so basically this left and right means that you know the biggest one we can inherit and we can get uh from left side or from the right side okay and then for i in range of 1 to m right so first we scan from left to right which is while j in range of n right so if j is equal to zero right then we simply do a left dot j equals to d p j right because for the first one there's nothing on the left right else as we do a left j equals the max of left like j minus one right and then minus one and then dp dpj right yeah okay so remember so uh before when i draw the diagram i use dp uh dpr i j minus one here right um i think we can use the same thing but here i just separate this one into two dp array here just to make this code uh more uh much clearer right so which here we have two dp uh array here one for one from for the left from left to right and the other ones from uh for the right to left okay right uh and then the next four loop is for the right one okay so it's going to be n minus 1 right so this time similarly if j is equal to n minus 1 right then we have right of j equals to dp of j right else right j equals the max of this time is going to be right of j plus 1 right and also do a minus one right of dp j okay so yeah this part is it's pretty obvious right because you know even from the right side so every time we also need to do a minus one because the difference right it will always be increasing by what from the neighbor right okay and then the last four loop will be like this right simple we just need to do this dpj right so now this time the dpj will be what will be the points right of the current one which is i and j plus what plus the bigger one right from either the left or the right to this one right j okay and in the end we simply return the microsoft dp so i think that's it right if i run the code okay accept it right and there you go right because obviously this one is what the time complexity for this one the first is the m right and then we have another n here time m times it right uh yeah i think that's it right i mean this one i know i think it's a little bit tricky uh i think the first one is pretty easy pretty straightforward where like you know for each of the cell we loop through everything from the previous uh row right and we try to get maximum from it but you know it turns out we don't have to do it uh for we don't have to loop through the entire previous row for each of the cell instead we can use another like dp concept for here you know this one actually you know i think similar i remember there is like a problem called trap raining water right i think for that one we also use something similarly for this one i think for that one we also use uh define like a left and right uh dp and then we populate the left and right and then we use we choose which one is bigger right in the end so similarly for this one right because um i think i already showed you guys why we can uh make this transition right because this one includes everything for the current row except we have to do a minus one right and yeah i think that's it for this problem and thank you for watching this video guys and stay tuned see you guys soon bye | Maximum Number of Points with Cost | maximize-the-beauty-of-the-garden | You are given an `m x n` integer matrix `points` (**0-indexed**). Starting with `0` points, you want to **maximize** the number of points you can get from the matrix.
To gain points, you must pick one cell in **each row**. Picking the cell at coordinates `(r, c)` will **add** `points[r][c]` to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows `r` and `r + 1` (where `0 <= r < m - 1`), picking cells at coordinates `(r, c1)` and `(r + 1, c2)` will **subtract** `abs(c1 - c2)` from your score.
Return _the **maximum** number of points you can achieve_.
`abs(x)` is defined as:
* `x` for `x >= 0`.
* `-x` for `x < 0`.
**Example 1:**
**Input:** points = \[\[1,2,3\],\[1,5,1\],\[3,1,1\]\]
**Output:** 9
**Explanation:**
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
**Example 2:**
**Input:** points = \[\[1,5\],\[2,3\],\[4,2\]\]
**Output:** 11
**Explanation:**
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
**Constraints:**
* `m == points.length`
* `n == points[r].length`
* `1 <= m, n <= 105`
* `1 <= m * n <= 105`
* `0 <= points[r][c] <= 105` | Consider every possible beauty and its first and last index in flowers. Remove all flowers with negative beauties within those indices. | Array,Greedy,Prefix Sum | Hard | null |
1,417 | yeahyeah Hi everyone, I'm a programmer. Today I'm going to teach you a new problem, which is the problem of reformatting a string. The problem requires us as follows. An age that only consists of letters and numbers, in this place it only consists of English letters without capitalization and numerical ideas, our task is to find a definition of this Age so that There is no letter followed by a letter and no number followed by another number, so we don't have any adjacent sequences that have the same pattern. means having the same letter or number. Yes, we will have to return a permutation that meets the above requirements of the Big Card. If there is no permutation that satisfies, then we will return the subject. Yes, let's go to the example of one of the people giving us a string a0b one c2, then we see that in this place people will be able to make a number of positions that meet our requirements. That problem is A0 A1 B2 c then you can see that there is no digit em why it is a now the word following a is the number followed by a b is the letter em why b who is the number and according to After CO2 comes c which is the letter a. Please make a typeface, then follow it with a number type and then follow it with a typeface. You can't have two that are consecutive, it's the same type and it's over. In the second example, we see again this word logic. The input is the logic: there is this word logic. The input is the logic: there is this word logic. The input is the logic: there is no permutation that can satisfy the requirements of the problem. Because in the topic, we see that it is all words. There is a number, how can we reach an age when it has both storage and wolf alternating and then passing with the third season, it's the opposite, it 's a string. then we are 's a string. then we are 's a string. then we are not about to reach an age that is both ugly and the word is used by monsters 4 now we can see it again because the word she wrote in 2019 let's rearrange it into c2o no v11y 9D a la This place can arrange a single permutation. Hey, the example five is the same, so in this example, what you see is that it can be arranged. You can arrange 4 permutations, so we only need to return one of them. These four permutations are the requirements of the problem. If it will accept it, then we have grasped the requirements of the problem. Now we think about the Buddha's solution in these problems, then the solution to the problem. Hey, I don't think I know how to pedal very well, so according to my way of thinking, I will have to figure out where I have to eliminate the places that don't have enough numbers. The number of characters and the number of numbers, the number of characters and the number of numbers, is enough to meet the requirements of the problem. I see that it is only necessary that one of the two be more than two units above each other. Saturday has two numbers of quantity words that are more than the number of numbers and is a quantity that costs two more units than the number of words. I don't have to lie down. I'm about to get what I'm learning. There's a string that I can see. The title of the lesson is okay because well, there it is. For example, the number of numbers and the number of letters should be equal or 1 unit greater or less than each other, for example in these cases, letters and numbers are The letter is three and the number is three, then I combine this team or now I add another number. If I add this one number, I buy the number at the market at the end, for example, I add the number 3 to make it zero. 1 b 2 c 3 is still accepted or I add a letter if you add a letter on the screen without adding it at the end Because according to the bag at the end it is a letter and I add the beginning to the beginning using decoration dd0 A1 B2 c is still fine. But if we are above each other, that is, the number of these two things is 22 values above each other, then these two things is 22 values above each other, then these two things is 22 values above each other, then I can't add them all because it will definitely be one. The times I repeat it in a row, with an idea like that, first I think I will have to find the quantity, I have to calculate the number of letters and the number of frequencies in the original place. Well, to do this problem, I will install it in Co Lan a language and then first I will report the results as usual without calculating my results now will be the string after calculating I will Returns a cause and effect result, and so on, I will have to calculate the number of letters and I will have to save it in a piece then I will also calculate the number characters, then Then I will compare Han's quantity and the length of these two items. After the length of the two pieces is satisfied, I will continue. I will take these two pieces to create the resulting cabinet. I'll report a piece. The piece is a laser from my company. I'm like cursing. My second name is you kill. It means it's just a number. Now I 'll pass the initial place with 'll pass the initial place with 'll pass the initial place with Yes, the syntax keyword. The game is in Vu Lan, I don't care about Intex, so I let this be a tiled mark. I just need to get the order right away. I set the order to C Yes. Then I will go through all the elements and symbols. The letter in the letter s is now to be able to distinguish it. It is a two-digit string that is the order of cursing the two-digit string that is the order of cursing the two-digit string that is the order of cursing the digits, so I will use a Pham Library. I will print bubbles into an ideology. That's intentional. Now I'm going to call a Ha in this connection. It has a function name called laser printing. I'll pass it a character and it will check for me whether it's a character or not. It's a number Yes, if you curse, it returns Chu. If it's a number and then answer the phone, then if you curse again, I'll give it this momentum for the current character installed in my life update and I don't remember just dialing it. okay now the one year old piece my skc tree is a character type because it's a byte type Okay now comes If it's not a word then what letter will I add to it help put it in the table help me At the end of this round, I will have two groups, I will have two pieces, one piece is the letter and the other is the number, I think I probably have to use the quantity of this piece tree a bit. There are many types, so I will declare a piece so I can retain its value. It's good that I don't belong to the piece, but this is the number of the piece and the number of elements in the remaining letters. Now is the number of elements in Len's code, then kill the boss as mentioned above. First, I have to call out the places that have the length of the two mothers. Wrap it up with the guy that has the proof. of the word for the butt of the ah which is larger but equal to two or Yes the link of the word - for the proof Yes the link of the word - for the proof Yes the link of the word - for the proof of the sore which says smaller than or equal to minus 2 which means that in this case it is a less word These two numbers are asking, Ms. Is this meeting a number less than a word? Then I will have to return the value to sir. Now I'm sure to cut it to make it beautiful and not ugly at all, then I will return to suicide but ask her to come back. She said that if she wrote without any questions, I would return to the product. If she just passed this test control, then the voice is definitely valid, now the next task is to do it. In my opinion, you have to find out if there is a chance to meet again, then to find a place where there is a chance to meet again, that's the first thing I will do if it is, there will be 3 cases that happen in the first hour of class : the chain network and The : the chain network and The : the chain network and The number of pieces will have the same length. In this case, it's very simple. I just need to browse from beginning to end the length of any of the people creating leads to each other and then I Just automatically the bottle holds the result alternately and digits then it will come out but in the 2nd and 3rd cases that is the case where curses are one unit more than the number of animations plural fonts So now I don't really care about that one unit. That means it will be exactly 11 digits 1 or a letter, then I only care about me and I would like to choose the brother's age and the result according to The length according to the lengths that you two follow the lengths without trusting each other. Then I will calculate the number above each other. If it is a word or a number, I will calculate it later. Well, now the first thing I have to do is find the length. What is the minimum space I need ? I call it ? I call it ? I call it the endless battery, the movie I visit every year is about a kilometer. Then I'll check the number of molecules of the word, if it's smaller then I'll give it to my mouth again but if you get to the number of words then this element is to find my meme. I don't. Now I don't know which one is bigger, which one is longer, which one is one character or two are equal, then I'll just take the first one and text him the number, but I'll check and give him the small number of stickers. If I change the address again, then I will have a meme. Now I will select this result for VSIP II so y + + then Place This way, just so y + + then Place This way, just so y + + then Place This way, just page the number of that number. Now I give previous number, Mr. Yes, to know the y, then look and choose for this letter and mother, then after this life, if the case is that the number and letter are equal, then I will return the result. That's fine, I see that's the truth. But for case 2 and study Three, I have to have one more variable. I see there's one more test condition here so I can handle that guy. There's a number left over at the end. If it writes two, it means it's blocked here again. Whatever makes it fun, it only has one row left over than leaving a number of business in this school. cursing it more than the number I knew just now, this string is the starting letter, the starting number is a number, let it go to the letter, then it goes one after another like that. At the end it will output a letter at the end, don't you? I hate what I can. Join the remaining letter to the end of the string. I have to write the first part of A so that it is a letter and come to numbers and letters. Let's learn this is this letter. It's not the first or last word of the meeting result. So where should I put it? I'll put it here first. Yes, I'll leave it here and ask for the positive values, then I'll give you something. But the case now is that there's only more, and the case where the remainder is a number, isn't it? is a number, it is the number of dogs, it must be greater than the number of words, right? Then now I will have to match the letter, this number that is left over at the end gives the owner the result because of the result cabinet Right now, what I want is to rebuild the number of letters that end with the letter a, so I have to follow this number at the end of the letter Yes so that it doesn't get subtracted. Anh Ngoc That's what I said. I think I have solved all the cases of these problems so I will always follow the syntax. Well, let me commit suicide, here is a corrected syntax. I forgot my wallet. let it be 0 Yes then it will solve for whether one but you see the example a few are easy to succeed Now I see I'm about to know let's see if I know anything else Yes okay So it has solved everything including other applications of the problems according to my algorithm. Well, before ending the video here, I will calculate its complexity first, the complexity and complexity of this algorithm. Then I see that if I call N the length of f, then I have a filter that goes from the beginning to the end of the Asia chain and a second filter round, the nature of the second filter also goes to the maximum which is also Energy two. Is that right? Why, when we go through this situation, the letters and numbers are relatively close to each other, so it's not like we're born, but we die in the filtering cycle and have that. When filtering a lot of serum, it must be someone who does it, but the storage space I see I use has two manual pieces. This version has a moving length that depends on the name of this input owner. How many doors are there, how many numbers are there, but I see that its switchboard is still impossible to get through, so the storage space for me is also you in the ring. So I have a little now. If you find it interesting, please give me 1 like, 1 car and share the experience. If you have any comments, such as if you have any questions or if there is a better way to respond, you can leave a comment below. Thank you. You guys say goodbye and see you again yeah | Reformat The String | reformat-the-string | You are given an alphanumeric string `s`. (**Alphanumeric string** is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.
Return _the reformatted string_ or return **an empty string** if it is impossible to reformat the string.
**Example 1:**
**Input:** s = "a0b1c2 "
**Output:** "0a1b2c "
**Explanation:** No two adjacent characters have the same type in "0a1b2c ". "a0b1c2 ", "0a1b2c ", "0c2a1b " are also valid permutations.
**Example 2:**
**Input:** s = "leetcode "
**Output:** " "
**Explanation:** "leetcode " has only characters so we cannot separate them by digits.
**Example 3:**
**Input:** s = "1229857369 "
**Output:** " "
**Explanation:** "1229857369 " has only digits so we cannot separate them by characters.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters and/or digits. | null | null | Easy | null |
212 | okay 212 word search to give me a 2d board and a list of words from the dictionary fine all right so no in the boy each one must be construct from a letter of sequentially adjacent cell where adjacent cells are those horizontally or vertically they break the same letter cell may not be used more than once in a work with make sense I guess this is a standard dish evening hmm I mean this isn't that hard conceptually is just a tough first search with maybe some pounding I mean yeah I always find these maybe it's fine no what I was gonna say is that I always find these like I wish they gave you their constraints but then like I also complained about that I also complained that two constraints are not good enough in a sense that uh because when you're given a constraint yo you look at the worst case scenario and you know and maybe for this one they just want you to do a task research and then like I don't know it's that - oh wait no maybe I miss oh no tell me something about where you could sneak around so there you go just only go up down that way that's oh wait can you yeah you can okay no it is like Bongo where you could go off down that way Oh like you can sneak around okay yeah I mean I guess that's just stuff for search but then as I was saying I'm gonna complain about either way because I don't know how much planche am pounding that they want me to do is there a lot of like optimizations you can do in the general case but uh yeah I think that's my annoyance for it I mean it's just some of this is just that I don't really know what the real constraint is I think that's why I have annoying and like because it's like just my algorithm because this algorithm doesn't work for all cases but it only works for some subset of cases and if you could guess it then it's right and I think and this type of clam is fine in an interview because I have one person but like I just teach so the things I'm thinking is and dependent constrains is it good enough excited like cetera but if I'm like looking on a problem on a thing like I don't know what the real constraints are but uh okay I think I mean also depends on the size of words for example like type don't try it maybe depends I'm mostly I'm lazy but like I don't want to I don't have to that maybe I you know yeah okay I guess I'll put a try and then just definitely search I think that's fine will be my approach so that you could take advantage of kind of multiple words at the same time kind of thing so you know so you can at least get rid of a constant of the words or something when I okay I haven't done just in I mean I know how to do this and wake it up - I don't know to do this and wake it up - I don't know to do this and wake it up - I don't know I'm doing this way and they code Python so Lucy okay which ways to put a face case yeah that's fine the past word like that much mr. Bruck I wonder which one's right I should make optimization there neither value except output I cash it recently I've been mostly to or not recently anymore but my last job I mostly didn't go and back and stuff before that I did pipeline a bit and before that I did scaler a bit and before that I did C sharp and Java from her so a lot of what he's all over the place dad tiny to run mm-hmm you know I'll dad tiny to run mm-hmm you know I'll dad tiny to run mm-hmm you know I'll just do it in person to keep it on the question maybe University your dentist may be slightly efficient in destroying stuff Rosi No maybe this is it having done haven't voted a trifle scratching a while sir hmm I might just open anything useful except I should put like four times maybe okay that's what I expected which is good maybe that's with you bugging well not even debugging just do a sanity check a little bit I guess I could actually just point out a word okay however try mmm like that just touches from memories and I may have got any mum swapped no good Stoker I think yeah most recently I've been actually playing around c-sharp and been actually playing around c-sharp and been actually playing around c-sharp and unity I imagine it earlier so just playing around and I try to do most American five fun just let's practice I don't know if it's just in one language moment anyway it's just so good that he's passing to life stuff we just put away to do the backlash is to one keep the roof no Chuck I can't anyway it's just that maybe slightly better to check out I don't know maybe I don't leave I take it out it's a keeper yeah no this is it what I know that is this is not tomorrow you fishing right but all right it's gonna focus on getting it right first and then week after my stuff pleasure mostly to destroying creations now at this and it would call to one-time purchase I won't do the one-time purchase I won't do the one-time purchase I won't do the optimization we were talking about yeah when you should doing it very specific order but I've been kinda you okay but your statement like that actually we're multiply 100 edges I should cash it you and I'm missing something there are two visit I know just going to do this first I told myself I would do something back together it is I guess a head case not a bad answer and I was like except it was too that decided I know I just wanted to see where it stuff this so I was great focus on this one but thank you as wrj for subscribing I don't know again actually don't try to make money off this I will probably not probably definitely I don't like I stay probably I definitely if I actually I see any of this money from twitch moto nated to some charity why do it okay well debugging is what I'm doing okay that's why yesterday I could I never can discuss I think today she's back today in the last weekend before I can't even get one that's crazy ready stem eats some colors and you're running before ever time because they're never reused before okay well it's good to I test it shaver yeah I'm gonna answer your question afterwards I think I'm close maybe so once I finish this I will answer your questions I focus because I'm kind of get bad at this we gotta stay with me thank you pick up clothes clean I'm not I don't know okay why is that how's that given an end like I'm laughing like that's not good enough what's up what the heck nicely I think two letters at a time maybe that's why my stuff is weird oh wait what is this me don't ever do that on the other day but I do it twice I don't know maybe [ __ ] me oh yeah I don't know maybe [ __ ] me oh yeah I don't know maybe [ __ ] me oh yeah well did I tell me should practice that okay oh there's an off by one that's fine baby we're treating mm-hmm we're treating mm-hmm we're treating mm-hmm I think my recursions fine at ease it's because I'm dumb well too many professor chiu qualms today but that's why that's my story and I'm sticking to it oh that's a good point I'm gonna probably get it right first and then we could yeah I do actually I mean I kind of parallel it in that I do it in a try defender when you meet my pal I mean yeah there's all you could paralyze it on top of that okay yeah that's tell me then theory in a conversation that's what we talk about well like an intimate conversation oh I guess you were responding to what tux was saying yeah all right no spoilers first let me try to okay you're a second let me try to finish there said there now I'll read over the comments a little bit look I mean I get this way I just don't return it so good so make my test fingers ball without a knife I'm running this on the construction first so don't put on and leave then it's true that's my definite search awesome believe that no this is not right this is only my fingers just weird mocha oil damaged if you burn but still I feel like that's gonna be some off by one evening let's try poke baby okay I mean kind of like trying more stuff and I also I am lazy so I might just submit this and hope that it ones because they don't give you two there are constraints oh yeah go either way hey looks like people are having a blast and a chat I'm trying to not look to be honest so I and not like to be mean I'm just trying to make sure I get this first what the kids say ah now huh did I miss a visit I don't put R is it on the first one okay then okay that's a circus because I chose to put it here instead that was the decision I made instead of putting dead before the recursion but I should have had that as a test case maybe yeah I guess there's no way to modify this to be similar okay maybe I don't like it okay if it's wrong again I'm just gonna be sad okay cool so I mean okay that was a silly mistake bit but it's just nothing too crazy but yeah cool wow there's a lot of cars you're gone but uh all right let me talk about his problem and for a second I mean I basically did like ready proof foresee things I mean made my coke oven cleaner and that may be why should have been yeah what's not that watch I don't think the build try thing yeah essentially I build the try so that you could so you don't have to go through the entire dictionary every time do we elevating the recursion I think there's some like trust you have to put on there to constraint the system that there's a one in time which I think I'm like in the median ish i don't you know i'm not exceptional them okay the optimization you're gonna make for sure which i did not necessarily make and this I have to but yeah I mean I sort of try was there to optimize down a little bit it tries a way common data structure that people will assume you or you should demonstrate that you know what a try is and how to use it and in this case even how to build it and versus tougher search and then even tougher search sorry give same death for search based just exhaustive search way because let me it's recursion that I stopped I guys stop complaining though but yeah as an exhaustive search with natural bound on based on what you get from the edges and the nodes and you know where you're on the try and so forth so you have kind of essentially like states that you have a lot of them to do you know that's many ways like yeah I mean it's kind of weird because I feel like for example if you have I don't know a 10 by 2 bored of all A's and you have just like and your voice are just like twenty a night of AIDS or something like that probably already should make it one out time I think give or take if not then add like another ten A's right or something yeah so I don't know so I don't feel I mean this is one of those problems were like you can optimize as much as you can and you can optimize as little as you want it's kinda how strict about it and on an interview definitely as I was saying kind of course slash complaining in the beginning and an interview that's where you know you can figure out the part or the approach to take because you have someone to bounce your things off because in this case you just don't know what n is you know how many were tender dictionary you don't know what how long those strings are in the words in the dictionary which and also complained about earlier which is that even if they give you those constraints you're gonna plan for the worst case which maybe is not in the test case so that's the thing that if this is an interactive or with violence move another person asking this fall then we could kind of have a conversation about a lot of these decisions that we make along with Bobby what I would because I feel like this I haven't been followed up but yeah just a lot of conversation in a chat so yeah uh I don't think so but I don't think this is uh you know actually I guess you could tell you could definitely convert this into an explicit stack action yeah you can't really tricky because of the way I did it anyway I actually I mean pythons have been around for so long I can't imagine it doesn't right but I'm also not to be frank Python expert to that degree so yeah if someone else find talent maybe know then actually I would know put a future to the background estimated time tree oh okay yeah like I said like so tux made a comment or tux your love and made a comment about my guest delivering the real point which you're given the size of the dictionary which is I guess yeah I agree that uh that's quite good like you just have yeah you can at least like play about the numbers and like what's the worst cases cuz right now I'm just like one wine and it's a little weird and I'm looking at a blacks is code give me a second real quick let me finish ranting about this and then I'll go over in Mexico but uh yam you know it's a hard problem but it just combines to two things you should know which mainly isn't always easy to do that thing but uh there's a try and a solver search I think this like I've seen this on an interview for sure and my colleagues PI have asked it I don't ask these type of questions generally so but uh so definitely I think yeah I mean but that separates the leak or part of it in that a lot of the value of an interview they're allowed to value that an interviewer gets from this forum is the conversation about like that case it to the exhaustive cases the education system erst cases and all those stuff and love meta conversations and things that actually are brought up in a chance like you know if you paralyze things yeah how would you paralyze it and I can you paralyze it how do you make it motivated and stuff like that so you have to all wait tricky problems and stop that but yeah as a part of interview that's why where they would get the most value and kind of see where you at and this enough code that you never could fight bad code so I think did I do a good job I did an okay job I think into exceptionally well bit but I mean what are my functions are like five lines so I think maybe that's okay there's some assumptions about you know can it define them and use them anyway twice for minute but uh yeah uh I feel like I'm okay with my I did maybe that's what I'm waxed it uh yeah I could created a thing from do I mean go API definitely is between err I mean that's what you would expect for me man I just switching from white mode and black mold is actually now a little thing back is that's what I did go try makes me guess I could have returned it tried and subject afternoon just note in it have more abstractions on a PR and that I think that's fair and I think that's what I should have done if I were to kind of go back to a little bit you have a graphing to now and you pre-processed assist into a graph which pre-processed assist into a graph which pre-processed assist into a graph which sounds like an overkill but and I don't know but uh I guess I mean if you say it's fast enough you know I believe you yeah and embedded naming cuz I think I just named it n but uh oh yeah definitely I think I do like using try oh no sorry I know it's not your bad I'm just making fun of it because I think everyone to be honest I think everyone uses dark mode a dart team and I'm like one of the weird people who still uses like team I mean what I just need to do it for like a week and then not complain about it and then get used to it I think I've been I've just been doing this all my life of like team for whatever reason because I think back in the day I guess people didn't know better or whatever I don't know so now it just feels a little weird I don't know like I'm not in a bad way it's just like a subjective thing and in a way it's subjective worse for me because it's supposed to be worthwhile your I but yeah I definitely need a few things a little better and also maybe yeah and like this stuff I'd ever could abstract it so glad that you know what it means and yeah so definitely I could yeah so I could definitely uh abstract this a little bit if that's what Optimus him for I haven't one thing I point out like when I'm interviewing one thing I do say is like I'm just I'm focusing on getting up all my time focusing on problem solving for we could refactor things a little bit later after I kind of start with that and depend the interaction and depending interviewer you know you figure out how to write the code Ivan for me that's how I think about it know me I think it fine I mean I essentially I mean we still solved the same problem it's you know like it's essentially an implicit graph versus an explicit graph and in this case I mean in general I mean I don't know about whatever on this particular case well in this particular case too but in general obviously an implicit graph use less memory but depend of how complicated your rule set is for kind of constructing the graph sometimes an explicit because yeah you know because the cost is that I have to do these checky things a lot and maybe this is a function that you know in a way I'd use multiple times and in that case a quad for some kind of weapon representation if you make it explicit and you sent your cashing it up you will if not I mean I don't know I mean you're such things to play around yeah adjacency graph and so that guy's he said you'd like maybe cash is not a great more than that when you build a data structure that you know allows you to not to repeated calculations and here it's kind of okay like I mean for me I mean I like you could definitely still make it cleaner but oh yeah the French are using - yeah definitely I need to be are using - yeah definitely I need to be are using - yeah definitely I need to be better about default nodes the template use this pattern a lot which obviously is good enough but it's not great I actually use default take on a what default while you or whatever I actually use that on a problem earlier today but I didn't do it with this one so I guess it's still I still have a lot to learn but or you know keep learning so that I kind of you know until it becomes innate maybe I'll just say screw it and you see what wasn't hmm but on interviews but yeah I think yeah I totally agree right like I know how to use it I just sometimes it's just like it takes a you know in a practice to be like out this is where you use this tool and just for me it's like what once someone mentioned it my god yeah I should have used this but like it's not you know inlaid in my head to use it yet I think that's my thing okay cool but yeah this is I mean there's people in the chat yeah I feel the chat has mentioned this is a form that like a lot of companies but gifts so definitely practice it even if it's considered a heart here like it will come up you will be asked about optimizations in many different ways you'll be asked about worse case and you ever asked about a lot of things so make sure you practice this and make sure you at least get the fundamentals of the coding point and then you can think about how to expand it I've you're probably know I know they do but uh you need to can you stop the backtrack I didn't even do that kind of maybe not directly not explicitly I did it kind of to try now they tell you they've been priming to try on this okay yeah okay cuz yeah there may be that this is a problem where want some there interviewer ask you there will be follow-ups on a lot of different ways follow-ups on a lot of different ways follow-ups on a lot of different ways and I always wish they could mention them maybe in the discussion boy but yeah so definitely practice it I definitely recommend it because this will come Oh | Word Search II | word-search-ii | Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
**Example 1:**
**Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\]
**Output:** \[ "eat ", "oath "\]
**Example 2:**
**Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\]
**Output:** \[\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 12`
* `board[i][j]` is a lowercase English letter.
* `1 <= words.length <= 3 * 104`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are unique. | You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first. | Array,String,Backtracking,Trie,Matrix | Hard | 79,1022,1433 |
217 | leak code question 217 contains duplicate so given an integer array nums return true if any value appears at least twice in the array and return false if every element is distinct very simple straightforward question what we need to do is we need to just decide whether there is a duplicate in the array and so one way of solving this is to use a set data structure and what the set data structure does is when you initialize it with say this nums array it's only going to pass in unique values so it's going to look something like this one two and three and then we can just compare a property of set which is size so set.size of set which is size so set.size of set which is size so set.size we can compare where it doesn't equal nums dot length so if dot size is different to nonstop length three four then we can return this so this is going to return true here with respect to time and space complexity time is going to be o of n where n is the values of nums and then space is also going to be o of n because we need to store the values within this set and in worst case this could be four and then we'd have to store it in the set as well so let's initialize the set and pass in the nums and then return set dot size to grab the property for set does not equal nonstop length and then try this out true it's been accepted let's submit it | Contains Duplicate | contains-duplicate | Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** true
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Example 3:**
**Input:** nums = \[1,1,1,3,3,4,3,2,4,2\]
**Output:** true
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109` | null | Array,Hash Table,Sorting | Easy | 219,220 |
536 | hey what's up guys john here again so this time let's take a look at this problem here bit cold 536 construct binary tree from string right so you're given like a string with like integers and negative sign and the left and right parentheses and the left and the right parentheses represents the subtree of this of the current node here basically if you have four here so the first substring as parenthesis is the in steer the cell the left subtree two three and one and the right one that the second pair of this of the parentheses is the right subtree so it ask you to return them to basically the tree node so with this kind of problem you know it's kind of obvious we need to use recursions basically every time when we see a four here right we see the a four here we try to find the left what's the strings for the lab to subtree and what's the stream for the right subtree right and for example here we have a four here so we find okay so when we find the first flap find the first left parenthesis right and everything before that basically what we have you will happen will have a helper function here and here we're gonna have the currents out substring here so first we with the current a substring here we first find the left parenthesis here so if there is a lot of parenthesis then it's we know okay so there is a left and the right subtree if there's no there if there's no left predators at all we see we know okay so there's no left and subtree left or right subtree for the current stream we can simply return the routes known with the current value right so if there is a left sub parenthesis so what do we start from constantly so first anything before the Select paren it is will be the numbers here let's say the four three two right this is gonna be the index then gonna be our starting index and then we just loop through everything loop everything after this index here and we'll try to find out the matching right parenthesis for this one how right basically starting from here we increase every time when we see a left parenthesis we increase by one and every time we see a right parenthesis we decrease the counter by one when we see when the counter becomes to zero and then we know we found this like the matching right parenthesis right and then we just pass every the substring between those two matching parenthesis into a recursion function right and we use that one to set the left sub-tree of the current route the left sub-tree of the current route the left sub-tree of the current route right and then everything after this one here will be the right subtree if there is anything right maybe the left and right so for the four right sub-tree we don't need we don't right sub-tree we don't need we don't right sub-tree we don't need to care about the matching index here the matching planet is because we know the last one of the south of the stream it's that it's gonna be guaranteeing it will be the right parenthesis so basically we just start from here to here right we don't care how many whatever inside in between we just want to we just need to know what's we just want to pass whatever between those two print between the current between the here and the last basically the last index of this constraint and we just use that as the right a right sub-tree okay so with that being said sub-tree okay so with that being said sub-tree okay so with that being said let's try to code this problem here so first mmm helper right I'm going to define a card string here alright so first if not corn string right if there's nothing here we return a non value all right and then like I said a left tree start right and left tree start equals to the current as dot find I trying we're trying to find the first left parenthesis right so here we can do a simple check right so if the left if it's not does not exist it which means even this one is equal to minus one right then we know okay so this current string doesn't have any sub trees right we can just simply return tree note int right in corn string right you can simply redo the return that else also we need to find like left parenthesis counter count equals to zero okay let me do a while loop right while we can set a counter here let's do a counter here for I in range right so basically we start from this there's a left parenthesis right and then you start the N will be the length of that here so I'm gonna quit the end for the current ass right so basically we're trying to find the ending point of the left sub-tree right so if C goes to the left sub-tree right so if C goes to the left sub-tree right so if C goes to the current as high right if C equals to the left parenthesis with a left parenthesis count plus 1 right as if C equals to the right parenthesis right into a left parenthesis count minus 1 right and then retrial if left is equal to 0 right then we know we find a matching point right at the matching closing parenthesis so start went to a hand here okay I'm gonna find a hand here with 0 so and then we know the left it's the current I right and then we simply break the current loop because we know we already finished we found it so we don't have to continue then the root right then the root equals to 3 note we can create the root at the beginning here so here basic the same thing here right int since we find our left paren details so we're gonna use everything start from until that in there that start to be the value of our root basically the current has to the start right so basically everything before this lab premises will be our value for the corner root right and then let's assign this root start left right equals to the hopper right we're gonna do a helper here and we're gonna do a substring basically right of the current ass from where from we're gonna remove the add the starting and ending parentheses right so that we have the pure string for the substrate for the left sub-tree that's going to be the left sub-tree that's going to be the left sub-tree that's going to be seen since no this year since this love the index of the lab subtree started HDL is the parentheses and we want to move this one forward by one right and the endpoint will be the left sub-tree and endpoint will be the left sub-tree and endpoint will be the left sub-tree and this is fine because the this the start is inclusive and end is exclusive right so we can use this and how about right like I said the right it's just the endpoint right so remember the endpoint is this like for example is this like a closing parenthesis and we want to move it to we're gonna move forward by two so that we can add this six here right because we want to keep this the current ending and let me write this down here maybe the font is too small to three one five right so for example you assuming we right here right and then in order to find the right sub the right the strain for the right subtree we need to move this I current ending point forward by two so that it can skip the current closing parenthesis and the next open parenthesis right so that's why we need to point it this one to here that's why the starting point of this right subtree is going to be done and plus two right and how about the end it's going to be n minus 1 right like I said we're gonna skip the last parenthesis here right a closing parenthesis that's why we do n minus 1 here in the end we simply return the other hopper right off ass oh sorry I forgot so here we're gonna return the root all right so this roots just should just issues just work and let's see current our currency is our current ass I'm sorry what am I doing here could be the substrate here and okay so alright so this one accepted let's try to submit it alright cool so past alright let's do a little quick recap here so basically we do a recursive call for each string we try to find the starting point of the left sub-tree and the end point of the left sub-tree and the end point of the left sub-tree and the end point of the lab subtree and then we passed whatever string it contains in between to a recursive call same thing for the right subtree in the end we just return the root right all right cool guys I think that's it for this first problem thank you so much for watching the video and I hope you guys liked it and yeah I'll be seeing you guys soon bye | Construct Binary Tree from String | construct-binary-tree-from-string | You need to construct a binary tree from a string consisting of parenthesis and integers.
The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.
You always start to construct the **left** child node of the parent first if it exists.
**Example 1:**
**Input:** s = "4(2(3)(1))(6(5)) "
**Output:** \[4,2,6,3,1,5\]
**Example 2:**
**Input:** s = "4(2(3)(1))(6(5)(7)) "
**Output:** \[4,2,6,3,1,5,7\]
**Example 3:**
**Input:** s = "-4(2(3)(1))(6(5)(7)) "
**Output:** \[-4,2,6,3,1,5,7\]
**Constraints:**
* `0 <= s.length <= 3 * 104`
* `s` consists of digits, `'('`, `')'`, and `'-'` only. | null | String,Tree,Depth-First Search,Binary Tree | Medium | 606 |
62 | hello everyone let's look at unique path the problem statement is there's a robot located at the top left corner of the m multiplier n grid the robot can only move either down or right at any point in time the robot is trying to reach the bottom right corner of the grade the question is how many possible unique paths we can find let us look at example one the input m is three and equals seven so that's three rows seven columns the output is twenty eight this is a typical dynamic programming question the problem is actually we are at index zero 0 that's top left and we want to move to index m minus 1 and -1 index m minus 1 and -1 index m minus 1 and -1 that's bottom right let's have a look how we can solve it in the beginning the robot is at zero what if we want to go to zero one that's here how many paths we can have i think is one the robot only needs to move right how about zero two that's this place i think it's also one how about the rest of this row it's all one let's look at vertically for this position 0 1 how many paths it's also 1. however this 2 0 is also 1 it just keeps going down so we can say for this row and this column there's only one path how about in the middle that's one i guess is two the robot can go right go down and go down go right so to go to this position it has two paths how about go to this position that's one two to get to one two you either add one or zero two to get to one you have two paths and then you can go to one two to get to zero two you get one pass and then you can go to one two so as a result go to one two you have three parts that's adding 2 and 1 that's adding this value and this value so for the rest of all the position we can do the same thing and then in the end all the points will have a value that's the value is adding the its left value and its top value in the end we can get finished let's look at the implementation we will need a two dimensional array its size is m multiplier n its value will be all possible unique path we can get there and for the first row and first column the path number will be one because it's two dimensional array so we need to have array inside array let's give all initial value to be one by doing this we have our initial mammal array all the value will be one and then we can have our for loop we have these two layers of loop and all the start index is one this is because the first row and the first column have already have initial value and then we can get the individual value by adding its left and its top and in the end we need to return n minus one and then n minus one let's submit it looks good to solve this problem we just loop through the input array and we generate the next value based on its previous value that's adding its top and its left if i did not make this clear feel free to go back and look at the explanation for this example again let's look at the complexity for space it's obviously it's of m multiplied n that's the size of our mammal for time it's also m minus n this is because we have this loop for the row and loop for column thank you for watching if you have any question please leave a comment below | Unique Paths | unique-paths | There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100` | null | Math,Dynamic Programming,Combinatorics | Medium | 63,64,174,2192 |
1,255 | hey what's up guys this is sean here so today uh let's take a look at this 1255 maximum score words formed by letters okay it's a hard problem but i think it's to me it's more like uh between hard between medium hard but i mean regardless let's take a look at this problem okay given a list of words okay so you're given like a list of words and then a list of single letters might be repeating okay and the second parameters you're given is like the list of letters here okay um let me increase the font a little bit cool so and okay so and now the second parameters is a list of letters you know it could be duplicate for example this one we have two a's one c three ds one g and two o's okay and then the third one is the third parameters is just like a score basically i know a score of every character so you have a score of uh with the length of 26 right for example this one right it's a 26 length uh of list representing the score for each of the letter starting from a b c d and until the last one z okay and then and they'd ask you to return the maximum score of any valid set of words formed by using the given letters the words i cannot be used two or more times which means each of the words can only be used once and it asks you to return the maximum score that basically any combinations of these words okay so it has to be the whole word otherwise it doesn't make sense right and okay and to be able to form those words here you have to you have you need you have to use uh the letters uh in this letters list here right and each of the letters can only be used once so which means if you have used both of the two ways if you want to have another if you want to use another a to form the other words you can't okay cool so and it asks you to return the maximum score to have any valid sets of words okay for example this one the first one is we have one a sorry so the score for a is one for c is nine so um so we have like uh that is a score of 11 and a good we score of basically that plus good give us like total score of 20 23 which is the highest score here so okay so now it's quite clear that this problem is like a combination problem right basically you do we just need to choose any of the combinations right between all those words here and for the for calculating the combinations we usually use the backtracking right you know if you guys you remember like you're given like a list of a different of different uh numbers like one two three four five okay basically they in they ask you to calculate all the combinations of the uh of those words right basically you have one two you have one three it's a different as a permutation right so it's a combination right it's not a permutation because permutation means that you have to use all five words right all five numbers in this case but the combination is that you can choose from any number of those five numbers in this case it's like any number of words okay so to calculate the count the combinations we usually use the backtracking basically for the backtrackings the first prime there is always a starting point well backtracking okay backtracking and the first element is always the start it's a start index basically it marks uh our starting point of our of the index in this words here and the second one is in our case i think it's current something like a current score right okay yeah basically that's the uh the backtracking and then other than that so after the backtracking it's just like how can we calculate the score here right yep i think that's the main idea here right which um yeah let me try to start coding and maybe i'll try to explain a little bit more here okay cool so like i said you know first backtracking okay backtracking backtrack right and then like i said the first one is start index and um second one is the uh oh sorry so for the second prime second parameters in this case i we don't need the uh we don't need the score instead we need uh what we need is the uh for each of the backtracking method we need like updated versions of this ladder here okay basically you know at each of the back tracking method you know we need to know how many letters left that we can use right basically we need to get an updated version of the letters but you know if the letters here you know if the letters is small i think we can use like uh a bit mask to do that but if you if we scroll down here see the letters length is uh it's 100 which means we cannot use the bitmask so basically we have to use like a dictionary or hash table right and to store that basically you know here i'm have like a letter counter okay here so and yeah so that's that and every time right we just uh update we just try to get a new word and then we are trying to see okay if we can uh if we can form that word with our with this letter congress if we can't then we know okay that's a valid a word and we can just uh add that right and then we can just keep going cool so then to be to start with we have to do a counter write the of the letters right so that's uh that's like a python counter method basically this will return like a hash table with the key of each of the letters and the value of the count of the appearances of that letter okay cool and so and here in the uh in the end we simply call it backtracking okay and at the beginning it's zero index and the lighter counter is discounted right so that's that cool so for backtracking right so for backtracking and we have an answer equals to zero and since we're getting the maximum numbers right i mean we can simply uh re return it in the end so that we don't have to have like a or you know what or you can also do this you have a answer here at the very top here and here uh besides the list letter counters here you can also pass in like current score here right so that i mean later in the end here when we reach the uh the base case we can simply use this current score to update this answer that's one way of doing it okay and another way is that we can simply uh let this re recursion to help us to calculate that and in the end we simply return it okay and the way i'm doing it is that you know so i'm going to remove this part here okay so basically for i in range start to oh to n okay so we also need to define like the length of the words here so that we can loop it okay so that's the end here right so and basically now we're looping through the words from the current from the start index to the end okay and the word is words dot i right so um uh i'm going to going also to define like word score here equals to zero okay basically what we're trying to do here we have a for c in word right if c in the letter counter right and the letter counter uh c e greater than zero and then we know okay fine we can so this ladder we find it and then we just decrease it by one right and then of course we have a word score plus right plus the uh the what the score right so the score of what we need the index but we have a letter so we just need to convert this letter into the index uh based on letter a right so the way i'm doing it is we do an ordinal c minor ordinal of a okay basically this will give me the index based on a here for a it's zero for b is one that's how we get the current score for this um ladder here okay but there's an issue here you know because you know and or you know because you know since we're doing a backtracking right so we need to after we are we're doing this backtracking call we have to uh reverse i mean change this revert this letter counter to its original value so that the next four will have the same starting point right but since we have this kind of like since this is a dictionary and depending on the words here we have uh it could be we only find part of the letters in this word okay and later on it's going to be a little bit trivial not that trivia it's going to be a little bit uh not annoying to revert this thing back based on the current word so i mean to simplify these operations you know the simplest way is at least for me is i'm going i'm just using a temp counters from the original counters i do a deep copy you know that deep copy of the letter okay and here i'm only using this time counter right to help me uh check that and later and meanwhile i'm also like uh updating the temp counter so that every time we'll always have a fresh start for each of this i the for loop here okay so and okay and basically we have if here so if means that okay so we find it but else what happens for the outs else means that i mean this letter cannot be satisfied right so we need to break it basically so it means that this we cannot choose this word okay and to do that i'm also using like uh i'm also using like of variables here to seek to signal if we can actually use this word or not i'm i mean i'm pretty sure there are some other ways you can do this logic but at least for me this is my first approach i'm just using a bunch of variables that help me uh finish my logic okay basically that's what i'm that's what i did here right so valid equals to false okay so basically before breaking the for loop here i said it's invalid the flag to false so and here basically after this file this photo period if it's valid then we do a dfs call right so answer equals the max of answer dot backtracking okay here remember we do a i plus one not the start pipe by not the start plus one okay so this is a at least i uh i felt in this kind of like a pit several times i was using the start plus one and i was like what happened i've spent some time trying to debug it but yeah remember always do a i plus one because we're we are we're processing the current ice word right so that's that and then here we just uh simply pass this uh temp counter okay because this is the time counter is updated one that's the ones uh this backtracking method we'll be using later on okay and of course we do a plus word score here okay cool so and here in the end we simply return this answer you know yeah so that's that uh now the uh the base case right so when do we stop basically the if start equals to n right and then we simply return we return zero in this case because we are getting the maximum right from this recursive call so by the time we reach the last con last words or at this moment there's no more words left so that we simply return zero cool so yeah as you guys can see here basically for each of the words here right we're getting the maximum out of all the possible scenarios here right and then of course we have to uh plus our current word score right and then we yeah that's how we calculate the maximum score uh with all the combinations i'm going to try to run the code here so cool so this one passed submit yep so it's a success you know so i think like i said you know there's another way of doing it for example you know like i said since if we have answer here right answer equal to zero i mean if like i said we can there another way of doing this we can also pass in the current score here right so if we have a current score here right and then so here i mean if we do that right i mean we don't need to do this max here in here so we can simply do this so if the start uh equal equals to n here we simply do the answer equals down to the max of answer dot current score right so and it means that we don't need to return here right because we're handling everything handling all the calculations to the end when we reach the uh the end which when we reach the base case okay and then here uh basically we there's no need to do a max here because we are doing the max in the end here so we hit we're just doing this backtracking here backtracking call here and of course we have a we need to do a current score plus the word score right and here we're not returning here we basically we just call this backtracking method and we ask that we ask the backtracking to calculate that and in the end we simply return the answer yeah so we have a counter and at the beginning it's zero i'm assuming this should also work let's see if i'm right or not oh yeah of course so none local right answer okay run the code oh return so oh yeah there's so then there's no point of defining our answer here so and let's see let's run the code one more time yep so accept it submit um yeah it seems like the second approach doesn't work somehow um i see i think the reason being is this you know we shouldn't only update the answers while we're at the end because you know we might not be a we might not always be able to reach to the end because here you know if some for some reason the word cannot be this current word cannot be formed some somewhere in the middle we simply just stop here because we only forward we only uh proceed when the uh when the current word can be satisfied right so which means that uh yeah so which means we every time right every time we should do this yeah and we just need to do this right so let me see if this works yeah so now it works okay basically you know we are so this base case is only for us to uh to stop this for loop right and then but when uh when we are updating the answer here so like before how we update the answer we for each of the loop here we are we always compare it right so same thing for this second approach here basically you know because like i said i mean it our loop our backtracking could stop at any word right basically could we could have stopped at this word here because there's no uh no other words that can allow us to form uh this good here so that's why we have to some every time right we have a new score here we have to compare with the current answer cool yeah i think that's it and okay let's see what else we have here um maybe at the time complexity right so for the time complexity right let's assuming we have n words and so the total combinations of that i think is 2 to the power of n now the combination is this so the combination is the uh times n minus 1 divided by 2. that's the combination right the total combinations of the uh of this length of n words am i right okay let's see now i think the uh the formula to calculate the combination is this it's like it's n factorials divided by uh by k factorials of n minus k but in this case k could be from 1 to n right so yeah so i think in the end it's still like two to the power of n of the total combinations yeah and for each of the combinations right reserve for each of the backtrack here we have like we have a loop for the c here right basically i think for the let's see we have m here m is the length is the average length of the ladders here okay so yeah basically the time complexity for this one is 2 to the power of n times m yeah that's the time complexity and the space complexity i think space is cons it's constant i mean regard i mean besides the uh the recursive call right because here the counter here the size of the counter is like 20 so at most 26. okay yeah i think that's should be correct okay cool guys i think that's it for this problem thank you so much for watching this video guys stay tuned uh i'll be seeing you guys soon bye | Maximum Score Words Formed by Letters | reverse-subarray-to-maximize-array-value | Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character.
Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times).
It is not necessary to use all characters in `letters` and each letter can only be used once. Score of letters `'a'`, `'b'`, `'c'`, ... ,`'z'` is given by `score[0]`, `score[1]`, ... , `score[25]` respectively.
**Example 1:**
**Input:** words = \[ "dog ", "cat ", "dad ", "good "\], letters = \[ "a ", "a ", "c ", "d ", "d ", "d ", "g ", "o ", "o "\], score = \[1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0\]
**Output:** 23
**Explanation:**
Score a=1, c=9, d=5, g=3, o=2
Given letters, we can form the words "dad " (5+1+5) and "good " (3+2+2+5) with a score of 23.
Words "dad " and "dog " only get a score of 21.
**Example 2:**
**Input:** words = \[ "xxxz ", "ax ", "bx ", "cx "\], letters = \[ "z ", "a ", "b ", "c ", "x ", "x ", "x "\], score = \[4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10\]
**Output:** 27
**Explanation:**
Score a=4, b=4, c=4, x=5, z=10
Given letters, we can form the words "ax " (4+5), "bx " (4+5) and "cx " (4+5) with a score of 27.
Word "xxxz " only get a score of 25.
**Example 3:**
**Input:** words = \[ "leetcode "\], letters = \[ "l ", "e ", "t ", "c ", "o ", "d "\], score = \[0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0\]
**Output:** 0
**Explanation:**
Letter "e " can only be used once.
**Constraints:**
* `1 <= words.length <= 14`
* `1 <= words[i].length <= 15`
* `1 <= letters.length <= 100`
* `letters[i].length == 1`
* `score.length == 26`
* `0 <= score[i] <= 10`
* `words[i]`, `letters[i]` contains only lower case English letters. | What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[R + 1] - a[L], a[L] - a[R + 1]) - value(L) - value(R + 1)) over all L < R where value(i) = abs(a[i] - a[i-1]) This can be divided into 4 cases. | Array,Math,Greedy | Hard | null |
1,509 | Hello hello everyone welcome to my channel it's all the list problem minimum difference between largest and smallest value in three modes in this problem for women are not quite choose one element of changes festival in one to three minimum difference between the smallest value for example 153 246 To two to the number 323 324 subscribe to the Difference 0 that inch example is also 150 021 for achieving minimum value that tweet between center 521 and distant to one and support the native with minimum do that in fact third example behave 606 Soviet is loop 400 will change for the smallest value in directions four 12th fluid from this dish good so 10 not alone in this world will find the difference between a man and the sea but its real power to changes regular seven change what we can Do I love you can change the largest value and the smallest value time person to minimum will be doing what will you consider a this is the no one can change the system but something is the largest subscribe now to change element will that China selven 2nd of the value from s12 alto 800 the world value after receiving this movie will have to the - S1 and 1 inches one to movie will have to the - S1 and 1 inches one to movie will have to the - S1 and 1 inches one to subscribe my channel subscribe to subscribe minus one two to subscribe my channel subscribe - two to subscribe my channel subscribe - two to subscribe my channel subscribe - Shyamlal Jasvir Person Change of 1000 181 And Listen This Will Be Shift Chinese Larges Minus One Third Shyam Channel Subscribe Our In Which Is The Smallest Way Strong Minimum Nine Three Wheeler Can You Will Change The Colors Year-2013 Maximum Change The Colors Year-2013 Maximum Change The Colors Year-2013 Maximum Value 121 Adhoora Mohalla 80 Prohibition Subscribe New Saudi More Focus Send Me To Take Minimum In This Force How Will Implement This For Implementation Of Various Elements Of First What Will You Get Subscribe For 4 Minutes Element Which Any Element To The Difference Between The Smallest Mez Thee And Mez is not the point i20 to take care all the case me loot for demonstration and will get the results which will be the mean of the difference between the first president of the last value - free leg free last value - free leg free last value - free leg free subscribe my channel a plus b i is for loop in over - the a plus b i is for loop in over - the a plus b i is for loop in over - the smallest where is the smallest will wait for you in first k beerwah 10 to 12 and subscribe result is so let's compile tower ko dense where passing a is not subscribe skin this that and gift as well now Half Vidisha 209 Jis Maximum Test Cases Vidhyavya Passing Note Seervi Radhe Ki Saathi As Accepted For The Time Complexity Of This Code The Time Complexity Of Words Starting And What Is The Biggest Decision Constant Vikas Vihar Running For Foreign Relations Which Can Be Contacted Called S Bird Is Chatting will take and one-time se internal Chatting will take and one-time se internal Chatting will take and one-time se internal years old user mixed and the time complexity of dissolution iss bhi cheez ko off in log in a pan safe thank you feel like a solution please like video any fear when question skin in comment section subscribe My Channel and Hit The Bell Icon for Latest Getting Up Early Notification of New Video Thanks for Watching | Minimum Difference Between Largest and Smallest Value in Three Moves | replace-employee-id-with-the-unique-identifier | You are given an integer array `nums`.
In one move, you can choose one element of `nums` and change it to **any value**.
Return _the minimum difference between the largest and smallest value of `nums` **after performing at most three moves**_.
**Example 1:**
**Input:** nums = \[5,3,2,4\]
**Output:** 0
**Explanation:** We can make at most 3 moves.
In the first move, change 2 to 3. nums becomes \[5,3,3,4\].
In the second move, change 4 to 3. nums becomes \[5,3,3,3\].
In the third move, change 5 to 3. nums becomes \[3,3,3,3\].
After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
**Example 2:**
**Input:** nums = \[1,5,0,10,14\]
**Output:** 1
**Explanation:** We can make at most 3 moves.
In the first move, change 5 to 0. nums becomes \[1,0,0,10,14\].
In the second move, change 10 to 0. nums becomes \[1,0,0,0,14\].
In the third move, change 14 to 1. nums becomes \[1,0,0,0,1\].
After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 0.
It can be shown that there is no way to make the difference 0 in 3 moves.
**Example 3:**
**Input:** nums = \[3,100,20\]
**Output:** 0
**Explanation:** We can make at most 3 moves.
In the first move, change 100 to 7. nums becomes \[4,7,20\].
In the second move, change 20 to 7. nums becomes \[4,7,7\].
In the third move, change 4 to 3. nums becomes \[7,7,7\].
After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109` | null | Database | Easy | null |
485 | Jhaal Hello hi guys welcome back to the video you guys watching in this video this try vashisht then you one more question named maximum which u turn punch ok we are a winery hey yaar rahega meaning binary hey kya in which zero and man se We need to stop the maximum number of positive returns which are continuously coming. Okay, which coating would I apply then? How many consecutive one are coming in it? Three, two, I have to form a team. How many consecutive one are coming in this? Friends, my return is far away. To do this, the approach will be quite simple, I will take two Barry Bhaile, the answer is the maximum, okay, we will give this example, then we will see this example, I have come here, okay, initially I will move them from zero to the left, one, first of all I came to which strangeness, then I closed it, then it came to one, so I added 1 to it, then I came to zero, so I told it to be zero, then I came to one, then again I came to one, so I changed it to two, then when it was made again, I started. Well done for three, I am common in this maximum variable, what will I do, I will either take this maximum of profit, this maximum of this, then what is the maximum of these two now, out of 340, Preeto, I will add it to this, please return, what will I do? Answer It is coming free but look at this so what should I return so let's keep it in the fold for now okay now let's see this example in this also took the shelter of one Verrier Alvin is giving maximum for this too okay first of all here Hey, you have become from zero to 1, if only you did Rohit, then the sum is zero, then again the mind became a stranger, then came to the forest again, then you are okay, what did I do, what was I doing now, along with this, I was also updating the maximum. If I was updating it then maximum me is mine then it must have gone maximum mine you are of this is this and also updated maximum also ok one then I updated them now maximum and among these what is maximum answer and maximum message what is maximum If you feel like it, then I am also updating the maximum along with it. Okay, this point was done in my time, but after seeing this point, you should note that I am updating the 7 Sapna Maximum. Okay, whenever I If I am getting every one then I am ending it by one. If I am getting zero then I am making it 120 and also updating the maximum. This is my approach app. My matches have come to two. Now if I set zero then This hero went to another hero, this one got boiled, so what happened to this zero, Monu Bhaiya, what do I have to return, maximum, I will return here, maximum, good time complexity that Bigg Boss will become N, it will go because of the space complexity. Soak of one is okay, it was a very simple question and it became ours okay let's do court what should I do or 12 external villains or the answer is okay and to the maximum then I will run the look and then hydrate the eye lashes in Thumbs Don't Size After that, what should I do, Ka Yag Ghar Mere Ko Aap Naam Saunf Aap, if I get area element one, then I will make the answer plus, otherwise I will make the answer zero, you and also what will I do, maximum. Also keep updating or ok and what will I return in it maximum variable ok once more Roshanlal ok first of all I went to you a little if don-2 tu like I went to you a little if don-2 tu like I went to you a little if don-2 tu like this is 101 ok Close is zero so first of all I took the answer so first of all what did I do first of all I took the answer is you and one maximum is very different you are ok I lost these two zero six inches 1 so now he has done the maximum of these two What is the maximum among these? Okay, this one has become the first. These two have reached the maximum like this, so I updated it from 1 to 1. Then my one came to zero, then I reduced it to zero. What is the maximum among these two? Just made. If it is there then the maximum level will remain the same. Is this one in it? So it is indicated that what is made of these two in it will remain so. Now it came to them through me, so this came to them from mine and I asked what is the maximum of these two, you are. I have signed it in maximum, I have returned it in maximum, Meghvahan, now the approach is clear to you, 12 examples, try something direct, like yours and if you cool it down, then it is submitted and you have romanced me for a long time, but finally. I have been accepted, okay so after the question, I have understood and we will meet in our next video, till then keep studying, this is all the various. | Max Consecutive Ones | max-consecutive-ones | Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_.
**Example 1:**
**Input:** nums = \[1,1,0,1,1,1\]
**Output:** 3
**Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
**Example 2:**
**Input:** nums = \[1,0,1,1,0,1\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.
How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size. | Array | Easy | 487,1046,1542,1999 |
1,007 | hello today we will be doing today's good question that is minimum domino uh rotations for equal row and the question statement uh states that in a row of dominance tops of i and bottoms of i represent the top and bottom halves of the ith domino we may rotate the ith domino so that the tops of i and bottoms of i swaps the values we just need to return the minimum number of rotations so that all the values and tops are same or all the values in the bottoms are same if it cannot be done we just need to return minus one so let's understand this question more clearly so what this says is so we have been given some array values which has been given right here okay so uh viewing this diagram right here you can see that all the values that are here and all the values that are here are not equal obviously so we just need to make sure that any one row is equal so any one row is equal okay that is what we need to do and what i can do here is that we can take a value that is this guy okay from the top and one guy from the bottom and swap these two that means this five will uh come above and this two will come at the bottom so this is what they have done right here in this two okay they just have swapped it so this is uh the only thing that you need to uh consider in this question whenever you get uh two dissimilar guys you just have to swap and see if it can be made uh possible to actually change it and let's get the intuition on how we are going to actually uh come up with a solution for this so let's see the array is given here is 2 1 2 4 2 and two six two three two so what do we know first of all we uh know that in a dice the values can range from one to six only right it cannot exceed nor can it uh decrease uh from this so the values always range from one to six and what do we know else so as we know from here these two are the values that are given so according to our greedy nature what can we think so we have been given how many places let me just see there are six places so i'll just draw six blanks right here three one two three four five and six okay we have six blanks right here and we have six blanks at the bottom as well so what we need to do is we need to put some values in all these blanks and make sure these are equal okay in either the first row or in the second row so what we are going to do is first we are going to count the number of values which are uh present there okay so what do i know for two what is the frequency of two in the uh first array and the second array so let's just count it the frequency of two is one two three four five six and seven so the frequency of two we can see right here is seven okay what is the frequency of one that is just one which we will not be needing but still i'm just writing it down what is the frequency of four it is again one and five is again one i guess and three is also one right here okay so these values are pretty much useless to uh us we can say that these are not uh useful why i'll just get into that so see at max what can i have i can have some value okay and i just need to fill everything and how many places are there are only six places as you can see and do you see something here you see that okay i have got two whose frequency is seven that means i can do something and just fill everything with 2 right we can obviously do this thing but how can we do it so let's just draw this again there are six values and mind you it doesn't necessarily mean that if i have a frequency greater than that i will always be able to fill it and what do i mean by that statement is if you just go down in this statement you will see that the frequency of three is what one two three four five right the frequency of three here is five and what is the size of the array if you just carefully observe it is five right so it is the size is five so according to what i told previously it should fill right but it cannot why i'll just tell you see in the first guy we can write 3 for sure here also i can write 3 here i can write 5 here i can write 6 again we have 1 and 3 so i will say okay i have 1 and 3 i can just swap this and get one right fine by me not a problem now i go to the next guy again this is three so for these guys i do not have any problem i can make a swap okay and do it but there is a problem that is if you just carefully see here we do not have any three right we cannot make any swaps even if we make a swap we cannot have a three right here uh so that is the problem in this case and how we are going to deal with it that is what i am going to tell you right now so how to deal with this problem is so for now we know that the frequency of the highest guy is 3 right so 3 is having the highest frequency of 5 so what we can do is we will just iterate here iterate on the first guy and see if the first element and the first element of top and bottom both the array are same is it same so at the first instance i see yes it is same so i can i do not need to do any swap right but if i find at any point that my first instance element that is the tops element that is 5 and the bottoms element of any index which is similar is not matching with the frequency of the maximum guy that means i need to fill every guy with only three okay but here in both the places we do not get any three here so we'll just simply return minus one if we encounter this case otherwise we'll just simply increment our uh count variable which we will be taking and which we will be returning uh and that will be my answer only so now let's understand the code part then you will be getting the visualization and the code will be much more clearer do you sorry so here's the code right here so what i have done here is i've just counted the frequency okay of every element this is this part is very simple and what is this do doing this is just simply uh checking which guy is the maximum uh maximum guy in my array okay so i in this part what am i doing so i have how many elements i will only have one two three four five and six right i will only have these many elements only always the error size can be uh a lot 10 to the power four fine but the combinations of number can only range from one to six only that is i have taken a seven size array only which will give me the answer after that i am finding which guy has the maximum occurrence okay after that what am i doing so i'm just taking the guy whoever guy is the maximum frequency that means let's just take this example right here so in this example which element has the maximum frequency so as you can see in this uh array we have two whose frequency is what seven right so this is what i'm doing in this step okay i hope this is uh clear up till now so now let's proceed to these part which is the actual answer part which will be returning so what did i say i will just compare both of those array right so let me just write this that what this part of the code is doing okay so i have my array something like 2 1 2 4 2 and the bottom array is something like 5 2 6 2 3 and 2 let's just take uh this has 4 okay for now let's just take this as 4 so what do i say i will go at my uh top element and by the way what did i say this part was doing this part was just finding the maximum guys frequency and what is that this is 2 right so i will see if is 4 equals 2 equals to 5 obviously not both are not equal and also both are not equals to the maximum guy which is 2 is 4 equals to 2 or is 5 equals to 2 both are not equal to 2 so what will i do i'll just simply return a minus 1 that means it can never be formed but there is also a clause that if both of them are equal that means both of them are equals to the maximum guy what will i do i'll just simply continue because i do not need any uh moves to uh make those elements equal right because both of them are equal in both of the arrays but let's see if i have an array something like 1 2 3 and this is something like 2 1 or 2 so i knew that i have to write okay i need to make two equal so i am not sure in which array do i need to make it equal okay so what will i do i'll just simply take two variables i have taken up and down as the variable names what will i do i'll check if my upper array has the value 2 i'll simply increment the value of up by 1 or else if my lower value that is this guy right here if this value is not equals to my uh two so i'll just increment the down pointer by one okay so now i know how many places do i have to fill to make them equal so as you can see here only one value is different right which is not equal to two and here how many values are not equals to two there are two values which is not equal to two so here there are two values which is not equals to two and there are only one value which is not equal to two so which one will i take i'll take the bottom array right i'll take the bottom array and i'll simply say okay make this one to two and i'm done with only one move okay so this is what we are returning right here that is minimum of up and down sorry for that so yeah this is it for this code i'll just run and submit this again and i'll show it to you uh this is a slightly different approach which you will not find i guess in the submission forum there are easier solutions also okay so you can also follow that but this is what i had come up with at the first instance so this is it for this code i've already submitted this code so yeah thank you for watching and if you did understand please like the video and subscribe to my channel thank you | Minimum Domino Rotations For Equal Row | numbers-with-same-consecutive-differences | In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6` | null | Backtracking,Breadth-First Search | Medium | null |
268 | everyone so today we are looking at lead code number 268 it is a question called missing number and so we have an array uh example one here we have an input array of three zero one and we have zero one we're missing two and we have three so our output is two here our num is two uh it's or the length is two so n is gonna equal two so we have zero and one and we're missing two and here the length is nine and so we can count through all of these and we can see that the missing number is eight here the length is one and so we have zero but we don't have one okay so there are three approaches to solving this problem and we have a follow-up here that says could you follow-up here that says could you follow-up here that says could you implement this solution only using constant extra space and a linear runtime complexity so let's take a look at the three different ways we could approach this okay so i have the input here of three zero and one okay and so one way we could approach this is if we want to do it in constant space then we can think of sorting this array that's going to cost us n log n time okay to sort it but we'll do it in place and now we're going to have an array that's going to be sorted so it's going to be 0 1 and 3 and then we can do a linear scan on this array and figure out where the missing number is okay so we'll have constant space but we're going to have n log n time which is not what we want okay so that's one way we could approach this what's a different way we could approach this well we could also use a strategy where we hash okay so let's take a look at what that would look like so if we put all these numbers in a hash so let's say i have a hash here and i'm going to have a key of 3 which will equal true a key of 0 which will equal true and then a key of one which will equal true okay so here we have a hash and now what we can do is we can create an n variable which is just going to be the length of this array okay so it's going to be 3 in this case and now we just iterate over uh over the array or we iterate over these uh this num here so let's say i equals 0 and then i is going to be less than or equal to n okay and then we check is that key in the hash so 0 is going to be there when it goes to 1 is going to be there when it goes to 2 is not in here and so we return 2. right so that's the hashing method of solving this what would the time and space complexity be for that so we're going to have to hash everything that's going to be linear time we're going to have to run we're going to have to scan over it again to find the missing number that's going to be linear time so our time complexity here will be linear but we're going to have to create linear space with this hash all right so we're going to have o of n for space as well okay so those are two ways two brute force ways we could do this we can optimize for space or we can optimize for time and figure out a way to do this now is there a way to do this in linear time in constant space and the answer is yes okay there is a way to do it but it requires knowing a famous algorithm okay let me just go ahead and clear this all out so there is a algorithm that you can use a formula you can use to get the sum of all the numbers okay and use that as a way to figure out that just use the length of the array to figure out what the sum of all the numbers are if they're going from 0 to n okay so i'm going to call this g sum and the formula is n times n plus 1 divided by 2 where n is the length of the array okay so in this case the length is 3 so we're going to have 3 times 4 divided by 2 which is going to equal 6. all right and so now that we have the sum of that just using a constant mathematical operation based off the length of the array what we can then do is use reduce to get the sum of our input array which is going to be four and now you can see that if we subtract g sum from our reduced sum we're going to get the missing number which is two okay and if we use this method what is our time and space complexity well this part here is going to be a constant time operation and getting this part here is going to be a linear time operation and so our worst case here is going to be o of n for time and then what about space well we are creating no new space the only space we're creating is for the 4 here and then our g sum which is going to be constant regardless of the size of the input and so we can have a constant space for this solution okay so it's a very clever way to solve this and very elegant way um but however i think if you don't know that g sum formula uh that you know it would be very hard to figure this out in an interview setting so then you have two different approaches that you could figure out which is the hashing method or the sorting method okay so let's go ahead and code this out so here we're going to have our g sum here which is just going to be numston length times nums dot length minus or plus one okay divided by two i'm just going to put extra parenthesis here just to make it clean okay and then we're gonna have our num sum which is just gonna we're just gonna reduce all the numbers inside of that array okay and then all we have to do is just return our g sum minus our end sum uh let's see here and some reduce acc oh we need nums.reduce okay and so that does it you can see we get great performance using this method to solve this problem all right so that is lead code number 268 missing number i hope you enjoyed it and i will see you all on the next one | Missing Number | missing-number | Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return _the only number in the range that is missing from the array._
**Example 1:**
**Input:** nums = \[3,0,1\]
**Output:** 2
**Explanation:** n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums.
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the missing number in the range since it does not appear in nums.
**Example 3:**
**Input:** nums = \[9,6,4,2,3,5,7,0,1\]
**Output:** 8
**Explanation:** n = 9 since there are 9 numbers, so all numbers are in the range \[0,9\]. 8 is the missing number in the range since it does not appear in nums.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 104`
* `0 <= nums[i] <= n`
* All the numbers of `nums` are **unique**.
**Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity? | null | Array,Hash Table,Math,Bit Manipulation,Sorting | Easy | 41,136,287,770,2107 |
415 | how's it going everybody so today we're gonna go over a string based problem called add strings and this is a problem asked at Facebook Oracle Amazon and Microsoft so the description says given two non-negative integers num1 and num2 two non-negative integers num1 and num2 two non-negative integers num1 and num2 represented as a string return the sum of num1 and num2 and so the biggest note of this problem is that we must not use any built-in big is that we must not use any built-in big is that we must not use any built-in big integer library or convert the inputs to integer directly so to solve this problem we have to use the strings that were given to actually compute the sum and return the result so let's say we start off with two strings 2859 and 293 we need to add these two strings together without converting them directly to integers so we can't use any functions that are inside of the standard library of whatever language we're using we can't use those functions to understand how to compute the sum between two characters let's jump over to the ascii table so if we look at this section right here we can see that we have numbers 0 through 9 and if you look at the leftmost column which is the decimal column starting at the 0 character that is represented as number 48 and then all the way going up to the character 9 that's represented as decimal number 57 so with that in mind we can actually compute the difference between two characters and we can get an actual integer value so let's say we wanted to convert the character 1 to the actual integer value 1 without calling a function on it what we can do is subtract the character 0 from character 1 and that will give us a result of 1 the reason why is because if we look at character 1 that corresponds to the decimal number 49 so 1 is equal to 49 minus the character 0 that's represented as 48 in decimal so 49 minus 48 is equal to 1 so as you can see these statements are the same because the characters have underlying decimal values so that's actually how we're going to solve this problem we can convert every character that we're looking at into an actual integer value so now that we understand how to convert the actual characters to integers we can start on the problem so we're going to need two different pointers one looking at our first string and another looking at our second string so when we normally add up two numbers we move from right to left to sum up those numbers so we're going to do the same for the strings so we're gonna have one pointer starting at the very end of our first string we can call this I and then we're gonna have a second pointer starting at the end of our second string and we can call this J we're also going to have two more variables to solve this problem the first one is our carry when we are normally summing up integers we have carry numbers that we move to the next position when it gets over the value 10 so we have to make sure that we perform the same logic and know when we need to add a carry to the next position or not and then we're also going to have a variable called our result is going to be a string that we eventually return from our function so if we look at our first characters that we're looking at the character nine and the character three and if we subtract it from character zero both of these characters we will get a value of nine and a value of three and with that we can just perform normal addition so 9 plus 3 is 12 and what that means is we will have a carry moving to our next position so in order to determine if we set our carry to a 1 or not is if we have a left over after the value 10 so all we have to do is divide the number that we sum up by 10 which would be 1 so that means that this value is now our new carry so our Terry is set to 1 but we still need to determine which number is the remainder after we determine if we have a carrier or not so if we did 12 mod 10 that's the remainder after dividing by 10 that would be a value 2 so 9 plus 3 we have a 2 and then we have 1 as our carry which moves to the next position so the division determines if we have a carry and then the modulus determines which number is going to be in our result so now we're looking at the character 5 and the character 9 so we need to sum up these numbers so 9 plus 5 but remember we have a carry that we just set from the previous calculation so we also need to add 1 to this result so that would be a total of 15 and like before we're going to perform the division of it so 15 divided by 10 once again it's one hour carry is already 1 so we don't need to do anything and then we're going to perform our modulus 15 mod 10 which is 5 left over so 5 is in this place we're gonna have another carry go to the next position once again we're looking at character eight character two we're gonna do eight plus two plus our carry which is one currently that totals to 1111 divided by ten we have another carry of 111 mod 10 we have a 1 left over so 1 takes the position here so now the last position we're looking at we have our eye pointer looking at character to but our J pointer is no longer looking at anything so this is just an extra edge case we're gonna have to consider when we are writing the solution our strings may not be the same length so in the scenario that our pointer is not looking at a character we can just say that pointer is looking at the number 0 so if we do 2 plus 0 this is representing our J pointer plus our carry is currently set to 1 that would be a total of 3 so we do 3 divided by 10 that would be 0 so now our carry is going to be set to 0 and then we do three mod 10 and that would be three so three takes the final position that we have and then we add that to our result the final step is we can see that our result is actually backwards because we were iterating from right to left and appending from left to right so we need to reverse this string once we are finished looping over both of these strings so then we will get 3152 so we're given two strings num1 and num2 we need to add them together and return a string which will be our result so the first thing we want to do is create two pointers I and J so in I this pointer will start at whatever number 1 dot length minus 1 is it is always going to start at the very end so num 1 dot length minus 1 and likewise for J it's going to start at num2 dot length minus 1 and then we're also going to need an - juror carry because as we're entering - juror carry because as we're entering - juror carry because as we're entering iterating over these strings we need to determine if we have a carry or not so we can say int carry and this can just be initialized to zero and then we also need to eventually return a string so we're going to need to have a variable to keep track of that so we can use a string builder for this and we can call this result and now we want to loop over the strings so we can say while I is greater than negative 1 or J is greater than negative 1 the reason why it's an or is because if they are not the same length we still want to iterate over both of the strings so in the scenario where I is either less than or equal to negative 1 or J is less than or equal to negative 1 we still want to compute the sum for the rest of the digits so now we need to convert the current characters that we're looking at to actual integer values so we can say int digit 1 we need to check if I is actually greater than negative 1 or not because if it is then that's good because we can just convert the character to its own integer value however if it's not that means we have exhausted looking through all of those characters and we can just default it to 0 so if I is greater than negative 1 then we can say num1 char at I minus the character 0 if that's not true then we just default it to 0 and we're gonna do the same thing for digit 2 so if J is greater than negative 1 num2 char at j minus the character 0 if alt it to 0 and now we need to compute the sum so we can say int the sum is d1 plus d2 plus whatever our carry is up to this point and now we need to add in the modulus to our result right so we could say result dot append some mod 10 this will give us the very last number and then finally we need to compute our carry which we know we just need to use division so we can say carry is equal to sum divided by 10 and this will always be a 0 or a 1 and now we just need to move our pointers backwards because after we do these calculations we no longer need to look at these digits so we can decrease I and then decrease J and after that we still have to handle one extra edge case let's say we had two numbers 99 and we were trying to add it to 1 right this would obviously equal 100 however in our current code if we were to have these two numbers as input our carry would end up being a 1 when we come out of this while loop so our result if we had these two strings as input would just be 0 up to this point we also need to handle if we have a carry as we are coming out of this while loop so we can say if our carry is equal to 1 then we need to add it so result dot append 1 and now all we need to do is reverse our result and convert it to a string so we can say return result dot reverse dot to string so let's just make sure this code works and there we go our time complexity is going to be Big O of n where n is the bigger length between num1 and num2 because we will have to loop over all of the characters of both of our strings and then our space complexity is also going to be Big O of n because on line 5 we have to create a stringbuilder that we eventually return from our result so that's it for this video guys thank you for taking the time to watch my video I hope it was helpful for you I'll see you guys in the next one | Add Strings | add-strings | Given two non-negative integers, `num1` and `num2` represented as string, return _the sum of_ `num1` _and_ `num2` _as a string_.
You must solve the problem without using any built-in library for handling large integers (such as `BigInteger`). You must also not convert the inputs to integers directly.
**Example 1:**
**Input:** num1 = "11 ", num2 = "123 "
**Output:** "134 "
**Example 2:**
**Input:** num1 = "456 ", num2 = "77 "
**Output:** "533 "
**Example 3:**
**Input:** num1 = "0 ", num2 = "0 "
**Output:** "0 "
**Constraints:**
* `1 <= num1.length, num2.length <= 104`
* `num1` and `num2` consist of only digits.
* `num1` and `num2` don't have any leading zeros except for the zero itself. | null | Math,String,Simulation | Easy | 2,43,1031 |
324 | today we're gonna be working on lead code question number 324 now wiggle sort part two given an integer array nums reorder it such that nums of 0 is less than nums of 1 which is greater than numbers of 2 which is less than numbers of 3 so it's kind of alternating between less than greater than you may assume that the input array always has a valid answer so this has been given one of the output or this is going to be the output player one and then six and then one and then five one and then four nice and it does say that other solutions are also accepted where one four one five one six is also accepted okay so a naive situation is gonna be just sorted out okay and then uh from the median or the middle point uh one iterator is gonna go to the right one to the left and it's gonna be just putting elements to the right place in order to get that effect of increasing decreasing increasing decrease a better solution in order to achieve the linear time complexity and what we're going to be doing is first we're going to be this we're going to be finding the middle point or the median index by using a method called find gate largest we have solved this problem in the past before where we were looking for this kth largest element inside an array and gth plus one divided by two so we are looking for this index l e and g t h plus one basically we're looking for this middle index in this array nums so we're going to be using that function for that and then once we have the median or the middle element what we're going to be doing is to record the to keep the record of uh total length of the nums after that we also want to know that the left side we're gonna start with the zero and the right and i is gonna be our iterator it's gonna be the also start from zero and the right is going to be equal to n minus one okay now while the i is less than equal to right what we're gonna be doing is again we're gonna check that i'm sorry first of all the median is the element itself it's not the it is not the uh we so because this is going to be returning uh the value of it not the not just the index so because it's the kth largest element okay smallest element inside the sorry k largest element inside that array so in our case it's the same because we are looking for smallest or largest is going to be the same because we're looking for the middle element so that's going to be our median so all we have to look for is like at a particular like the element for a particular index uh if it is of x is greater than that median or not if it is greater all we have to do is to swap it right swap the nums from this uh like swap the left side of it right uh left side of it with uh with this numbers of x and then also increment that index okay we'll define these x's in the left in exactly but that's the gist of it where else if we want to check that the nums of the same like the same thing x is less than that median then in that case again we're gonna swap it but the right side is gonna get decremented so swap the nums of the right uh also that is gonna get decremented every single time and then the nums of whatever we were doing before like in the x okay otherwise we're just gonna increment our i okay and that would be the basically the solution so what is the x so x we want to do here is the we're going to call another function which is basically going to gonna be uh calculate our new index for that so nums of new this is gonna be the function we're gonna be using we're gonna be giving it uh like the particular index we are at and the total number of elements okay so there is this new index i and the n and what left here is again new index so this time we're gonna be sending left and the total number of elements similarly over here we're gonna be sending new index right negative and the total number of elements similarly over here this is going to be exactly the same over which we had over at this place okay so what exactly are we doing in this new index as uh we are returning an int back new index it does take the index i and it does take the total number of elements in that array which is n what it does is like it takes 1 plus 2 multiplied by the index and then it takes the modulus of that so whatever is the current index you multiply it with two and then add it one add one to it and then you take the modulus of that with n or one this is gonna be the new index every single time so we are actually switching between uh left and right uh side so whichever index you are at uh we are actually multiplying it with the index uh we're multiplying with uh with two and adding it one and then we're gonna keep it in inbound that's why we are actually taking the modulus of that the other thing we want to do is to implement that uh find kate largest element so that is the way we do it is we're going to be returning find largest anime it does take an array nums and then and okay the element which we are looking for or the order of element which we are looking for and we use a random function here okay uh then we want to swap it again so uh for that we're gonna what we're gonna be doing is and i is gonna start from the largest index nums.length minus 1 the largest index nums.length minus 1 the largest index nums.length minus 1 and then it's gonna get in decremented until it is greater than equal to zero i negative so what we are doing is to swap the element nums with i like we're changing the eye with the random next and with the i plus one and again we're going to start with the left equals to zero and the right is going to be the largest index num start length -1 -1 -1 and our k is every single time we're gonna decrement that and we're gonna the logic we're gonna be using is gonna i'm gonna keep doing it until the left is less than right and every single time we're gonna be looking for a middle uh index get middle okay we're gonna have nums and the left and the right once we have the left and the right all we have to check is if the left if the middle which we just found out is less than the k which is the index we're going to be looking for we're going to move over left to mid plus one basically moving left forward else um if the m is greater than k that means we are far away so we're gonna set our right make minus one otherwise that means we just found out also we're gonna just break once we come out of this we're gonna return the numbers of k good this is like there are uh there are proofs on this one like how this uh finding the kth element by using the random function uh takes a linear uh linear time complexity and you can find that out but it does take like on average it does take only linear time in order to find the kth element okay now we just have to implement two more functions one is the getting the middle uh index that is pretty straight forward and get middle it takes and nums and it takes the left and the right all you have to do here is what you need to do here is like uh and i is gonna be equal to l okay i was gonna start uh with l and then our j it's gonna start from l plus one right and then it's gonna go all the way up to the right less than and equal to right and j plus okay now if because i is the one element before that uh like a slow not a slow and a fast pointer uh i is lagging behind and a j is one behind uh one ah ahead so we're gonna ahead of i at the beginning but it's gonna keep incrementing so what we need to check is that the nums of j if it is less than nums of l now we're gonna swap numbers of now we're going to increment i because we don't have any another way to do that as we are just in this loop by just incrementing j and we're going to stage it okay once we come out of this for loop uh we are gonna swap one more time uh nums with uh left with the i and then we're going to be returning i this is to get so you are swapping you are actually changing there and the array and at the same time we are actually returning the eye where the i instead okay this is the middle element of that so basically get middle is gonna be return you the middle element of that array if you start from the left and the right and it's also gonna make sure that all the elements in there when you get the middle element like the all the smaller elements are to the left and all the bigger elements are to the right so the last thing is the swap we don't return anything in it all you do is to get an end num and i and end j so basically you're gonna say that the t is equal to the nums basically a temporary element numbs uh at that eighth position um we're gonna now we have saved the n number five so we can change it number j and numbers of j is gonna become equal to t so over here we have a diaper it does not recognize ght this is because i put this one in here did not recognize x this should be the new index of i and n numbers of i numbs of length numbstruck length didn't like that cannot find the symbol random this should be because we already had that end right should be then okay did not like that because we didn't define it again should have been numbs okay no i didn't like it so basically our uh once we find the median uh we say that n is equilibrium start length what we are doing here is setting i equals to zero left is equal to zero and right is gonna be n minus one okay then the i is as long as the i is less than that what we are saying is like find the new index by uh by actually like taking the i and then using that formula of multiplying y two plus one uh and then taking the modulus uh taking the modulus mod of that uh by n this is good and then the next time if it is creator we are saying that the left is going to get incremented and the i is going to get incremented okay and then the next time if it is less than that we are only in decrementing the right and keeping the eye the same that's what we wanted to do okay let's check out our kth largest element in order to find that we are starting i uh from nums dot length minus one and then it is greater than equal to zero and negative we are swapping uh i with the random next dot n next n i plus 1 that looks good we are starting our l with 0 and the right over here and the k is getting decremented while this l is less than r uh we are saying that get the middle one with the numbers l and r if the m is less than k then l is gonna become uh m plus one if it is greater than k then the m minus one is gonna become and the right is gonna become my minus 1 otherwise break it looking good so far now the middle is where we have we start i with the l and then the j is equal to l plus 1 j is less than equal to r j plus okay if the number of uh j is less than the norms of l all right we're gonna swap the nums uh and increment the i and then j okay and then we have n i n j so he's saying we're going out of bound okay we have been calling this function over here okay and we have been calling this function over here okay numbs off and there is one more point where we are calling it when we are calculating this in that case we are sending the nums i and random dot next and i plus one right and i is going from looking good okay this can be a plus one right yes we are also calling the swap over here in the this one let's check that out so what is going on here is we're making sure that the right was initialized as n minus 1 right we are saying that the i is less than equal to the right and i was also initialized uh to zero okay yes and then we are saying that this web is gonna be used for the nums where the nums are of next new index uh left plus and n yes a new index i so the error over here is that we are not actually using the numbers of that we just needed the index here for all of it's just gonna be the new index and because the value of that can be anything let's give that a try looking good and it works | Wiggle Sort II | wiggle-sort-ii | Given an integer array `nums`, reorder it such that `nums[0] < nums[1] > nums[2] < nums[3]...`.
You may assume the input array always has a valid answer.
**Example 1:**
**Input:** nums = \[1,5,1,1,6,4\]
**Output:** \[1,6,1,5,1,4\]
**Explanation:** \[1,4,1,5,1,6\] is also accepted.
**Example 2:**
**Input:** nums = \[1,3,2,2,3,1\]
**Output:** \[2,3,1,3,1,2\]
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 5000`
* It is guaranteed that there will be an answer for the given input `nums`.
**Follow Up:** Can you do it in `O(n)` time and/or **in-place** with `O(1)` extra space? | null | Array,Divide and Conquer,Sorting,Quickselect | Medium | 75,215,280,2085 |
349 | welcome to book screen talk and let's write some code today so we given two integer arrays nums one and nums two return an array of their intersection each element and the result must be unique and you may return the result in any order all right so essentially what we're supposed to do is return the common elements between these two arrays um it doesn't matter how many times the elements are repeated the output should be unique numbers only so one way is to you know for every element in nums one you check if that element is present in Num two if it is then you append it to the output right and then you just find the unique values from that but how do you actually write it in code so let me bring up the code so all you have to do is list compression right which gives for X in nums 2 if that X is in nums one only then appended to common or else ignore it right now instead of returning set of common and then taking list of that we could have just easily added it here and then you know made this into a return statement and have it as a on line answer to this problem but um just for understanding what is going on that is why I kept it um in two different lines well that's it for today subscribe for more | Intersection of Two Arrays | intersection-of-two-arrays | Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000` | null | Array,Hash Table,Two Pointers,Binary Search,Sorting | Easy | 350,1149,1392,2190,2282 |
429 | hey how's it going we got another question today which is nine area tree order level traversal which is a medium given a nine airy tree return the level order traverse of its node's values so a level or a traversal we have level zero here in this example we have actually let me rewrite that looks like level 10 level 0 level 1. level two level three and the level four and you see with this question that the levels i've drawn out correspond with the output so we have one for level one two three four five for level two six seven eight nine ten for level three and so on and so forth so for this question we want to do a breath first search what is the best first search and why is a lot better than the alternative which is the depth first search brass first search would look at each of the children before going any deeper so for one you look at one uh for you look at each of his children so you look at two then you look at three then you look at four and then you look at five the depth first search on the other hand would do something different look at like two then look at three then look at six then look at seven eleven fourteen before you look at four or five and this becomes more of a headache for us because we wanna do a level or traversal and look at all of these children at once so let's start with our initial value in some data structure which is one we know from this value we have a we know the length of the first row is one so row length is equal to one we could pop this value out and have our first level have the value one which is correct then we want to add in all of its children which are two three four five six oh wait two three four and five and we want to keep track of the row length here as well row length is equal to four why do we want to keep track of this is because we're going to be adding the children to this data structure as well so let's see the ch so first we would pop out two add to our output and add in two's children two doesn't have any no children then we look at three pop it out add to our output at his children which are six and seven then we pop out four ad in this children which are eight oh my mistake we want to add four here add eight over here then pop out five and add its children which are nine and ten so having that rolling stored from before tells us when to stop so it tells us to stop after four values because these four values are in the row and the rest are all children so then for our next iteration of this process we have six seven eight 9 and 10 an array we basically do the exact same thing which is store a row length equal to 5 pop them out and add them to our output array while adding their children six doesn't have any children add it in add seven pop it out add its children in eleven eight pop it out add it in add their children pop it out add it in other children which is 13 and 10 doesn't have any children so you just add it in there we go and we stop at five because we know there's five values if we continue this process we'll just be filling and emptying this data structure until we eventually get to popping out 11 12 and 13 giving us the data structure with just 14 popping that out and getting our final list so 11 12 13 and then 14 which is our expected answer right here so what data structure should we be using for this problem we want to so let's look at it from the beginning when we pushed in 2 3 4 and five we wanted to look at two then three then four and then five before worrying about any of the children here right and the order we pushed them in was two then three then four then five because we looked at one's children which was first two then three then four then five so we have first in first out so this has to be a q it doesn't have to be a q like don't get me wrong you can use that array but for simplicity's sake you can use a cube because you can just pop out the first value that you added in um so with this first in first out structure all we have to do is start with the q having the root value pop it out add its children like we did here and continue this process until the queue is empty because we'll reach 14 it doesn't have any children to add in and that's the last level that we're reaching so with that being said let's look at the time and space complexity for this question the time complexity we're looking at n is equal to the number of notes and we're going over all the nodes so this time complexity is o of n space complexity on the other hand would be less than or equal to o of n because the maximum space would be um a fully fleshed out tree the last row of values which are these ones four and two is seven so we can do the math to figure this out in terms of height it's probably some factor of i two to five h so it's probably o of h i don't really want to do the math right now but that's the time and space complexity generally so we can look at some code so you guys can get a better understanding of the problem here we have my solution uh if we the root is now we don't do anything we just return uh empty and we just add the root to our q otherwise and while the queue isn't empty we run this process where we store the number of values in the current row add the values in the current row and add the children to q and continue this process until eventually we have run out of values and we can return our output uh this works fine and this is the most optimal solution so thank you guys so much for watching uh the code is always in description make sure to like comment subscribe it means a lot if you could upload the problem you know uh i'll upload my solution on lead code because the answer will always be in the description so if you have any friends that are worried about algorithms or studying for interviews make sure you share this with them like comment subscribe and i'll see you guys in the next video thanks | N-ary Tree Level Order Traversal | n-ary-tree-level-order-traversal | Given an n-ary tree, return the _level order_ traversal of its nodes' values.
_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** \[\[1\],\[3,2,4\],\[5,6\]\]
**Example 2:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** \[\[1\],\[2,3,4,5\],\[6,7,8,9,10\],\[11,12,13\],\[14\]\]
**Constraints:**
* The height of the n-ary tree is less than or equal to `1000`
* The total number of nodes is between `[0, 104]` | null | null | Medium | null |
399 | hey guys welcome back to another video and today we're going to be solving the lead code question evaluate division all right so in this question we're given equations in the format a divided by b which equals to k where a and b are variables represented as strings and k is going to be a real number given some queries return the answer and if the answer does not exist return negative one okay so the input is always valid you may assume that evaluating the queries will result in no division by zero and there's no contradiction so one thing we want to note over here is that there's some sort of relationship which there is so for example when you're doing a divided by b there's a relationship which gives us a value of k and another thing you want to notice is that there's a strict conditions over here which is the fact that the queries will not result in division by zero and there is not going to be any contradiction so using that we can kind of assume that this question is going to be a graph question so for example let's look at this first example over here so i just drew out the first same example over here so a comma b and b comma c and what this basically means is that a divided by b is equal to 2.0 divided by b is equal to 2.0 divided by b is equal to 2.0 so a by b is equal to 2.0 now one more so a by b is equal to 2.0 now one more so a by b is equal to 2.0 now one more thing we can deduce out of this is the fact that if a by b is equal to 2.0 we can take if a by b is equal to 2.0 we can take if a by b is equal to 2.0 we can take the reciprocal of that so all the reciprocal is the numerator becomes the denominator and denominator becomes the numerator so a by b equals to 2.0 and we also have so a by b equals to 2.0 and we also have so a by b equals to 2.0 and we also have one more thing which is b by a is equal to 1 by 2.0 b by a is equal to 1 by 2.0 b by a is equal to 1 by 2.0 so we have both of these conditions that we can account for similarly for b by c equals to 3.0 similarly for b by c equals to 3.0 similarly for b by c equals to 3.0 we can also say that c by b is equal to 1 by 3. so we have those two conditions that we also can account for so over here we're going to draw a quick graph so over here we're going to have a node with the value a then we have b and then we have c so now 8 divided by b is going to give us a value of 2. now one more thing that we noticed is earlier we saw a by b and b by a both have completely different values and that tells us that this graph is directional so the direction does matter so a to b is not the same as b to a so in this case a to b so a divided by b is equal to 2 but b divided by a is going to be equal to 1 by 2 or 0.5 is going to be equal to 1 by 2 or 0.5 is going to be equal to 1 by 2 or 0.5 similarly over here b divided by c is equal to 3 but c divided by b is equal to 1 by 3. so this over here is our little graph that we have but now the question is how exactly can we use this in order to get an answer so i'm pretty sure you understand how can we get the answer to a divided by b divided by a b by c or c by b right all of them we kind of went through that now the question is how do we get the answer of a divided by c so this is what we want the answer to so currently we have a value of a by b and we also have the value for b by c and we also have the values for the reciprocals of each of these and the value that we're looking for is a by c now if you multiply these two values a by b multiplied by b by z the b and b get cancelled out and this equates to nothing but a by c and that is exactly what we're going to do we want to get from a to c so to do that we first go from a to b and that over here has a value of 2. so we're going to get that over here and in other words this 2 just represents the value of a by b similarly we go from b to c and that again just represents the value of b by c and what is this b by c equal to it equals to 3. so over here we're going to multiply these two numbers giving us a value of 6 and this value of 6 is going to be the value of a by c and real quickly let's just double check it over here so we made a query of a by c that's the first query we made and as you can see over here the first query a by c is equal to six so we did get that correctly and real quickly one more example let's say a by e and when you have a by e where is e does not exist at all in our graph so in that case we're going to end up returning negative one as we did over here okay so hopefully you understand how this works and now what we're going to do is we want to code it out it might be a little bit confusing and while coding this how we have two different approaches we can take a depth first search approach or a breadth first search approach i don't think any of them has anything better or an advantage over the other one but they just work slightly differently so for this question we'll be taking a depth first search approach all right so over here we're going to be having two different steps so our first step is going to be to build the graph and in our second step we're going to be going through each of our queries and we're going to perform a depth first search in order to come out with the answer for that specific query okay so let's start off with the first step which is building our graph so over here we're going to have a variable called graph which is going to store our graph and in order to get that we're going to be using the default dictionary from collections so collections dot default dict and then we're going to be using a dictionary the reason we're using the default dictionary from collections instead of the inbuilt dictionary of python is because for default dictionary so let's say you try to access some value which does not exist then in that case you're just going to assign it a random value and it's not going to throw out an error okay so now that we have this we're going to add stuff to our graph over here so to do that we're going to be iterating through our equations and our values for that so to do that we can use the zip function so for our values we're going to be getting x and y uh just two arbitrary values and each of them are going to be strings and the other thing that we're going to be getting is going to be the value of it called val okay so for this in zip and we're going to be getting the equations and we're also going to be getting the values okay so now that we have this inside over here we're going to be defining our values we're going to go to graph and then we're going to go to x and then y and that is going to be equal to our current value and we also need to do the inverse of this so like we saw earlier so graph x y that basically says x divided by y equals to this value and in other words uh what this is doing is where we have a key x which points to y in simple words and now what we're going to do is we're going to do the opposite so y pointing to x and in this case the value is going to be the reciprocal so 1 by val and i'm just going to do 1.0 and the reason i'm doing 1.0 is that 1.0 and the reason i'm doing 1.0 is that 1.0 and the reason i'm doing 1.0 is that way we're gonna get a floating point value since that's what we want so now that we have this we're done with the first step which is creating our uh graph so before we go into building our dfs function over here we're gonna define our results list which is just going to be an empty list and to this we're going to add all of our results so now what i'm going to do is we have the queries over here so let's go through each of these queries so to do that let's just do for query and queries okay so now that we have each of our queries we're going to be adding the value of these queries to our results value over here so res dot append and over here we're going to be calling our dfs function so dfs and what are we going to be calling it on so over here we want to give the query and we're going to give the 0 index of it and we're going to give the first index of it so the 0th index is going to be the first value so this let's say this is x and this is y so it's going to be x divided by y and over here we're also going to give it a set and this set over here is going to be used to track um the values that we've already visited the purpose of this will be really evident once we're creating our dfs function and that should be it for our queries and at the ending of this we're just going to end up returning our results error finally over here we're going to finally build out our dfs function so that's the last thing we need to do and over here we're going to give it a x value a y value so that's going to be x divided by y and we're also going to be giving it a set called visited sorry visited i can't spell okay there so visit it so what visited is going to be used for it's going to be telling our dfs function what notes did we already visit so if we already visited a node there's no point of visiting it another time so in that case uh that's what we're going to be using our set for and the reason we're using a set and not a list is because a set has faster lookup times so yeah okay so over here in our function we have three different conditions that we can look for so our first condition is going to be if our x value is not in our graph or our y value is not in our graph so when if neither of these are not in our graph then in that case that means that we're never going to get an answer so in order to take care of that condition we can just directly return negative one uh and more specifically i'll be returning negative one point zero since we will they want us to return a floating point value okay so that's going to be it for our first condition and now our second condition is going to be if we actually have a direct connection so what i mean by that is let's say we have a to b so there's a direct connection from that right a divided by b does exist so in that case what we're going to do is we're going to go to our graph and we're going to iterate through the x values so that is going to give us all of the nodes that it connects to so in order to check if y is one of those nodes that x points to then in that case we can just directly return that value so if sorry if y in graph x then in that case we can just directly return its value and its value over here is going to be graph x and then y and that is going to give us our value finally we have our third condition so our third condition here is going to be for the fact that we did not have any of these met over here and more specifically this third condition is for when we have some sort of a division but they're not joined to each other directly right so for example when we're doing a divided by c over here a and c are not directly joined we go to a to b and then b to c and then we multiply those two values so that's what we want to do and to do that before we actually do that i just want to show you how our graph looks like so you can kind of understand how we can possibly do this okay so yeah it's obviously going to be wrong but this is how our graph looks like so over here we have the node a and a points to b so that's what it's showing us similarly b points to a and c on the points to b okay so using this we want to get a value of a divided by c so what we're going to do over here is we're going to have a over here and we're going to iterate through all of the values inside of a in other words everything a is pointing to could possibly lead us to c and we're going to check each and every one of those until we get to c so over here there's luckily there's only one value but there could be more value so we're going to be putting it in a for loop and we're going to go through each of those nodes so over here we have b and now what we're going to do is we're going to call the dfs function but this time we're going to be calling it on b and c so we're basically going to find the value of b divided by c so now what's going to happen is we're going to check if b exists and b does exist as a key and luckily for us c also exists as one of the keys so we're just going to end up returning the value 3 and we're going to multiply that with our current node which has a value of 2. now in this case this is pretty simple we only have two of them but what if we had more of these nodes that we want to travel to so in that case what's going to happen let's say in b as well let's say this c does not exist so what's going to happen here is we're going to call this function one more time with whatever values are over here one more thing that you want to notice is that in order to avoid us going and visiting the same note several times that's why we're using our visited set in order to see which nodes we have already visited okay so let's just do that over here um so finally we're going to be iterating through all of the values for i in graph x so that gives us all of the values uh or instead all the nodes that graph x is pointing to okay so now that we have this we're going to check if that is inside of our revisited list so if i'm not invisid then in that case we're going to go ahead and do these steps okay so what we're going to do is we're first going to go to our visited set so visit it and we're going to add this current i value it's just so that we don't go and visit it another time so visit it dot add i okay and now over here we're gonna have a temporary variable which is just gonna store the value currently of our dfs function which we're going to call on this new node so let's call the dfs function we're going to be calling it i comma y and this y over here is what we get from over here so we're basically doing i divided by y right now we want to give it one more value which is the visited set that we have over here so we're going to give that as well so visit it okay so that's what we end up having over here now over here we're going to have two conditions so we might not end up having or finding any value so in that case our temporary value is going to be negative one so when our temporary value is going to be negative one and in that case we're just going to continue so what that means is we're going to go back over here to our for loop and we're going to look at the next possibilities or the next possible options but if this is not the case so else this is not the case then what we're going to do over there that means that we have some sort of value in our temporary list and like we did earlier we multiplied those two values with each other so we're going to do that so return so we're going to go to graph x since this is what we're on and we're going to go to that current i and we're going to this is going to give us that current value and over here we're going to multiply this with our temporary variable over there and that is going to be it and one more condition that we want to do over here is at the very ending if we do not get anything that means that we do not have any answer and we're going to end up returning negative one and that should be it and one more thing you want to notice is each time we start off with a fresh set of for each of our queries and uh each time we're going to be adding that to our results so that should be it so let's submit our solution over here and as you can see our submission did get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if the video helped you thank you | Evaluate Division | evaluate-division | You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits. | Do you recognize this as a graph problem? | Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path | Medium | null |
146 | what's going on everybody zane here back with another video for this one we're going to go over question number 146 which is lru cash lru is representing least recently used cache so in this problem here what we're being told is to design a data structure that follows the constraints of the least recently used cache now although we're being asked to design the data structure there's actually a much more efficient way of solving this problem because in the end what we want to do is if we had an example such as the following where we're putting two integers into some cache we'll say one and then we'll put two and two then the next one would be three and these could be any values and we're using two integers so because that's what the key and value are they're both ins so we put in these values and now if our capacity was equal to 3 that means that our capacity has been reached so now lru is going to come in least recently used is going to come in when we need to do our fourth operation where now we need to add in another value such as 4 but we can't do that because we are already at capacity so now lru comes in by taking away the oldest value and then adding the next value so when we're considering this question and any question really we need to think about what type of data types we need to use so here we're seeing puts and gets we're also seeing a runtime of 01 and we're seeing a lot of key value stuff so right off the bat we're gonna we know that we need to use some sort of mapping but we also have the lru portion which is telling us that hey we need to do something with the head when we have a new tail so that is going to tell us that we need a doubly linked list now before i go into explaining this we need to establish the fact that once we have our data types we can use the built-in functions of java to our the built-in functions of java to our the built-in functions of java to our advantage we don't need to necessarily create a new node class and then establish the variables there and then link the heads and tails we don't need to do that right now what we could do is we can extend an existing class called the linked hashmap because essentially that's what we're doing we're going to be dealing with a doubly linked list and a hashmap of some sort so we can just extend the existing collection of the linked map and this hash map will be of type integer and integer because our key in values are both ins now that we've done that what we can do now is we need to establish a capacity so although we're being given capacity inside of our public lru cache let's first initialize it and then we'll say that this capacity is equal to capacity and now we need to take care of the access order so what we can do now is we can use the parent classes methods or functions in order to do that we would use the super keyword and what super is doing is just using the parent classes initial methods so whatever is part of the linked hashmap class that's what's going to be used after this statement so i'll just say super and then i'll overload the linked hashmap method to be capacity and then some decimal value or some float value and a value of true or false now in this case i'm going to put true and the reason for that is because i want the access order to be specific to its access and not insertion so when true equals access order when false equals insertion order so since we're dealing with lru we need to use the access order which is why i have true here and i'm overloading it with the capacity of float and true you can read a little bit more about linked hash maps you'll see that i have some tabs open just reading up on what exactly load factors are and whatnot but i saw that in the solution for the lru cache people were using 0.75 f and it looks like that seems to 0.75 f and it looks like that seems to 0.75 f and it looks like that seems to be a good trade-off be a good trade-off be a good trade-off in terms of time and space like right here as a general rule the default load factor offers a good trade-off between factor offers a good trade-off between factor offers a good trade-off between time and space costs so if we were optimizing something perhaps 0.75 would be better perhaps 0.75 would be better perhaps 0.75 would be better but in this case it does not matter so i'm going to overload it so that we are this is really the main thing we care about we want the access order that's the whole point of lru cache which is why we're extending this class to the linked hashmap class so we can take advantage of that property so now that we've done that we're done with our initializing of the public lru cache now we can use super the rest of our linked hash set a hash linked hashmap class so what i can do now is since we need to return the value from our map we can say return and then super dot get the value of the key and if that is equal to null then return negative one because we say here that if the key exists if the key does not exist then just return negative one so if it's a null then we'll return negative one otherwise if the super dot get otherwise we'll just return super dot get key now that's it for our get function because we're again using the get function from the linked hashmap class we're extending that and using the super as our parent classes method for our parent classes method now on our last piece here we have our put this is a void so we can do a simple super dot put key in value now if we were to run this we're not necessarily going to be finished although it looks like we're almost there but there's still a major aspect which is although we have our access order proper we need to now be able to remove our oldest key like in the example i'd shown below if we have our fourth entry and a capacity of 3 we need to remove the top value so what we could do is we'll create a function and it'll be a boolean function and we'll say remove eldist key ldist key and inside of here we're going to pass in a map entry of type integer and integer which is essentially going to be this linked hash map and we'll just call this map and we'll say that this will return true if the size is greater than the capacity so we want to remove the oldest key if and only if the size of our map is greater than the capacity or the size of our lru cache is greater than the capacity so if we try to run this we're still going to get an error here because there's still one thing missing and that is we need to actually override this function and the reason we're overriding is because we don't want to actually use the parent classes function we just want it to do its own thing so we'll run this now and we'll see that there does not implement the magic from a super type okay that's fine what we can do here is we'll change this to a protected um and see if protected static might work okay so there's an issue here and i would assume that it's because i'm using the wrongest uh yes so i'm using the wrong name so remove so i'm going to change this back to public let's try that again and now it's saying that cannot override so now i'll change this back to protected and take this off there we go so this is something that i've learned and i wanted to share and i'm glad these errors occurred because when we're trying to override something it needs to be in a specific type when we're doing the signature of the class or of the method so if i was to do public i just want to see if that works out so public still works so just make sure if you're overwriting something it needs to have the exact name of the parent classes method now once we've overridden that we can say okay instead of doing what you typically do we're going to override the signature with this and return only if the size is greater than capacity and then when we submit this we should be good to go so just to recap real quick we already have our lru cache we're extending the linked hashmap class passing in an integer and an integer initialize our capacity inside of our public lru cache we'll set the capacity to equal capacity just like we typically do for any class creating of the constructor and then we'll super the capacitor will super and overload the bypassing in the capacity some load factor in this case we're just using the float of one and true only because we want the axis order not the insertion order that's the whole property of the lru then in our get we can just use our parent classes super so we can get the value of our key and if that's null then return negative one otherwise we can return the keys value alternatively i think what we could do is we can return super dot get or default and we'll get the value of the key or turn negative one now let's just make sure that works yeah so this is a little bit cleaner and then for put we'll just do our super dot put and we override the remove eldist entry method and only do that if the size is greater than the capacity anyways guys that's it for this one if you have any comments questions feedback please let me know in the comments below otherwise hit that like and subscribe button show me some love and i'll see you in the next one peace | LRU Cache | lru-cache | Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`. | null | Hash Table,Linked List,Design,Doubly-Linked List | Medium | 460,588,604,1903 |
1,269 | Welcome to my channel code Sorry with Mike So today we are going to do video number 70 of our dynamic programming playlist. Okay, this is a very easy question. Actually, this is such a hard question which is quite easy. Okay, it should have been marked as medium. The lead code should be given less than code number 1269. Ok, it is very simple. The bottom will be made with recurse memorization. You will have a separate video. First, I am making the video with recurse memorization. The name of the question is Number of Ways to Stay in the Same Place. After some steps g and mater asked this question so the question is quite simple that you have a pointer at index zero in are of size are length there is an array whose size is length and you are standing at index number zero okay at In each step you can take three decisions, either you can go one position right or you can stay at the same position, meaning if we assume you are standing at X ID So you can take a step right, either left, or you can stay here, okay, the pointer should not be placed outside the are at any time. Okay, if we assume that our length is the length, then the index from zero to Arle will be up to a minute and should never go to its left side i.e. out of bounds never go to its left side i.e. out of bounds never go to its left side i.e. out of bounds either from zero to left or from Ar length to right side is ok then given two integers we have given you two Integer steps and Ar length is ok Is return the number of ways true that your pointer is still at index zero after exactly step by step ok and the answer can be big then send the answer by doing model 10 power 9 p 7 ok total number of ways tell how many such are you There is a Veda in which you reach index zero only, by taking back, this number of steps is fine and you can do these three moves, one left, one right and either stay in the same position. Let's see this example, we have only steps. The length of is three, the length of is two, let's write down the length of two, so there is zero index and first index and you are starting from zero, okay, you are starting from here, we have only three steps, so how many ways are there to do that? One way you can reach back to zero is that you stand at zero, remain at zero in the first step, remain at zero in the second step, if you remain at zero in the third step, then you have completed all three steps. If you are at zero in the step, then one way is this. What is the other way that you were at zero then went right, walked one step, then went left, walked two steps. Okay, that means you first went right, then left and then came to zero. When you came, you stayed there, then you took three steps and you came back to zero. Okay, what happens after that is that you went right, stayed there and then came to the left. In three steps you came back to zero. You see, you were at zero, what happened here, went from zero to one, went back to zero from one and stayed, then you are at zero. See, the ending should always be at zero and the steps should be completed in full. Total three steps. So there should be three steps. Okay, look at this also. If you went to index one, you went to the right and stayed there, then you remained at one. If you came to the left, the index number became zero. Okay, what can be another fourth way that you Stay here, okay, then went right, then left, meaning if you stayed then you are at zero, then if you went right, you came to one, if you went left, you came to zero, the ending is at zero and you are looking at the steps, he is using only three, this is four. There is a wage, there is no wage more than this, the answer is four, okay, it is quite simple and if you want to see how to approach it, then I would say forget that this is a DP question, you will assume that you already know. No, forget the question of what, okay, but I told you one thing that if you are seeing options on every index, then there are options, you can go right, you can go left or you can stay, if there are options, If every index is visible then always make a tree diagram. So taking this example I am making a tree diagram. I have not yet told you that it is a question of DP. I said if options are visible then make a tree diagram. Okay, make a tree diagram. Remember, you started from index number zero. You have to start from zero itself. Index number is zero and now how many steps do you have left. Three are left. Okay, let's make a tree diagram. Okay, what is the first option? Either you are at the same point. Stay on the same index. What is the second option that you go right? What is the third option that you go left? Okay, now see, if you go left from zero, the index number will become minus and move to the right and step one. If you move one then step. Now only two are left, okay but if y is minus and index is yes then it is invalid then we will not go further. Okay, now let's look at the stay case. If you stay then the index will remain the same but one step has been taken. No, now you have two steps left. Okay, let's see on the right. Index will become one because you have gone right and only step two will be left. Okay, let's expand this one. Okay, let's expand it here with the white pen. You also have three options, okay, the first option is that you stay here, if you stay then the index number will remain zero but one step will go right because one step is being spent every time, what is the thing after that you right? You can go, what after that you can go left, okay if you go right then index number will become one and now step one is left, only if you go left then index will become minus one step, now only one is left, okay if stay also. If you are doing that then the steps are also being counted. Okay, let's look at this again. You have three steps. Stay, go right or go left. If you stay, then the index number remains at zero and the step is now zero. If you go right then the index number is one and has become zero. If you go left then the index number is minus one and the steps have become zero. Okay, look at this too, there are three options here. The first option is to stay at the same index and the steps number should become zero. We have gone right, we have gone to index number two, we have reached zero, we have gone left, we have reached index number zero, we have reached steps zero, it is okay, it has gone to minus one, so it cannot go further, it is okay till It is clear that let's expand it left right means this is stay This is right this is left If you stay then you will remain at index one Steps become one If you go right then index number becomes two steps One If you go left then index number is zero Steps one Done, pay attention, is there anything else left? Yes, look at this, pay attention, this index is out of bounds, right, we have reached index number two was never there, because if the length is two, then the index is zero. And if the index remains one then it is out of bounds, we cannot move beyond it, okay this index number is zero, on this also we have three options, if we stay then 0, if we go right, and 0 if we go left - 1 0, if we go right, and 0 if we go left - 1 0, if we go right, and 0 if we go left - 1 0 Okay, you can't go beyond this, it's mine, it's gone out of bounds, there are three possibilities here, if you stay, then 1 0, if you go right, then 2 0, if you go left, then 0, Okay, you ca n't go beyond this is mine. It is out of bounds. Okay, so let's see if it can expand anywhere else. Look, this will not expand. It has gone out of bounds. The negative index has gone. This too has gone negative index. The steps end here. Look, this. You can't move further, the step has become zero, so this is also the base case, my step has become zero on this, it has gone out of bounds on this, you see, the index has gone to two, the step on this has become zero, it is out of bounds on this. This is also out of bounds, this is also step zero, this is also out of bounds, this is also step zero This step has also become zero. Okay, so what is the question in the question that the step should become zero and now it should reach back to zero. After using all those steps, see what is that condition, that is, after using all the steps, it means the steps should be zero. The remaining and your index should be at zero, so where are the zeros and 0s. Let's see one, two, three, four. Okay, so our answer is four. Okay, so how will it be four? Look. 0 P. As soon as I reached, I said, one way. Got it, I have returned one from here, this number is 0, okay, since steps, it has become zero here, but look, the index is still one, so it means it is not a possible answer, so I have sent zero, this index must be out of bounds. When I went there, the answer was zero. Take out the sum from all the three possible ways. 1 + 0 + Take out the sum from all the three possible ways. 1 + 0 + Take out the sum from all the three possible ways. 1 + 0 + 0. What will be the return? Here I will do one. Okay, here too I will cry because look here, the step has gone to zero but till now I am on index one, I am zero. But it should have also been 0, if it sends one, then 0 + 0 + should have also been 0, if it sends one, then 0 + 0 + should have also been 0, if it sends one, then 0 + 0 + 1, here one has gone, it is okay, here it is out of bound, so if it has sent zero, then 1 PPS 0 1 P 0 2 has come, it is okay here. Let's see here 00 1 So one is gone here Zero is here Look here 0 So one is gone 1 P 0 Pw what happened 2 So it came from here So 2 P 0 The answer is here 4 It is simply clear. And look, I told you that look, learn some things about tree diagram, it is good forever, when should we try tree diagram, we generally come up with tree diagram only in recursive questions because we have options, if you see options that every Index P: If if you see options that every Index P: If if you see options that every Index P: If you have the option, then make a tree diagram. Second, what happens in the tree diagram is the leaf nodes, that is the base case. Okay, so what is my base case, where I stop, pay attention to where I was stopping, if My index is if it is less than zero or if the index is greater than or equal to our length then we will return zero here. Okay what was another base case that my steps became zero so beyond that I cannot take any more steps. If I can then what will I do in that case that if my steps become zero then I have to check that all the steps are finished then if I have reached back to index zero means I have found one method then in that case I will return one and if it doesn't happen then I will return zero right like look here the steps have gone to zero okay but I am not back to zero on index two okay I have to get back to index zero on the edge Questions why have I returned zero? Okay and if these two are not the base case then there were just three simple possibilities. The first one was that you either go right or go right then what will happen, there will be a pause and the steps will be there every time. The second possibility was that you go left i.e. index goes i.e. index goes i.e. index goes steps left, it is okay. The third option was that you stay at the same place, this is also simple, the index will remain the same but the steps will always reduce, okay. And what we were doing in the last, remember right plus left plus right, I have said that you have to send it in answer mode, then whatever result will come from solve here, doing it in model mode is fine, power of 10 is fine, power of 9 is fine with 7. It is given in the question, so after that we will do right plus left plus here and see, memorization is very easy. Two variables are changing, so what will I do simple, I will take a deeper of two dimensions. What is the first dimension, what is the index, second dimension is the steps. Okay, so let's look at the constraint, what is the constraint given, so look carefully here, the constraint is given, my maximum will be 500 steps and the length of the power of 10 will be 6, so what does my index mean, it will be 10. Power of 6 can go up to 6 mive, in the worst case it will be a very big test case, and the steps which are there will be 500, so if I mean to make the steps, memoization, I will take 501, okay here and the current index is my power of 10, 6 mive. You will have to take it, Natalie, you can't take such a big DP, it's too much size, you can't take it, you wo n't be able to define it, okay, if an error starts coming, how to fix it, then this is an important part of this question. If you notice, pay attention to this example, let me take a small example, let us assume that the length is 1000, it is fine and the steps you have, you can walk maximum five steps, I have given you five steps. If you want to cover then the length is Haj so let's start with index number 0 T and so on till 999 index will be index number zero this is one this is two this is A so on ok it will be till 999 index so now tell me one thing you Obviously, it is given in the question that you will start from index zero. If you are watching, then what is the maximum distance you can go on the right side? One step, two steps, three steps, four steps, five steps. You can go maximum only five steps. It is on the right side, you will not be able to reach Hajj, there is no point, you will not be able to reach, okay and if we assume that the steps were 500, then you would be able to walk 500 steps. Okay, if the steps were Hajj, then you would be able to walk till 1000. You could walk, but look at the steps. If you count the steps here, if it were 10, then you can go maximum right side up to 10 and if you look on the right side, you will not even go till 10. You will have to come back at zero, but in the worst case, I say. I am saying that maximum you will walk only 10 steps while going right, meaning I am saying that you will be able to walk on the right side only as much as the value of steps is, so there is no benefit in giving such a long length, okay, so what am I saying? I am saying that even though the length has been given as 1000, how much will you be able to walk, the value of steps is not 1000, you will be able to walk only 10, so do you know what we will do, we will modify the length, whatever is the minimum value of length given. And the value of steps given is okay, the smaller one among the two will be assigned the length, like look here, the length was 1000 and the steps were 10, so the length is equal to the minimum of 1000, so the length is 10. Mine will be 10. Okay, so with this we will fix this issue. I was facing the issue that I cannot take such a big size, so what will we do this time? The maximum size is of steps, it is also of length. We will take the same, okay and you are thinking that why I have taken the minimum here, maybe the example is like this, the length is five and the steps are 10, okay then what is the minimum of length, mine is five and steps are mine. If there is 10, then there should be only five, so the length of five will remain only five, okay, that is why we are taking minimum of array length comma steps so that even if this step is bigger than 500, let's say, then the value of these steps is small. So the steps will be assigned in it because maximum you can go only this much. Okay, so see, our memoization is now fixed, it has become smaller. Okay, so let's see, code it and submit it. Memoize it if you are able to pass all the Best cases, after that we will do a small space optimization. Let's code with OK. It is very simple with our rectors and memorization. I told you that you can also reduce the length. Whatever is the value of minimum of length and steps because maximum. You can go only a few steps, it's ok on the right side and define a variable n e err r lane and keep it global int a ok b simple i have to write recursor nothing else what will you pass here zero index I have to start from and I have the same number of steps, I have to complete it in this and create a zero index from back then int solve int id one in these steps okay so remember our base case what comes if id x my lesson becomes zero or else If ID If my ID is not zero then false i.e. my ID is not zero then false i.e. my ID is not zero then false i.e. zero will be returned. Okay, after this there were three possibilities that if I go right, it is okay. Either we write like this and store it in a single value. Int result is equal to two. If I go right, that means. If I go left then steps-1 is ok. Here I write steps-1 is ok. Here I write steps-1 is ok. Here I write that I went right. Result plus ev two. Either result is equal to result plus solve. If I go left then -1. Steps-1 is ok. And you have to keep taking the module. -1. Steps-1 is ok. And you have to keep taking the module. You have to get the result. E is equal to result plus if I stay i.e. E of I stay i.e. E of Result is simple s that is ok let's just memoize it in t how much was 501 and 501 ok already we will see if its value is if t of id one comma steps is not equal to my return t of id one Earn steps are ok and before returning here we will store it ok and here inila it is treated with memset by mive. We also have to define the mode as 10 power 9 p 7 so defined here by submitting. Let's see, hopefully fully, we should be able to pass the test. After this, we will see a small optimization. In fact, we have solved this question. Quickly, let's see that small optimization and solve it. Before moving on to the time complexity, if you see So remember on every index, there were three possibilities, right, then its exponential would be the time complexity, power of th, if we assume that the length is n, then n would be the power of 3, right, so this is my expo collection, but if I am doing memo. So remember I had said that maximum how many steps will you visit to visit the state, this much into this much is fine, meaning oh of are the length into states but I said that you can also change the length, you can shorten it oh of are the length. I have written ' can shorten it oh of are the length. I have written ' can shorten it oh of are the length. I have written ' thana minimum of are length comma st' and these states are already in the states. comma st' and these states are already in the states. Okay, so this is the time complex of my recurse memoization. Now let's come to where we can do slightly more optimization. Okay, let's see by giving an example. Let's assume that the number of steps we have is three and the length of our array is four, so the length of the array is four, meaning zero index, first index, second third index, I write that it is 3 steps, it is 3. Okay, so its output is actually four, okay, it is four, we will try it sometime, the answer will be four, it has four steps in total, so okay, tell me one thing, I told you that you have only three steps, so it is obvious from here. If you want to start then you will walk three steps, reach here in one step, reach here in two steps, reach here in three steps, okay but tell me one thing, if you accept that you have come here, followed your three steps, your steps are now How many zeros are left then you can go back to zero th index. If you can't go to the sum then you have to get the answer anyway zero. That's right, it means one step ahead was wasted and stopped here. If we assume that till now I have done two steps. So how many steps do I have left, one step is left, only one step is left, then you can go to zero, no, you need two steps to go to zero, so you have still gone ahead, you have gone too far. Let's also remove this, you have come here, how many steps have you taken till now, have you walked one step, are there two steps left, can you come back to zero in two steps? Yes, I can come within two steps. I can only come back here, then I will stay here, then in three steps I remained at zero, so now it is an obvious thing, if you accept it, you are at zero, it is okay if you do X move, look ahead on the right side. Anyway, you cannot go to the left side because there is a negative index, you cannot go there, but if you walk to the right side, if you walk If you go then you will not be able to come back to zero. What does it mean that if you walk on the right side then walk only so much that you make one journey backwards and you reach zero. The steps should be only this much and then there should be only this many steps. It should be only, that's fine, then you can write it as Batu 3/2 came 1 but if we Batu 3/2 came 1 but if we Batu 3/2 came 1 but if we take ceiling then what will be the ceiling of 3/2 it will be two, I take ceiling then what will be the ceiling of 3/2 it will be two, I take ceiling then what will be the ceiling of 3/2 it will be two, I mean I want to say that there is length, if you keep two then all your answer will come in that because if you move after this then you You will not be able to reach zero anyway. Pay attention. In this example, let us assume that you have taken one step, two steps have been taken, now you have only one step left, you will not be able to reach back to zero, then all those will be invalid cases, right, if the steps are taken by two. The ceiling of, that is, even of two sizes, is only hey, all your answers come from here, no, all the answers come from here, see how because you have only three steps, you will either go from here to here, one step becomes two steps. All that is left is to come back here and then in the third step, the same is left. Even if you go further, you have walked one step here, walked the second step here, then only one step is left, you will never be able to reach zero, okay? If the valid answer will not come anyway, then your valid answer will come in this space, it is fine in the space of this size, I mean what I want to say is that the length is actually the ceiling of steps by two too. You can do it means you can make it shorter, remember here I told you that you can reduce the length to steps, there is no need for such a big one because you will walk maximum this much, maximum you can walk this much, right side but valid. For the answer, look at the ceiling of steps by two. You will not go further than that. Here, as I told you, all the answers will come to you. Look, we were standing here, we stayed here, so stay. One way is this. The second one is done, from here you went here, took one step, the second step came here, stayed in the third step i.e. right, in the third step i.e. right, in the third step i.e. right, left and stay is ok, what was the first case in the first one, stay, all three steps are here, what was the second step. Went right, went left, stayed there, what would be the third one, stayed right, went back left, right? If you go out of this window then the answer will not come out, yours is ok, one more step, total will be four, its possible ways are ok. This is more slight optimization, what am I saying, not hey, remember the length, what I said earlier, what was this minimum off, hey, length, comma steps, you can do this, my submission was done with this, but I am saying You can make it even smaller, you will get the valid answer in the same size, length comma, sealing of steps by two is fine, what can you do to remove the sealing of steps by two, either use the seal of steps by two or So you can also write steps like this, it is okay, it will handle all the cases, there may be some issues in the seal, there may be corner cases, but it will not fail, right? It is best to do 6 bytes because look here. Also see, in this example, here my step was 3, what would be 3/2, how much would be 3, what would be 3/2, how much would be 3, what would be 3/2, how much would be 1, it would be 2. Okay, so look at the maximum, here we had taken only two sizes. Okay, so by doing steps by two. Let's solve it, we will just replace it with this and see if we are able to submit, the whole code is the same, just what is it doing instead of steps byte pv is ok, if we submit then this will also be accepted, just slight optimization is left. You must have understood the approach. Any doubt, raise it in the comment section to help you out. See you in the next video. Thank you. | Number of Ways to Stay in the Same Place After Some Steps | market-analysis-ii | You have a pointer at index `0` in an array of size `arrLen`. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time).
Given two integers `steps` and `arrLen`, return the number of ways such that your pointer is still at index `0` after **exactly** `steps` steps. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** steps = 3, arrLen = 2
**Output:** 4
**Explanation:** There are 4 differents ways to stay at index 0 after 3 steps.
Right, Left, Stay
Stay, Right, Left
Right, Stay, Left
Stay, Stay, Stay
**Example 2:**
**Input:** steps = 2, arrLen = 4
**Output:** 2
**Explanation:** There are 2 differents ways to stay at index 0 after 2 steps
Right, Left
Stay, Stay
**Example 3:**
**Input:** steps = 4, arrLen = 2
**Output:** 8
**Constraints:**
* `1 <= steps <= 500`
* `1 <= arrLen <= 106` | null | Database | Hard | null |
886 | hello everyone welcome to the channel today's question is possible by partition if you are new to the channel please consider subscribe a question says given a set of n people we would like to split every person in two groups of any size each person may dislike some other people and they should not go into same group formally it is like I a V it means it is not allowed to put people numbered a and P into the same group return true if and only if it is possible to split everyone into two groups in this way so let's move to pen and paper let's see how we can solve this question after that we will see the code you can take this question in such a way that we are given with the end number of people and we need to send them as a roommate and visa same only to Rome and we cannot keep two person who does not like each other in the same room if at the end we are able to assign them a room in which every person like each other we will written to else we will return false and amazing thing here is we just have two rooms so we can say we have room 0 and room 1 and if we see one does not like to one does not like 3 in that same way who does not like 1 and 3 does not like 1 and 2 does not like 4 so that means 1 and 3 cannot be in the same room 1 and 2 cannot be in the same room and 24 cannot be in the same room and if I talk about a general scenario you are saying with this Duty the t need to assign a group of people in two groups in such a way that in a single group the person will recite who like each other so what you will do first of all you will make a lesser person who does not like each other so we will also going to do the same thing we're going to make a dictionary I will take one I will lead to there I'll come to - and I know who does not like one to - and I know who does not like one to - and I know who does not like one toilet one there then I will come - I toilet one there then I will come - I toilet one there then I will come - I have one does not like three so we'll add three here and three does not like one solid three with value one I come too - who does not like four so come too - who does not like four so come too - who does not like four so I'll add 4 here I will come to four so I will add four with value - so now I have will add four with value - so now I have will add four with value - so now I have a kind of list in which I know that one does not like two and three - does not like two and three - does not like two and three - does not like one and four three does not like one and four doesn't like two and why I have taken dictionary because it's easy to look up so right now I have a list so what I can do I will ask one here once could you please tell me with whom you don't want to live then he say that I can't live with two and I can't live with three so suppose one is in room zero so I know that I cannot assign to entry in room two in the same way I will ask - and - we in the same way I will ask - and - we in the same way I will ask - and - we love and we will tell that I disliked one and four so I can't live with them so we know we cannot keep two and four in the same room and two and one in the same and we know we have already designed room zero to one and we only have two rooms so we have wrong one and rule so I have assigned room zero to one and I was in room 1 to 2 that means all other elements who are coming we have we need to add them to room to rent one and if any time the person who does not like each other or in the same room or unable to get into room zero room one will simply written forth or we can simply say that we are unable to form a group or unable to form in width we can make people live who like each other so I come to three I ask three hey could you tell me with whom you don't want to live then you say I cannot live with one so we cannot assign from zero to three so only option we have is drone - so the only option we have is drone - so the only option we have is drone - so the only option we have is true once I come to four I will check and I will ask for and he will tell that hey I cannot live with two so to have room number one so the only option we have is from Chios and after sending these rooms I can simply check whether the person who'll dislike each other are in different room or not so I can check for one two and three so room of one is zero and rule of two and three is one so okay we come to two we check for room of 2 is 1 and for room of 1 and 4 is 0 okay we come to 3 room of 3 is 1 and room of 1 is 0 so ok room of 4 is 0 and room of 2 is 1 so in this way we from these two rooms and we have sent 1 and 4 2 1 0 & 1 & 3 to room 1 and we are able 2 1 0 & 1 & 3 to room 1 and we are able 2 1 0 & 1 & 3 to room 1 and we are able to form these groups so we will return true so how we can perform this so what I can do first of all I need to ask every single person and I need to check for their assigned values so I will take state so that I can ask one person and then I can ask for its value and then I ask for those and every time I will ask one and I will pop it from the stake and then because we are also checking whether the values of whether 2 & 3 of whether the values of whether 2 & 3 of whether the values of whether 2 & 3 of the person who do not like each other or like each other in the same of the different room or node so we will also megha dictionary which is seen in which either I will assign room 0 or either I will assign one and we will perform these tasks using stack and say so what I will going to do I'm going to add one to my same dictionary one and I will assign room which is 0 and I will same room 0 to 1 okay then I added 1 to my stake now we'll check for value of 1 in that dictionary or you can say I will ask 1 and I will get the person whom he does not like and one does not like 2 and 3 so I popped one and I ask whom do you don't like he said I don't like to entry and I will check whether 1 & 2 has the same room or check whether 1 & 2 has the same room or check whether 1 & 2 has the same room or not if they are the same room that means they are unable to form any group in which people who like each other lives so ok till the time we don't have a room for two so we added to our scene and we need to make sure that I assigned to a different room than 0 that means I have to assign him room number 1 and if derived value 1 then I have to assign it 0 and when we have to assign these values children 1 whenever we have to assign a opposite value the easiest ways I will take the value of 1 which is 0 I will add 1 and I will take modulus of 2 so one model of 2 is 1 so at sent value 1 and suppose if it has been 1 so I have taken 1 I have added 1 to that I had taken the modulus 2 is 0 then I wasn't 0 so we can use this formula cosine values so all right let me raise this so I assigned room number one to two and I have added and I've added two to my stake then I come to 3 again 1 & 3 should not be in the to 3 again 1 & 3 should not be in the to 3 again 1 & 3 should not be in the same room so I did three and I will assign a different room than 0 and down the option we have is 1 and how I got one using this and then I added 3 - one using this and then I added 3 - one using this and then I added 3 - mistake ok then I will poke and I will get 3 now I will check for the person 3 does not like and that is 1 and now I need to check whether 3 and work are in the different room or not if they are not in the different room and I will consider it in 4th and 3 and 1 are in the different room so ok we move ahead I poked and I go to now check for person - doesn't look like and the persons are - doesn't look like and the persons are - doesn't look like and the persons are 1 & 4 so I will check for the room of 1 & 4 so I will check for the room of 1 & 4 so I will check for the room of two and one out in different room then ok I'll move ahead and I have already covered one so I don't have to add it to my spec I will only add something to mistake which I earned covered or which is not in the scene so I come to 4 and I don't have 4 in the scene that means I will also add 4 to mistake and I will also add 4 to my scene dictionary so now I need to assign for our own in which we don't have 2 and 2 is in room 1 so I will assign a different value then one option we have is 0 and I am using this ok now I will pop now I will pour 4 & 4 does not like pop now I will pour 4 & 4 does not like pop now I will pour 4 & 4 does not like - then I will compare 4 does not like - then I will compare 4 does not like - then I will compare the values of 4 & 2 in the scene or you the values of 4 & 2 in the scene or you the values of 4 & 2 in the scene or you can the room of four and two in the scene and foreign to have the different room okay so we Accord all four persons and has checked and among all four who does not like each other are in different rooms so at the end I will simply return true so this is the way I can solve this question so what I have to do first of all I will make up dictionary or you can make a list in which I know who does not like home then I will come to every single person one by one and as I only two options you run one I will assign I will try to assign different room to person and if assigning suppose after sending Geron when I go to time when two and three does not like each other and one and three also does not like each other that means I don't have room number two percent to three because I have already covered zero and one and three and two and three does not like each other and if I come to this point then I will return false because as I told we only have just two options from number one and two and we have a person who does not like one in two that means we will return false because there is no way I can fit three in any of the room there was three also disliked one and three altered is like two so this is the way we can solve this question so let's move to the coding part and let's see what is the code for this problem at line number ten I made a dictionary which is storing the person and the person he does not like at line number 22 how made a dictionary seen and I'm taking a loop and if I start insane then am assigning rule number zero or you can say initial LD 0 to I in the scene and I'm adding I to my stack and then while mistake is not empty and I'm popping each element once then I'm checking their values in the upper dictionary then I'm taking a for loop in the values of a and if B isn't seen and if they have the same rule that means they hate each other and they're in the same room we will simply written false else if B is not in the scene then we will going to add B to the scene and I will assign the value opposite to be and I will append it to stack and then again I will pop it back and in the same way we'll keep going on and at the end if I pass through all these steps I will simply return true so this was the code let's check whether it works or not so here I submitted my code and it got accepted so this was the solution for this problem if this video was helpful to you please give it a thumbs up thank you so much guys for watching the video please don't forget to subscribe | 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,470 | hi guys today we are going to do the Western shuffle the array given the added norms consisting of n elements in the form X 1 X 2 xn y 1 y 2 y n return the array in the form x 1 y 1 x 2 y 2 up till xn YN so basically let's take this example where we are given an array of two five one three four seven right so we are given that it is a 2 into n sized adding and we are provided with the value of n so we need to do it what we need to do is we need to construct the resultant array where we have the we have a combination such that we have this first digit and the n plus 1 is digit so we have four then three in the resultant vector we have the answer like the I 8 character followed by the n plus oneth character then we have digits 5 followed by n plus I that is n s 3 plus 1 initially I is 0 then it is 1 then I is 2 so initially we what we did is 3 plus 0 so it was here somewhere right so we needed to form a 3 then what we added is I get character that is 5 then we add n + i8 character that is 3 plus 1 so we n + i8 character that is 3 plus 1 so we n + i8 character that is 3 plus 1 so we have 4 then we increment the value of I that is 2 so we will add force the is character that is 1 followed by n plus is character that is 7 so this is the result and adding that we have so this is a very simple question let's code it so what we need is a vector of eight will name it as answer right so what will be the size initially let's not give any size fine then what good an idealist 0 is less than 10 I plus worse since we just have to I tread half of the Aaron Tara can find so we are either adding up to n and then what we do is answer dot pushback first we insert the i8 character then n plus is character right so I push numbs of I and then what I push this I take a pointer J in J is equal to n find I point initially I'll point J to the NH character and then I will insert the gate character and then what I'll do is increment J every time so this is the resultant array and then we will return it from the function so let's run the board so we bought a correct answer on submitting what we get is we get a quite efficient solution so this was a order of n solution that we discussed I hope you guys have understood it gives a thumbs up bye | Shuffle the Array | tweet-counts-per-frequency | Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3` | null | Hash Table,Binary Search,Design,Sorting,Ordered Set | Medium | null |
442 | hey everybody this is larry this is day six i think it's a little bit weird because actually it's october 5th where i am but uh i guess today is day six of the leeco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom let me know how everyone's doing i was actually watching the yankee game and i kind of missed a bit of they're not doing so well right now hopefully they'll come back give me good luck uh wish or wish the team good luck they should take my good luck maybe anyway today's problem is find all duplicates in an array given uh and numbs of length and where all the individual numbers are in one of them when each and every one of the traces return where that appears twice um okay i mean of course it is you only want uh i think well one is uh um it should be obvious that it should use only constant extra space because if it's linear space this is just a dumb i mean well you know like it's just like a for loop right which there are problems like that on lead code but i guess this is not one of them the other thing that i've am curious about is um the thing that i am curious as well about is whether um you can use nums itself because i know that tech like if you manipulate nums that's not a great thing i don't know if that's a possible solution as well because that'll be a little bit awkward otherwise let's see length is equal to length of nums um and also the other awkward thing is of course the output size can be over n right it could be n over two exactly so that's also a very awkward thing um because by definition that uses of uh space but and it's not you know but uh but in the spirit of trying to minimize extra memory uh we'll do it but uh but i think the phrasing it has to be really precise and it was not here anyway um yeah i don't think there's anything um i mean the implementation may be a little bit trickier um the thing that i would look up is something called uh permutation cycle uh in case you want to do it at home i'm usually solving this live some days i explain it in more detail some days i don't and some days i just don't know them the way the good way to explain the solution but i will give you some reference on how to kind of look it up um because there because this particular one is a i wouldn't say it's mathy in that sense but there is a lot of good background that um a lot of good background math that you can play around with and learn with respect to permutation cycle but the idea is just okay uh you know we swap things so that things are where they should be i think it's kind of what um uh what i would say and of course in this case we are going to use in place uh we're going to manipulate nums which the one could you ask uh if you ask me that's not a really a good answer because if i talk about this a lot about api design but um api design is just really uh like you know you basically try to design something that has the least surprise as possible right the principle of lisa price and my question is if i give a function find duplicates i give them a list of an array and suddenly my array is memory is all jumbled i would probably be pretty surprised so in that case you know that's basically the idea there um but anyway ignoring that apart the idea here is just going to be to okay for example we go from left to right we see a 4 then we should swap it with the 7 to make sure that four is in the right place and then in that world then only one integer will be at each slot unless it appears twice then you can kind of you know go for it that way um i don't know if i'm explaining that quite well we can you know start by going into code but the idea is that okay you move to four to the slide four you move the seven to the slot seven um the three you move to slide three and then later on you see this twin you're like oh there's already a 3 in slot 3 so that means that this 3 is an extra that's basically the idea and of course this is going from 1 to n so you have to do some one indexing things or whatever you want to call it but that's basically the idea um i think that's all i have with respect to explanation about this but um i don't know yeah i mean i think let's get started let's get let's start playing with this problem then right so now we just go okay um yeah left is he did he go to zero um maybe we could just go we have four start in range of n so this is our starting index um so yeah so current is equal to start while num sub current or some way okay this is the index or the well the first the number in the first index is not equal to current we do something like okay now what well let's swap let's make the number in the current in current right so yeah so num sub uh num sub current we swap it with this i think uh and eventually this should be good i think maybe i'm wrong on this one let me think about this so basically you swap and then now oh this should be okay but i have to update current so then okay so what happens so let's say we have oh and also left some off by one things so let's play around with that but okay let's just walk through this example right so let's say we have here that's how i do it sometimes i don't i mean historically i actually do it on paper just like right out the examples and kind of go through it um but obviously i want to visualize it for you viewers at home so that's why i'm kind of thinking about it a little bit so yeah let's see is this zero so this is looking forward um let me think how i actually want to do this uh i'm going to be a little bit lazy because i don't want to think about these indexes and stuff like that so i'm just going to subtract everything by um uh one right and technically this actually constructs a new list but i mean we're in the spirit of things you could just i mean this is a line one liner you could have just write for i in range of n uh num sub i uh maybe that's a little bit whatever i mean it doesn't really matter anyway like we're just playing around with the problem here the ideal um yeah these things are kind of like you know you just try to think about what you wanted to do and what you want to practice and what you want to learn um for me i hand wave it and i say it doesn't matter um in an interview it actually might matter to be frank but for me like these are trivial fixes ish and i'm recognizing them but you know i'm just kind of saying it like that anyway yeah so here now we effectively convert these to uh turn away that's smaller so three now what does that mean right so current is zero so while this isn't zero we swap this with three so six um okay so in this case um there can be an infinite loop in the sense that um zero might not be in here right let's replace it with four then this may you know this goes to the six goes to uh what is it one two three four five six goes to the two and then the two goes to the one and then now the one goes to the two and then here we find the first um thing i'm trying to think a little bit does that mean the zero doesn't exist i guess that's not the case maybe i'm writing this a little bit awkwardly yeah i don't like the way that i'm writing this actually um because i think this one has the way that i'm writing it has more edge cases so now i'm just trying to think about um now i'm just trying to think about what is the right way of doing it right so then here i think we should just follow the current to num subcurrent uh or maybe yeah right so then now for example we had uh three two one six seven one two zero um then now we swap the three of the six oops swapped this three to six um but then now of course we have to follow this along so actually what we want is next is equal to right um and of course like i said there will be an addition wait that doesn't this doesn't make sense either because that means that three is in the right place right okay um actually you know what maybe that's fine maybe what i had before was fine actually uh we just find the we just keep on swapping until we find a dupe but is that uh hmm i have the idea but i now have to think about how to do it quite correctly i think there are a lot of like edge cases and stuff like this um hmm in a second well you know you are watching it live so if you feel like it feel free to kind of fast forward a little bit um okay but yeah uh so now we switch to three okay and now what do we do okay because basically here we want we do it to six but then now what happens if we have a two one two type thing right for example okay let's just say we have something like this uh where okay but someone i forgot what it was something like that all right i don't know and then now what happens when we keep going okay the one it doesn't do anything the two doesn't do anything the three is in the right place the four uh we move to seven so now this is oops this is zero this is seven and then now we put but then now we put the zero and then we swap the two but we already did the two right so that's going to be awkward because we should not and do it again right maybe this is fine actually maybe we just don't add until the very end and then six is this on six now just because then now in the in essence this all this does is sorting it and then now we can just go through all the numbers that don't have it okay maybe i'm happy with that um and then what are the ending conditions up here so obviously this would be an end condition but also the other one is if so we keep going until this is the case or one more thing right which is that um if num sub kern is you go to num sub i guess this should be okay i'm just gonna run it real quick um so we should either get a infinite loop oil and if it ends then i'm okay with that okay and then now we can print out the answer maybe i should have just added that didn't take no effort um okay the printing is not good because we print the answer what we wanted to do is actually print the numbers away because here now everything should be sorted except for the things that are out of um of order right um so yeah so as we expected so now we have the two and the one so then that should be good i mean of course we have to add back one but that's fine so now we do for i in range of n if num sub i is not i and start a pen i push one and then we just return enter right oh hmm really did that miss read something let's take a look again uh zero one two three numbers of i is not equal to i yeah oh well i'm returning the index not num sub i whoops okay so we are maybe still okay in concept i think the harder part is going to be to show that this is linear now look i've done this a year ago which i will show in a second if this goes look another one day streak um a little bit slower this time with it i'm just curious what did i do a year ago i don't remember this problem i just remember the concept uh i don't really and in general i don't really remember problems unless i'm learning something from it but um okay wow i did it some other way i think i mean i did it the same way but in a different concept maybe um no i think we mostly did the same with different code but yeah so okay so the hard part is kind of thinking about how many operations does take away how do you analyze the complexity well in this case let's just skip this because this is of n and this is all technically like i said of n space but um but what but um this is all event space but all one extra space because this is i don't depend on how you want to say extra but um because you know we only have variables things um and of course we can also do another folder to fix the input if you like but we already messed up the input anyway i don't know you do the math here but yeah but the so the way that i would think about how to analyze this complexity the naive thing to say is that this is an open loop this can go off and time so this is n squared time right but that's not the case because this is i don't know what n is 10 to the fifth so if it's n squared you're gonna get time limit exceeded anyway so the reason why this is n is you can think about each number that's in this array right in a way we're kind of like sorting it's not really a sword per se but you can look at every element in this array and ask yourself what's the most number of swaps that you can get right well every swap um every swap means that one number is put into the right place right and if that's the case that means that there will be at most n swaps meaning that there will be n swaps or n minus one swap sorry off by one uh n minus one swaps if every number would appear once and you swap them into the good price right um because every like the invariant is that every swap means that one number is in the correct place so that means that you have n minus one swap at most and because you have n minus one swap at most uh that means that this is going to be at most all end times um together combined amortized whatever however you want to say it so the sum of all the individual swaps it's going to be of n so that means that this is only going to happen over n times and that means that the total amount of complexity is going to be all of n um yeah and of course all one space we already talked about it earlier so i'm not going to go over that deeply again but yeah that's all i have for this one let me know what you think uh hit the like button hit the subscribe button join me on discord and wish me and my yankees good luck anyway i'll see you later stay good stay healthy to good mental health i'll see you later bye | Find All Duplicates in an Array | find-all-duplicates-in-an-array | Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
**Input:** nums = \[4,3,2,7,8,2,3,1\]
**Output:** \[2,3\]
**Example 2:**
**Input:** nums = \[1,1,2\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= n`
* Each element in `nums` appears **once** or **twice**. | null | Array,Hash Table | Medium | 448 |
839 | Question from video number 23 of Hello Gas Welcome Tu Me channel, we have made it in video number 22, but using BFS and DFS, we will make it with DSO, okay, it will be quite easy, we will understand it with DSC also, then what is the requested, those with graph concept. The playlist is DSO, read it, after that this question will become very easy. Okay, so let's start with the union. Before that, you should know that there will be a question of how to know. This is okay, so if we have read the question then we will remember it in the question. Grouping of people was taking place, isn't it? Zero index, one index and 2 index. They were dividing them into groups. He was studying in the group and earlier when I have studied B.Sc., and earlier when I have studied B.Sc., and earlier when I have studied B.Sc., I had said that whenever there are questions with such grouping, isn't it? A group is being formed, either you can say different components, then the concept of DSO comes in it, then this question means that it can be formed, OK, now let's see how it is done in desi, in the beginning, they used to do this because of their mother. All the people are fine in different groups. All the people are fine in all the different groups. Now let's start from here. Okay, first I want to see this RS which has come, then I came to know that it is similar to this one, okay. Right now I am standing on I and I am seeing all the elements after I. As soon as I came to know that I and K are similar, then what must have come in my mother's mind that both should belong to the group. So first of all I will ask I who is your parent I means zero index then zero will say that I am my parent because I have only one group like ask i.e. I will ask one who is your parent, i.e. I will ask one who is your parent, i.e. I will ask one who is your parent, it will say that I am also a different group. I am my parent, I am myself, so now its parent zero is representing different groups but what happened in both the simulators that we have to merge both of them, so what we did was we added both of them and took P as its parent. It is not clear even here, okay, so we have captured all the similar elements, now let's take Ai Maa here, okay, so let's see all the elements from Ai onwards, which ones are similar to it, then 800 rates are both similar. Okay, so similar, first ask Aai who is your parent, then Aai will say one, this one is part of this group, zero is part of this group, okay, zero and who are your parents, that is you, both of them are not equal, that is, they are definitely different. In a different group but if it is similar then it will have to be put in the group i.e. what will I do by i.e. what will I do by i.e. what will I do by picking it up here and putting you here too, okay now when you ask me who are your parents then you will be like oil bill. My parent is zero because now you have come to this group, okay there is no Simran here, okay, now I have gone ahead, okay, everything is over, everything is fine, just like that I came to know that I have only two groups, that is back. Went and this one went back, okay 123 How much group account did I have in the beginning, as I came to know who will be in a group, after that if you also join their group, then the group should be added again. After that, if no one joined the group, then look, the value of the group will be my answer. Otherwise, I will go to the value of the group in the beginning. Okay, so its code will also be very simple, so how will be its story point? Read playlist in desi. Take it only then it will be clear. Okay, United, what will happen, understand, okay, I will trade first if similar which is STRSI which is string. If both of them are similar then what will mean that I will have to merge these two. Mines. I understand that the story will be fine and here we will keep decreasing as much as the unions are doing and in the last what will we do in the return group account Go to the graph area, I have made a separate report in the graph, I have made a sub director. In which what I will do is that there are only two things in find and distance, there is union and find, so I just copy and paste the complete union fine here and put the complete code here, see, now you do not have to do anything. You can do it directly but I am repeating, you had to write it yourself when your revision is done, we have written the final union and if it is a science rank, we will have to initialize it, okay then resize the parent dot [ then resize the parent dot [ then resize the parent dot starting. Everyone's rank in me is zero Those who are alone in the beginning, it is okay, just keep one thing, we have solved it will be of function, so I pick the same and put it here, okay, I never increase, copy pasting, but just you, your time. From here I am picking up the official solution of IT WOULD BE GOOD IF YOU ARE RIGHT AND IF YOU DO IT WOULD BE GOOD. | Similar String Groups | short-encoding-of-words | Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal.
For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "` is not similar to `"tars "`, `"rats "`, or `"arts "`.
Together, these form two connected groups by similarity: `{ "tars ", "rats ", "arts "}` and `{ "star "}`. Notice that `"tars "` and `"arts "` are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.
We are given a list `strs` of strings where every string in `strs` is an anagram of every other string in `strs`. How many groups are there?
**Example 1:**
**Input:** strs = \[ "tars ", "rats ", "arts ", "star "\]
**Output:** 2
**Example 2:**
**Input:** strs = \[ "omv ", "ovm "\]
**Output:** 1
**Constraints:**
* `1 <= strs.length <= 300`
* `1 <= strs[i].length <= 300`
* `strs[i]` consists of lowercase letters only.
* All words in `strs` have the same length and are anagrams of each other. | null | Array,Hash Table,String,Trie | Medium | null |
72 | edit dividends one of the most classical problems when it comes to dynamic programming and surely this problem is asked almost everywhere in one form or the other so by solving this problem I will also focus on how can you come up with a solution like what should be a thought process so that when you encounter similar problems you already know what to do Hello friends welcome back to my Channel first I will explain the problem statement and we'll look at some comparative cases going forward we are gonna see briefly what two operations actually mean when it comes to this problem after that you're gonna come up with an efficient efficiently problem step by step and then we will also do a dry run of the code so that you can understand and visualize how all of this is actually working in action that way you will never forget it without further Ado let's get started let's make sure that we understand the problem statement correctly in this problem you are given two strings and you have to return the minimum number of operations that are required to convert string 1 into string two that means you have this first string horse and you have to apply the minimum number of operations to convert the string to the other string Ros correct so for a first test is how can you go about performing these operations for the first operation you can remove the character R and then you will get the string hose for the next operation you replace H with r and then you get r o s e and finally you will remove e and then you get your final string Ros right so for the first test case you did a total of three operations right and three will be your answer you cannot achieve this scenario in less than three operations so three if the edit distance correct similarly let us look at our second test case and this is special because you have repeating characters right you can see that n is repeated twice and similarly T is repeated twice so an important thing to note over here is that when you do an operation you will only operate on only one character so if I say that my first operation is remove t then you are only removing one of the teeth that is your choice which one to remove so for my first operation I will remove the first T right and when I do it I get my string as i n e n t i o n correct now similarly we will perform another set of operations to arrive at our final string we replace the first I with E and this is our new string moving on I replace the first n with X and I get my new string like this similarly I replace the first n with the character C and I get my new string and finally I will insert U somewhere in the middle and I get my final string that is execution correct so I took a total of five steps and this will be your answer now you can try several different other ways but you cannot achieve this transformation in less than five steps so 5 is the edit distance for these two strings correct now this is the major Crux of the problem that you have to identify the minimum number of operations but I want to talk a little bit about what do these operations actually mean basically you have three different operations possible that is insertion deletion and substitution so for example if I have this string with me then how can I insert characters when you say inferred that means you are inserting at any one position and you are inserting only one character for example you can say that I want to insert X at the third position so when you do this your string will eventually become and this constitute Institutes of one operation the next available operation is deletion that when you're deleting character one operation means you are deleting just one character for example if I say that delete T then you cannot get rid of both of theft you can only delete one of these keys you are deleting the first T and eventually your string will become if you now want to delete this second t as well this will take up one more operation so just keep this in mind act similar is the case with the next operation that is substitution you can only substitute one character at a time so in this particular example if you say that you want to substitute I with the character C then you have to specify which I you have to substitute you cannot substitute both of these I's at the same time so now if you feel that you have understood the problem statement even better and understand what do operations actually mean feel free to stop this video and try the problem once again on your own otherwise let us dive into the solution to start forming a solution let us take up two sample strings A B C D E F and a z vde correct now if you try to come up with a Brute Force solution you will quickly see that it is not optimal how can you go about performing a Brute Force approach what you can do is you can start with the first character in both the strings see that they are same so now move ahead you will go on to the second character and that is B and that is z right they are different so you perform one of the three operations substitution insertion or deletion you will try to substitute one of the characters and let's say I substitute this with B now you have two new strings so once again you will take these two strings and recursively pass into your function while maintaining the operations that you did one operation once again you will start from the beginning and then go over each character and try to determine if they are same or they are different so you can easily see that this is a recursive solution and it will end up taking a lot of time so certainly this is not optimal there has to be an efficient way possible but at the same time while performing this method you can certainly come to one conclusion and that is that if you have already solved for a certain segment of the string then you need not fall for it again and again for example if I had the strings like these and somehow you have determined that the edit distance for these two strings is three now if I expand these two strings let's say I add an X over here and I add a y over here correct then you need not calculate the entire solution once again you already know that the edit distance up to this length is 3 and you only need a solution for the remaining characters right so you just need to replace an X with Y that means one more operation and then your answer will be 4. so this tells you that it is an Optimus substructure property and hence you can apply dynamic programming to this question so let us take up our example once again and try to think step by step what we can do about it for our example test case we have these two strings right you have to convert this first string to the second string and you also know that you have to reuse your results so you need some kind of a structure to store all of them I will take help of this two dimensional Matrix that is representing the number of operations I require to convert one string to the other one so in this Matrix for example I have this cell will store the number of operations I need to convert the string ABC into string a similarly this cell will store the number of operations required to convert the string a b c d e to string azc right so the last cell this cell will store the answer how many operations do you need to convert this string a b c d e f to the string a z c d e and we will go step by step and then see how we can populate this Matrix so let us look at this first cell this means that both of my strings are currently empty how many operations do you need you don't need any operations right so you simply write down a 0 over here look at the next cell this next cell is telling me that the first string is a and the second string is again empty how many operations do you need just one delete operation and you will reach your second string so I took one operation for this next cell my first string is a b and the second string is an empty string how many operations do I need to delete operations similarly I will populate all of these remaining values now we will populate our first column what is this cell telling you this cell is telling me that my first string is an empty string and the second string is just the character a how can you go from the first string to second string you will just add one character right so I need one operation looking at a next cell my first string is empty and the second string is a z how many operations do you need two insert operations so I can write down two over here similarly I will write 3 and then 4 and then a 5. so this is how we initialize our Matrix you can see that at every instance for example I have this cell is telling me the number of operations I need to convert an empty string to the string a z c correct just keep this in mind and this will be the base of how we're gonna populate our entire Matrix just go step by step and follow it patiently and you will never forget it so now let us look at our next cell that we have to populate what does this will tell you this cell is telling me the number of operations I need to convert the string a to the string a both of these strings are same right so how many operations you will need you won't need any operations so you can write down a 0 over here right look at this next cell now the first string is a b and the second string is a how many operations do you need over here you just need one operation and that will be to delete the B so you cannot write down one over here similarly for this next cell my first string is ABC and the second string is again a so I'm gonna write down 2 over here that means two delete operations similarly I will have a 3 4 and then a 5. what is the next fill that you have to populate this cell and the test case for this cell will be the first string is a and the second string is Av how many operations do you need you just need one insert operation where you are inserting a z so you can write down one over here up till now you either had a empty string or just one character in one of the strings so all of these cases were fairly simple now comes the interesting part when you have to populate the rest of this Matrix right because try to think for this particular cell you have to find the minimum of operation for string a b c d and the string a is at C so how do you find it out let us look at this cell now for this particular cell what will be its answer the test case over here is that the first string is a b and the second string is AC to determine the minimum number of operations you need to think how can you reach the scenario you can reach this scenario if you move one step down from here if you move one step forward from here or if you move one step diagonal from air right and you have already calculated all of these three values correct for example what is this value telling you this value is telling you that the first string was a b and to convert it to string a you needed one operation right and where do you have to go to this scenario right where the first string is a b and the second string is Av how can you go over there just by adding one more insertion operation and that is z so if you choose to come from this particular location then you will need two operations right so you know that in at least two operations you can come from string a b to string AC right but there are several other candidates as well let us look at this scenario now for this particular scenario the first string was a and the second string was a z so you know that to convert string a to string a z how many operations do you need one operation right and now you want the first string to be a b so once again if you add one more operation to invert the character B you will arrive at your answer so once again with two possible operations you know that you can achieve this right there is one more scenario that we can look at and what if this scenario telling you this scenario is telling you that when both the strings were a you don't need any number of operations right and now where do you have to go over here right where the first string is a b and the second string is Av and how can you achieve it you can substitute any character with the letter V right so you just need one more operation think like this if I have any character over here let's say I have an a edge How can I convert it to AV I will just replace this edge with the letter z four what you need to do is just look at all of these three values find the minimum and just add 1 to it because you need the minimum number of operations possible to arrive at your second string out of all these three values 0 is the minimum and then you add 1 to it so I'm gonna write down one over here this one is simply telling me that if the first string is a b and the second string is AC I need just one operation to arrive at my answer similarly let us look at this next cell now for this next cell I have the first string as ABC and the second string is Av and how can I arrive over here I need the minimum number of operations so look at all of the values that we have already calculated check out all of these three scenarios from each of these three scenarios you have to reach your final scenario right and you have already calculated the minimum number of operations for our previous scenarios correct so if you have to reach the scenario from the top then you need one more operation and this will end up taking three operations correct if you want to go from left to right then you need one more operation and that is a total of two operations and if you move diagonally you know that you have already solved for this you just needed one operation over here right and to substitute a c with a V that is one more operation so once again you will need two operations so what do you pick the minimum of these three values and just add a 1 to it the minimum value is 1 so I'm gonna do one plus one and that is 2. so this is how you are gonna keep populating your Matrix look at this next cell now find the minimum value that is 2 and just add a 1 to it for the next cell also find the minimum value out of all of these three minimum is 3 and just add a 1 to it once again the minimum value out of all of these is 4 just add a 1 to it and that is 5. so once again at every instance this Matrix is telling you that for example if the first string is a b c d e and the second string is a z you need a total of four operations to go from the first string to the second string right now keep moving ahead look at this cell now what is the minimum of all of these three values the minimum is 1 right so just add one to it and then you're gonna populate 2 over here correct for the next cell the minimum value is one again just add a 1 and write down two over here now comes the interesting part look at this cell now for this cell you are adding the same character that is C right and if the character is same you don't have to perform any operations right so you will try to look back what have I already solved I have already solved for this scenario right and this value of already one so what I can do is I can simply copy this value down and I will write up one so this is a special scenario when both of these characters are same try to think about it for this particular cell what is the test case the first string is ABC and the second string is a z c and what is the test case for this particular cell the first string is a b and the second string is a z for this particular test case you have already found out that you just need one operation right and if you're now adding a new character and that is same so effectively your problem simply reduces to this right and it is same as this scenario so you can simply write down whatever value you found over here and that is why we write down one over here now move ahead to the next cell C and D are different so just find out the minimum value that is 1 and add a 1 to it so I get 2. once again e and C are different the minimum value is 2 add a 1 to it and write down 3. for the next cell F and C are different the minimum value is 3 add a 1 to it and write down 4. moving ahead to our next cell d and a are different the minimum value is 2 add a 1 and write 3. B and D are different 2 is the minimum value add a 1 and write down 3. C and D are different the minimum value is 1 so add 1 and write down two now once again both of these D's are same right so look at the vertically opposite value and this is one so simply copy it and I'm gonna write down one over here for the next cell e and D are different minimum value is 1 so add a 1 and write down two F and D are different get the minimum value that is 2 add a 1 and you can write down 3 over here similarly Jeff populate this last row as an exercise on your own so you see now my Matrix is completely populated and if I look at this last value this is telling me that this is the minimum number of operations if my first string is a b c d e f and the second string is a z c d e so for this particular test case 2 will be your answer so you see how we were able to use dynamic programming and memorization to user previously calculated results and then use them in our future test cases and this is the main idea how problems on dynamic programming actually work now let us quickly do a dry run of the code and see how it works in action on the left side of your screen you have the actual code to implement the solution and on the right I have my test strings that are passed in as a input parameter to the function Min distance oh and by the way this complete code and this test cases are also available on my GitHub profile you can find the link in the description below moving on with the dry run what is the first thing that we do first of all we find what is the length of both the birds because that is how we have to create our Matrix right so now we will create a matrix that has one extra character accounting for the empty string so this creates my Matrix where I will be storing my final answer going forward we initialize a matrix and to initialize we only consider all of the blank values for now I have my basic setup ready for this next for Loop this simply iterate over each of these cells in The Matrix and we are going to compare each of these characters if these characters are same we copy this same value over here and if these characters are different we check all of these three values get the minimum one and then add a 1 to it once again if these values are different just check the minimum one out of all of these and add a 1 to it so this is how you are gonna keep moving ahead in your entire Matrix and ultimately this last cell this will have your answer and this is ultimately returned over here if you want to check out the code this is where we check if the characters are same then just copy from the top left location and if we are not the same just get all of the three Neighbors find the minimum and then add up one to it the time complexity of this solution is order of M cross n where M and N are the length of the two strings and the space complexity of this solution is also order of M cross n because you need a matrix of M cross n size to have all of your memorization answers I'm able to simplify the problem and its solution for you as for my final thoughts I just want to say that whenever you see problems like these that are asked so many places and are so popular try to think the reason behind it the main reason is that these problems have very practical applications let us say you have n number of strings and I ask you that okay which strings are the most similar now think about it this is a very practical application right and how do you find it yes edit distance is the answer so out of a bunch of strings the strings which have a minimum edit distance those two strings will be very similar right at a difference of 0 means the strings are actually equal correct so while trying to solve these kind of problems just keep your mind open and keep on thinking that hey where can I actually use these problems right and while going through this video did you face any problems or have you seen any other such problems which are very popular and have a very good practical application they all of it in the comment section below and it will be helpful for anyone else also who is watching this video as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what are the dynamic programming problems do you want me to solve until then see ya | Edit Distance | edit-distance | Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters. | null | String,Dynamic Programming | Hard | 161,583,712,1105,2311 |
426 | hello welcome back to my channel i'm here to do my 100 lego challenge today we have leeco 426 convert binary search tree to sword doubling list and here's the description and you can take a moment to take a look at that but in summary uh you can take a look at this example so now this is the binary search tree and we invert this one to uh double linked list looks like this and it's in sorted order so what is binary search tree so binary search fee is when you see this node and everything on the left side is smaller than the middle note and the right side is bigger than a middle note so you can see here two is bigger than two smaller than three and everything on the left side is smaller than four so five dip is bigger than four the order in here is always go to left side and then go to middle and then go to right side so now the left side is done and go back to the middle note which is four and go to right side and 5 then that's the order of the binary surgery so in here is the node we have a hat it's a one of the hint that we're gonna use we will start with using the hat and also a previous number pointing to the head and we will have a helper function uh that connect uh go all the way to the left side first and receive one is the one that we're gonna process and we connect it to the previous number and after connect and previous number will be one we update it and then we go to the middle and connect to the previous one which is one and after that connection we update this one to become periods and we do the same thing on the right side so we always updated the previous number until we get to the last node so let's take a look at that code first and up to here so we will need a node called periods equal to uh no we just have it for node first and we'll keep track if root is no then return no so now we have this one so we have to create a hat called hat equal to new note and that take in the 0 and left and right will be no so we have this and we have previous equal to had now periods is this note right now we keep we use hat to make a pointer and we're gonna use it at the end of the question so we just update previous as a pointer so previous pointing to the hat and what we can do is use a helper function and process the root because we are going to loop through this root and get to the left point pointer the most left pointer and then go to the in order traversal for this node and we have something later so let's take a look at the helper function we have a helper function that take in a node called node also we check if nodes equal to um no then we don't do anything that we turn and like what we said when we see a note we go to left side first and go back to middle and right side so that order will be helper function will go to nodes.lab and then helper function node.right and then helper function node.right and then helper function node.right at the end in the middle we're gonna connect the periods node with the current node and then update the previous node so what it does is the previous no dot right equal to no and no dot lab equal to periods so then they connected so after they connected then we can update the periods equal to no so this is what the helper function is doing so after the helper function so up to here we can draw the map like this now we have a hat and what we do is make a zero the hat will look like this and also the periods right here i make a head here and p is called periods note so the half left no and right now so if we keep traversal the left we'll go to sorry four and four it's not no and we go to do force left first and fourth i mean now is two we do one go to one left which is no and it will return after the return then we start to the middle one which is one when is one we have connected one to the previous note here so in here the periods no right side will point to one and then one will point it back to periods number and then after that we update the periods to become one now one is period and then after one is process go to right side have nothing then left sides got finished so when lab size finish we go to middle which is two and now we see periods is two we connected to two back to one and we updated so i just run through this code with you and we go to the right side which is here and it looks like this it will keep connecting and we're back to middle four point is three and then after everything is done we go to the right side we have five and point it back to four but we're missing one thing just because in five we only have left side but it doesn't have right side right you can see you need to connect five right side to one that's one thing and then one is connected to the wrong left side it should connect one two five once left supposed to be five so this zero is just a template that we're gonna change so what can we do now so now we have all this connected with the hat right here let's go back to the code okay now i can type so now we know hat is connected like this in this order we can see if periods which is pointing to 5 right now dot right is equal to hat dot right now you see hat is 0 right hat stop right is one so we connected five periods to had dot rights one so now we connected i can draw again so now we connect to here that looks good but we need to connect one back to five after this we will have head dot write dot left equal to periods so you can see hat dot right is one dot left is periods then you connect it one to five so i'm not going to draw it from here so what we can do is almost done it's return head dot right which is one right here let's take a look at this and cool this is one of the test case and let's submit it cool and then it beats 100 yeah this is this question and i hopefully is clean up so if you still have questions please comment below and i will see you in the next video bye | Convert Binary Search Tree to Sorted Doubly Linked List | convert-binary-search-tree-to-sorted-doubly-linked-list | Convert a **Binary Search Tree** to a sorted **Circular Doubly-Linked List** in place.
You can think of the left and right pointers as synonymous to the predecessor and successor pointers in a doubly-linked list. For a circular doubly linked list, the predecessor of the first element is the last element, and the successor of the last element is the first element.
We want to do the transformation **in place**. After the transformation, the left pointer of the tree node should point to its predecessor, and the right pointer should point to its successor. You should return the pointer to the smallest element of the linked list.
**Example 1:**
**Input:** root = \[4,2,5,1,3\]
**Output:** \[1,2,3,4,5\]
**Explanation:** The figure below shows the transformed BST. The solid line indicates the successor relationship, while the dashed line means the predecessor relationship.
**Example 2:**
**Input:** root = \[2,1,3\]
**Output:** \[1,2,3\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 2000]`.
* `-1000 <= Node.val <= 1000`
* All the values of the tree are **unique**. | null | null | Medium | null |
895 | Loot Hello Everyone Welcome 28th President Ko Chalu And S Lord Your Honor 4 Inch And Discuss Maximum Screen System In This Question In Two Employment Of Frequency Stock And Subscribe Define More Objective Side Must Subscribe Button Was Clicked Aunty By Removing Element You And Telemedicine Element Most Frequent Servi Subscribe 5745 subscribe and subscribe Free Web Element President Me To The Volume Evening List On Or Induced How Will Keep Element Subscribe subscribe to the Page if you liked The Video then subscribe to the Video then subscribe to subscribe our Channel subscribe for watching this Video plz subscribe A Surplus Stock Stocks On Hai Jiki Besan Mind And Left Side Truth Labs For Lips Dry Push 512 Subscribe To Insert New Stock In To-Do List In Insert New Stock In To-Do List In Insert New Stock In To-Do List In To-Do List On It Well Placid It's To-Do List On It Well Placid It's To-Do List On It Well Placid It's Quite The Amazing Labs Play Free Play List of Quid Souvenir Using Star Investment in The Calling Rock Band Element subscribe to the Page if you liked The Video then subscribe to The Amazing Link Pastry Episode 151 Lipstick 2.5 Link Pastry Episode 151 Lipstick 2.5 Link Pastry Episode 151 Lipstick 2.5 subscribe and subscribe this Video not support Elements Which Element Which Will Do Subscribe Blast Element subscribe to subscribe and subscribe the A Pomegranate Will Simply Delete This in More Video Channel and subscribe the Channel Please subscribe and subscribe the Video then subscribe to the Ek Ansh Move Ahead Hydration What treeless next is 500 against acid attacks of class 10th in the list loop 1525 eddy subscribe button middle aged man will return from this will keep on doing this question the entry intersect liquid subscribe The Video then subscribe to the constructed on a content equal to new are left CR during early tampering exploiting the index for the frequency and now comes to push through it will do not for access oil not get or difficult that access oil 0 plus one should be extracted the frequency testing Sequence from deposit 128 and updated box with update from zor subscribe my stock pics that dots in it frequency - 1.2 greater that dots in it frequency - 1.2 greater that dots in it frequency - 1.2 greater than or equal to start size ghost vr always post tracking and frequent class11 wedding elements do subscribe my new notification on the start of art i Mukesh Lemon Juice Quality Stocks Star Plus Tasty List Institute of SD A's Process Loot Ki Shot Art New Stock News Talk on Generate Ayush Dubey Enter in this App Ki Oil and Elements Want to My P List and a Great Frequency - One Daughter List and a Great Frequency - One Daughter List and a Great Frequency - One Daughter Is Picked Up Elements That This Particular Section Is A To-Do List The Size Particular Section Is A To-Do List The Size Particular Section Is A To-Do List The Size Of The Butt And Stress Se Left Side Is Loot Under Which Element Is Also Removed From Heat STD List Product Size - Vansh Different STD List Product Size - Vansh Different STD List Product Size - Vansh Different Elements Of This Particular Frequency - 121 A Need To Return 10 element from this is the third anil powder elements from that from this point class 10th std list date of birth mein ka gana remove hair from my yellow steps follow strike hai front usi is champion remove this point color entry from the best doctor imo saaf - 121 doctor imo saaf - 121 doctor imo saaf - 121 ki anna file update maf hai a common aap dots ki get and default x and not get x minus one is my frequency in the map get updated tu 08 removed from the ki nadody remove Online Media Trials Of Looks Perfect That Accepted Notice Piece Complexity Of Just Measure And Stock Should Be Contacted Exactly To God Of On The Number Of Element Arvind An Important And What Is The Time Complexity For Both Push And Population Subscribe To | Maximum Frequency Stack | shortest-path-to-get-all-keys | Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the `FreqStack` class:
* `FreqStack()` constructs an empty frequency stack.
* `void push(int val)` pushes an integer `val` onto the top of the stack.
* `int pop()` removes and returns the most frequent element in the stack.
* If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.
**Example 1:**
**Input**
\[ "FreqStack ", "push ", "push ", "push ", "push ", "push ", "push ", "pop ", "pop ", "pop ", "pop "\]
\[\[\], \[5\], \[7\], \[5\], \[7\], \[4\], \[5\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, null, null, null, null, 5, 7, 5, 4\]
**Explanation**
FreqStack freqStack = new FreqStack();
freqStack.push(5); // The stack is \[5\]
freqStack.push(7); // The stack is \[5,7\]
freqStack.push(5); // The stack is \[5,7,5\]
freqStack.push(7); // The stack is \[5,7,5,7\]
freqStack.push(4); // The stack is \[5,7,5,7,4\]
freqStack.push(5); // The stack is \[5,7,5,7,4,5\]
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,5,7,4\].
freqStack.pop(); // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes \[5,7,5,4\].
freqStack.pop(); // return 5, as 5 is the most frequent. The stack becomes \[5,7,4\].
freqStack.pop(); // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes \[5,7\].
**Constraints:**
* `0 <= val <= 109`
* At most `2 * 104` calls will be made to `push` and `pop`.
* It is guaranteed that there will be at least one element in the stack before calling `pop`. | null | Bit Manipulation,Breadth-First Search | Hard | null |
583 | Quiz Welcome To My Video Series Coding Is That Problem Digit Operation For Boosting Subscribe And Subscribe To Our Channel Subscribe Now To Swapn Free To Present Distic Total Pati Is What You Have To Retail Blurred Crush How To Delete To Make The World Is The character of this sunnah in redmi phone where and distance in pills cancel all the value share with all no validity tomorrow morning mist serials nursing meeti common question is anti-aging hai selectors suno is anti-aging hai selectors suno is anti-aging hai selectors suno character candy Comment Similar Phalwan Ke The First Column Ok Alag Aur Rohit Lage The First Time When Everything You Need To Know What Is The Distance Between Both Of You Aisi Bindi Logic People Against Court Of Various Lungi Let's Make Reservation In The Next Time You Have The First Indian To Win Over And Over Again That Builders Ne Examples On Between This Row And Column Submit Under Hi Kam Na Interval Peace Ok How Many Characters You Have In Common Now This Stupid To Record Sit Notice You Can't You Have Different Account Se First Features Having maximum one length reduce angle and someone and second spring is having two is torn account 150 cm only one night sweet dream ₹10 cm only one night sweet dream ₹10 cm only one night sweet dream ₹10 conductors one coin the only one who gives her all will only one is the worst drinks for your body diet. st hai abp news now you have to take up to this ruk next9 news room report subscribe now to the phone i is particular row and column waters in between k n p we have characters behave in common rates you can observe the characters informally character ki And in every year on just look at between both in the valley between them which does not mean that in this year let's go to the next one column water's point to first correspond with the worst thing this and the second JP Duminy We started on characters Comment ok know you rot this interesting things first exam point to the character definitely gayre nathu are you already have common between thandi patti lapat market with different color particular is ka boxing defeated and this particular boxing defeated you who already new between he Crispy How Many Characters All Information You Know The Between Dhyanpeeth Common Cold Even Characters Mix It Is Just And One More Character Tubelight Mukesh OnePlus One Is Equal Two Cash Award Character Already Director China Ko Manhu Not Looking And Defeated By Looking At This Box OK Decrement ₹1 Decrement Box OK Decrement ₹1 Decrement Box OK Decrement ₹1 Decrement OneColumn You Later This Thank You Have Been Combined With One Mode Tractors OnePlus One To Strike Enfield Surya Okay Sorry Villiers Paytm And Example Kwid Four Wheeler Into Consideration For Example You Have Been In Peeth Me Vitamin B2 We Have Character Sir Comment By Food Decide we called the character Mannu See the character Looking at this point in growing Olympia Looping 8 And looking and see the common etc Same day not seam to each other You remove Remove between there pac We called the character OK What do you think you are in love Between there characters and values and ps e love you shubhendu characters common between china and pac we have character common in order to leave a comment for this you can do you can also see are you trying to find us character common between he k n peeth ok between A Jnanpith Ko Hi K N Peeth How To Find The Value 3.2 Million In Noida And Share Common Between Both Value 3.2 Million In Noida And Share Common Between Both Value 3.2 Million In Noida And Share Common Between Both In The Character Common Between Two Examples For The Example Of Hai To Hai Navya Looking At Dainik Toilets For Lips Which Corresponds * The person from the Lips Which Corresponds * The person from the Lips Which Corresponds * The person from the left side it's clipping back OK What is the looking at you are the same to you August 21 Wondering what do you remove and not give me give you Remove one time will tell you what do you remove from you remove speed to the maximum grand -divine between two -divine between two -divine between two kids toys on getting clear select Neeraj selected for to the point between to the example of And tell all this between that they are this and back we have characters Aryan Comment So let's move to the column looking at the first of all they know not what do you know about the difference between 10101 maximum liquid to you to You To You BookMeShow This Point To This Row And Column Between Tabs Her Britney Spears And Visting Pac We Character Common Want To I Love You To See What Do You Know About One You Love You To The Between There Doctor To The Volume Maximum 21 A How To Ok Now Let's Forward To The Next Possible Father Of Movies Possible K You Have This Particular Role In This Particular For Your Company's AC With Peace We Character Comment 2012 Near Syrian KP Singh Share and subscribe the Channel Please like Share and subscribe the Channel Do You Know About Your Local Factory Mom 12025 Value Leg Spinner Possible Answer Looking at this point Notes about Maximum 21 to do the example which will give you are you should not know what do we call the New Look Famous LED Airplane Mode One Plus Two Speak Any Field 3851 Dancers Page On iTunes On Your Computer From This Is Gold Award Winners From The Final Answer Key To Avoid - 3 - You Love Answer Key To Avoid - 3 - You Love Answer Key To Avoid - 3 - You Love That Lift Is The Land of peace and we have characters yes to you define tube factory form for - peace one rates that factory form for - peace one rates that factory form for - peace one rates that you get to plus 123 20 minutes this video then subscribe to the Page if you liked The Video then subscribe to the 40 12345 ok what do you Are going to field this particular quote from abroad so let's get started wage board all of 4 but plus one number to this piece subscribe to the Page if you liked The Video then subscribe to the Page Qualities to Net Spike Sunao Chords Ko Interview Number of Rose to number of roses you have to be four plus one meter per sa and what is the number of columns and B5 which acid which will give a good father crops and writing for civil liberties and positive energy 0212 from old play list play Do Also You Have Points Equal to One Plus Important Part Plus to the President of - 151 - - - - Subscribe to a Slippy Matrix Is Equal to One Patnaik 200 Words Were Still Possessions All of You Happy - - - - Verb - One Who After All This Is Not an Example Will Answer but What is the Answer You to File Working Improvement Some Compiler And Use Of And Declared And File I So This Schezwan Sauce The Last Love Changes By Subscribe Now To Receive New Updates Subscribe To This Soch Accepted Thank You For Giving Special And Listening | Delete Operation for Two Strings | delete-operation-for-two-strings | Given two strings `word1` and `word2`, return _the minimum number of **steps** required to make_ `word1` _and_ `word2` _the same_.
In one **step**, you can delete exactly one character in either string.
**Example 1:**
**Input:** word1 = "sea ", word2 = "eat "
**Output:** 2
**Explanation:** You need one step to make "sea " to "ea " and another step to make "eat " to "ea ".
**Example 2:**
**Input:** word1 = "leetcode ", word2 = "etco "
**Output:** 4
**Constraints:**
* `1 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of only lowercase English letters. | null | String,Dynamic Programming | Medium | 72,712,1250 |
310 | hello so today we are doing this problem called minimum hatred it's a medium type problem on lead code it's a very popular problem so let's get to it so the problem says for an undirected graph with three characteristics we can essentially suppose just remember it's an interrupted graph and we can choose any node as the root and the result of graph is then a rooted tree so when we choose a node as the root then the tree so basically tree characteristics here let me just explain that a little bit that means that he doesn't have cycles because it has cycle well then that's not a tree and it has n minus 1 edges because as soon as it's have more than n minus 1 edges it's no longer a tree so those are the two tree characteristics and it's an undirected graph and we can choose any node as the root the result graph is then a rooted tree among all possible trees that we can get by choosing any node as the root those that have the minimum hates are called the minimum hate tree and remember the hit of a tree is the length of the longest path in that tree right and the longest path I mean from the root to any leaf in the tree so given such a graph we want to write a function to find all the minimum hate trees but essentially what we want furillo here is just written the root labels which are here the nodes are labeled from 0 to n minus 1 and so we need to return the root label so for example we can assume here that there are no duplicate edges all that stuff and here for example we have this graph with tree characteristics that is if we wrote it at 1 then that's the minimum possible we can get because if we wrote it at 1 that means the length here is just one for each from the distance from each node is just 1 however if we routed at 0 then the farthest distance here is 2 so that's not the minimum one that we can achieve the meaning the one that can achieve for us the minimum hate and so for this example if we take one we are going to have the hate be true three because remember the heat is the longest path from a root to a note to a leaf and so the best we can do for a hate here is that we can make the roots be three and then at that point the max the longest path from that tree to any leaf is two which is from three to five and four if we take for the longest path or the hate would be from 4 to 1 or 2 0 to 2 which is still 2 so these two have like the same hate which is 2 so we returned them and so this is the problem now let's think about it a little bit and see how can we solve it so to solve this problem first I'm just going to give a couple of things that will help us solve easy in an easier way so there are a couple of concepts with trees and graphs so for a tree there is something called the center of a tree what is that it's kind of similar to the concept of fruit that the problem is describing and that's just it's a property on a tree out of the finance in a moment but we need another concept called remoteness where is remoteness it's the remoteness of V so these remoteness a vertex V the remoteness is its distance from its furthest node and so this is kind of equivalent to if we take V as the root of a tree of the tree like we would our graph at V then us hold this up let's call this R of V at a function so if we take V as the root of the tree then the gate of that tree is equal to lv because essentially the head of the tree as we said is the longest path from the root to the farthest leaf from that wood right because that's the longest path literally it's the path from the root to the farthest leaf so that's essentially the hate and so that's exactly the mootness is its distance of V from this furthest node and so what is the center of a tree is which is equivalent to the minimum heat root that the question is asking and that is just the a node that minimizes remoteness that we just talked about and that's what we are looking for the nodes one or can be one or multiple or two actually here we are looking for the node that minimizes the hate if we take it as the root right and so that means the hate is the distance from the furthest node so it's the node that minimizes the remoteness of basically of all the remoteness of that so it's the node that if taken as root will have the minimum remoteness possible right so that those are the concept that we are dealing with and now let's think about how can we find it so I have some drawing here let's just see it for a second so here we have the example that we have the first example here and so you can see in this drawing here the node 0 has remoteness 2 because its furthest node is 3 or 2 and those the distance is 2 edges so it's two-for-one it's just one from each one two-for-one it's just one from each one two-for-one it's just one from each one of them for 3 the distance is the farthest snow zero or two and those as have remoteness - and same for two year and so the one - and same for two year and so the one - and same for two year and so the one with the minimum remoteness is the node one so that's our answer right that's the one that if we pick as the root will give us the minimum heat possible because the heat would be one now if we take the second example which is this here take the second examples is this tree the same as this one I just annotated it with the remoteness values you can see here that we have for one the remoteness is three because the longer the farthest one is five and the distance here is one two three four same thing for two in zero but for three the remoteness is just one to the furthest node from it is five four for the farthest node from it are L zero one and two and all of them have distance of two from it right so we can see it three and four have the same remoteness value which is two and so these two because they both minimize the remoteness as we said here in our definition here of the center they are both a center and so what you can notice here is that we can have you can have at most two centers so our solutions for this problem can have only one or two centers they can't have more and in what case we can have two so you can see here we have two because the longest fat is so because the longest path is odd which is three here so we have two in this case here the longest path is even so we can't we have only one right and so that's just something that you can explore while solving this problem and so we can see that there are most two centers or woods geodes now a couple of concepts that we need to done it to other concept that we need to define just to be able to understand the solution to this problem which are so a degree what a degree of a node it's just the number of nodes incident to it so basically what that means is that for an interactive graph is those it's those that are in the adjacency much of that node right so that's one thing and then also a leaf has degree of 1 why is that in an indirect to drop of course in an undirected graph because usually it's if it was a directed graph then it would have 0 but this one here the 1 bar is coming from the parent right from the current because undirected graph we add each node participating in the edge to the adjacency list of the other and so the parent gets acted a chance it's a lie so it's a child and the child gets added to their Jason suppose a parent so any node that has a degree 1 that's for sure a live right we have also this concept called a path graph what is a photograph path graph is it's a tree with two or more vertices that don't have any branches so basically there are there is no node that has two children every node has just one child any branches okay so let's see maybe an example of that here so you can see here this basically that this thing that I'm circling here that's um that's a path graph because basically it looks like this it's you have the node and then you have path like this Y and you can imagine it's like a path down instead like this because if it was a tree so da like this and why there are no branches so there is no other node in this side for example so every node has only one child like this now this basically if we take this one this is a simpler case so this is a simpler case and this is like a very useful tool when you design an algorithm which is usually sometimes goes by simplification or simplifying care so basically take a simpler example and see how would you solve it and so for something like this how would we solve it to find the root the center that minimizes the remoteness if we take something in the middle so depending on if the path is like has light has length odd or even if it has length even then we will find the center in the middle if it has length odd then we will find two centers like this right two centers that can because both minimize the head which would give us basically the same case as we had here with Islam what there is a tie like three and four here now with this case how can we solve it the simple way to do it you just take two pointers P 2 and P 1 and move them like simultaneously at the same speed keep moving them keep knitting them and at the end either they will both meet so they will both you'd have P 1 and P 2 at the same space there's a place 1 if the light is even or you would have them like this right and so basically what we'll be doing and if whatever the case is that they meet or they are one edge just apart then we stop and those two notes or one node at the center and so the solution for this case for this simple case simpler case is take two nodes take two pointers the edges are in the at the starting two pointers p1 p2 starting at the leaf in on the two sides of the path Brad and move them at the same speed until they meet or they are one distance apart one inch then return one or two notes they are pointing to and so we have that solution for the simpler case now what can we do this if you think about it we can just generalize this so we take a simple simpler case and then we generalize it to a more complex case so in our case we don't have just this paragraph we have multiple there are branches and so we generalize the solution which is just put multiple pointers instead on every leaf basically on every leaf in the graph and move them at the same speed and whenever two pointers meet so it's just for this one and then two so two would be so first we have will have multiple pointers on every leaf in the graph and then step two we'll move all pointers at the same speed and then three whenever two pointers among these are among these at the same speed meet or are at one distance apart one edge apart then keep only one of them and keep doing this and so there are and keep doing that basically keep doing one and while one two three until we have only two pointers because basically until we have only two pointers and that means we have found our centers because we can have only one or two centers like this and so when there are only one or two answered two pointers that are like that are at the same node or again one edge apartment then return the notes they are pointing to so while doing the same thing we did with once a photograph just first we start off with all of them and then we keep reducing until we get just two notes that I will give us to the one or two centers so one thing we can say about these two pointers what's called them P K and P sub or P sub K and P sub L so what can we say about these two pointers since they are the two last ones we can say that these two PK and PL are in the longest path right because if otherwise they would have met sooner and they would have been like made to be one instead right so these are the in the longest path right which means that if we take these if we take the nodes there are nodes as a center we will minimize their mootness because essentially they are it's the longest path so whenever who take the longest path and we put the center there that means we'll have because if we don't do that means we will have if we take one with the smaller path then that means those would have and hate that is bigger because they can go all the way because in a tree you can go you can do something like this you can go from here all the way up and so go from any node and go all the way and traverse the longest path and then have more than that and so the right strategy is to go to the longest path and just divide it by two invited like and find that longest path to get the minimum hit I hope that's a little bit clear and so for the implementation for our implementation of this solution now let's think about the implementation of this idea and so for this implementation our pointers we're all just going to call them leaves instead because that's what they are right they start them and we put them at the leaves our positions and every time we advance a pointer so let me just show the example I have fun with that I think it's something like yep so I will be doing is something like this so we have let's say this graph here the graph that I'm pointing and so we will take the leaves first and then to move instead of just moving a pointer because that would be hard on a graph we are just going to remove them or consider them removed and so when you consider them removes what does that mean that means that the degree of the nodes connected to them become minus one or at least we'll remove the this node from the adjacency list of this one when we don't move it and so when we remove this the it all the leaves who will end up with these two and so in this case we already found our solution it's the center's are these two because as soon as we have two leaves that means we are done for this one we will keep removing the leaves and so we'll remove these leaves and then removing them means the adjacency list of this node has wellness has one less this one gets removed from it and so we will end up with only this and so will have this will remove the leaves again because it's still not free with some not healthy well we have we still not have two we have three here and so we remove these two Leafs again and now we end up with one which is less than or equal to two and so we are done and we written this as the center and so the strategy here is so this the fact that we are kind of removing leaves that's kind of our way of advancing our pointers and saying that two pointers meet in our case here is just saying that okay we have only two leaves left or we have only one leaf left and so that's how we are going to do the implementation here and so we can so we are doing this with BFS because we FS allows us to do a lot of I love a line so the first level will move these leaves and then the second level shall stay actually this example so the first level would move T these leaves the second level traversal will move these leaves and so it's kind of BSS but we are not going to love available but we are going by leaf and then leaves again and they're moving piece until we end up with only two leaves or one day so that's the idea so let's get started and implemented star template so what is first before implementing it what is what do you think the complexity is of this so we will keep removing leaves until we have two or one so at once we will remove n minus 1 leaves or nodes in this case and so the time complexity here is just open such that open is the number of nodes and the space complexity it's the space complexity of BFS and since we will keep storing the leaves here will keep removing leaves and finding the new leaf so also the space complexity will be at most the number of leaves which would be at most or event right so the space complexity also is open so it was implemented so to implement this solution we need of course the adjacency list so that we can be able to remove once we remove a leaf we can remove it from the adjacency list of the nodes connected to it and so to do that we are going to have an adjacent sailors contracted as a set or list whichever is easier both are fine since there are no duplicate edges we can afford to have that set and so and then we are going to go through the edges so that we can add them and this is an undirected graph so we are just constructing the adjacency list so it isn't Silla stuff you are going to attend D and for D you are going to offend you and now we are going to have out leaves the first set of leaves which are these ones here that have degree 1 remember we said a leaf has a degree of 1 in an undirected graph and so and which is coming from the parent because of this here and so our leaves are going to be I for I in range of n minus 1 and sorry in range of and if the degree is 1 and what is the degree it's just the size of them of the adjacency list so the adjacency list of I should be equal to 1 so these are the leaves now what did we say is the our step in condition is if we have so we have at most and we have at most two centers right that's what we said here we have at most two centers and so we'll stop when our n becomes just less or equal to 2 because that means we already are we are either in this case or in this case right and so what we are going to do is welcome to while n is so this is still bf as you can see here that BFS can be different than the usual vanilla papers that we do so here our second condition is while n is bigger than 2 so whenever it's less or equal to 2 that means we are done we found our centers and so we need to subtract from n the length of leaves because these we are removing them and so you need to distract them from the number of nodes in our graph so the length of leaves and then we are going to construct the list of new leaves right and these are the ones we remove these leaves here we will end up with this new graph and so the new leaves are this one and this one so we are going to construct a list that will keep them that will keep track of them basically because every time we remove a leaf the one that became with the degree one that's a new leaf right and so this is our new leaves and then we are going to go through each leaf and see removing it made which node become a new leaf right so in leaves then we are going to take first the so it's a leaf so it has only one adjacent node right and so that's the parent so let's just call it G and the way we can get it is just by going Jason say list leaf and since we are removing the node so we can just say ah so that leaf will have no longer the parent as a in its adjacency list so changes father and then we are going to take the adjacency list of change is the parent since it has this one is removed so it's no longer part of its adjacency list so we need to remove it and so we would say remove right and now we will check your veggies and see of J it became one because we remove the leaf didn't become one if it became one then it's a new leaf which is what happening or what happened in this case but maybe it's not because maybe there is another node connected from this side so we are going to check and then if it is we are going to add it for the new leaves and then after this so traverse all the leaves after this we are going to assign for the next iteration we are going to assign two leaves this new leaves that we just got and so we didn't ask her leaves here so that we don't mess up this follow so that this four loop doesn't go with the new league side and now what is the what shouldn't be returned so we should return whatever it's left in waves because when any bigger equal to 2 that means whatever the last leaves like in this case or the in this case the last two leaves that's the solution so we can just return this and that's about it that's pretty much the solution and so why is it BFS because we are going through the neighbors adding them kind of to lot by 11 accepts our levels here are Leafs instead of the normal entry levels and that's pretty much it for the solution and so okay it's ad so here actually it's not the agency of Jay that is equal to one it's life that's what we mean by a leaf which is the same that we did here okay so that pass is there um so you can see here for the time complexity you can see here that we keep doing and until n is less than equal to 2 we stop and every time we subtract the number of flips so you can see that at most we will do open operations if like on every iteration will remove just one node as the leaf and that may happen in this case then we have open so the time complexity is open what is this space complexity so the main things we are using are this adjacency list and this leaves the adjacency list is at most of the number of edges and that was our n minus 1 so the graph here is at most base complexity of to e and since this is a graph with the 3 characteristics so we have at most and managed 1 edges all right we have n minus 1 inches so this is pretty much open and then for these leaves we keep adding only the leaves so we keep adding only the leaf so at most it will be the entire the number of nodes in the graph and so this also is often even combined with the new leaves both combined it's just open so the overall space complexity is just solve n here which is what we said here and that's it so let's first run this submitted and see if it passes okay we have one wrong case which is if we have one incan empty list and in this case we should return zero so I told me this one can just handle by checking if n is equal to 1 just return 0 it submit okay so with that passes so this solution was using BFS and using this trick of removing leaves this is a useful trick sometimes also it can solve topological sort I have a video just before this one that uses it to find if there is it for logical ordering it's the problem is called course schedule so you can take a look at that now we can solve this actually with a different method so let me just explain that I'll keep this inner so the other way we can solve this problem is using this concept of max path so what is the longest path so if we find the longest path find so if we find the longest path so if we find a longest path I'm just put back those something that we need so we need this so if we find the longest path all right then we can just take the middle or if the length is like if the length is some is odd then we take the two middle points that's what we said if we have the longest path that's a way to minimize there are moochers here and to get the minimum hit right and so the way we can solve this problem using that is we can just how can we find so we need to find the longest path and then just take the middle one or two no it's depending on whether it's even or odd and so how can we do that so first to find the longest path we can just select on any node X it's kind of a called the greedy approach in a way and so you can 1 select any node X and then 2 and consider the river and then this second step we do a DFS or BFS I'm going to do DFS in that case in this case but both work and so and find Y which is the node with the that achieves the highest our feet right with the highest or be the highest our X basically the highest remoteness from X so it's the node with the longest distance from X what so and then the third step we will let Y be the new route and do another DFS or DFS to find the nude with t with max out of y so same thing the node with the longest distance from Y at this point so and do another way to find them to find the node let's call that node set right and so now this means that the path white rosette is the longest path why is that let's just um so because if we have a tree like this and we pick any X as the root I say we pick this X as the root and so basically with this I'm just this year the rectangle triangle is just modeling that result a subtree that can be large that can be small we don't care but in our solution here first pick an x value there is any nodes in the tree and then we are going to do a DFS or a PFS to find y which is then the node that is farthest from X largest suppose this subtree was really long and then why was somewhere here then we'll do another BFS that finds the node that is the furthest from this Y and so a tree remember it is all connected and so we can go all the way from here fast through the root this red line here and sunset until we find that said here we can do this with DFS so this here is our longest path whatever if we care if we take anything else you can see in their presentation it won't be the longest path because all the tree is connected right so that will give us the longest path and then once we find this longest path so since this is the longest path just take it's middle one or two notes and that's the solution we are done so yeah that's it so let's just stop so we said we first we to construct the graph right we need to construct our adjacency list as we did earlier we can use the same set as we did but I'm just going to use our default dates that with set which would be the same thing as doing this is the same thing as the mean set for a range of and I just write like to UM give you a different implementation so that you can whenever you read new code you can understand it and so we are going to go through the edges and put them in the adjacency list and so adjacency of you we are going to add the a.m. for B we are going to add you and a.m. for B we are going to add you and a.m. for B we are going to add you and now we are going to do the steps that we said write select any node X as the root so I'm going to select X as 0 and so this is step one and then we are going to find the max do a DFS or BFS to find y which has the highest rx right or the nodes with the longest distance let's just call it the node with the max path from X so that would mean max path we are going to find max path from X to and since I'm going to use DFS and don't want to do much visit the same just the normal way BFS we have visited set right so that can keep track of the note that it isn't it and now we are going to find that path and we are going to put it in a less like this so let's just write the signature of our next path so it takes a note let's call that V and the Secretary's visit and does DFS to find the master will write that later and then so this is the second step then our third step is we take the wire as the new route into another DFS BFS to find set right and so our Y is going to be whatever path will return it we will write our BFS in a way so that the so that Y is at the first position you know I'll show how later but this is the third step and then let's just make this four step and then this is so do another B DFS or BFS to find the note said that it has the longest distance from why she's the node with the max path from Y and so that would be max path from Y and the new set of visited so that we can find it and that will give us another path that contains said but this path is the longest so Zed is at position cat 0 but we don't really need set here so the said would be at that zero and then now we just take the middle right so we just returned the middle and there is a nice trick to find the middle of this path which it can be either one node or two nodes because I will show like a why but we can do that by just doing em minus one so let's take em as the length of the path so it would be M minus 1 divided by 2 and then M divided by 2 it was fun so why is this so because let's take an example if the path length was four that means that this here what would it be so this would be because M minus one divided by two is going to be equal to four minus one divided by two which is 3/2 and so let's just write this in 3/2 and so let's just write this in 3/2 and so let's just write this in Python and see what this gives us so three divided by two that's one right and then M divided by 2 plus 1 that means 4 by 2 plus 1 so let's write that here again so 4 divided by 2 that's 2 plus 1 that's 3 and so this is 3 so our path is actually so this is our patties that we set here the first one which shows this one it's one and the second one which is this one that's three so this is essentially what is this is just in a list that's just path of one and path of two right because if my path is let's say 1 2 3 4 so the length 4 right if I do Pat 1 3 I should get just 2 & 3 right and that should get just 2 & 3 right and that should get just 2 & 3 right and that exactly what it should be because both true has distance if this is the path it has distance 1 from here from its furthest you know it has distance sorry of 3 from its furthest node 1 2 actually a tool from its farthest node and this one has distance of 2 from its farthest node so they have the same remoteness basically and so that's the case of when n is odd so this is case when M is even sorry and so when M is even we verified that this formula gives us the right thing right so now let's verify that in case when M is odd that it formula gives us that I think this is a nice trick to remember to use whenever you have something that can give only one or two volumes depending on thee in a list of course depending on the holidays the length is odd or even now when M is odd is it was taking example let's take for example five in that case the path is still this and so what is the value of this so in that case this here is equal to five minus 1/2 so here is equal to five minus 1/2 so here is equal to five minus 1/2 so that's like just four divided by two is two that's two in the case of M divided by two plus 1 is equal to 1 M is 5/2 by two plus 1 is equal to 1 M is 5/2 by two plus 1 is equal to 1 M is 5/2 plus 1 so let's see that but it's 5/2 plus 1 so let's see that but it's 5/2 plus 1 so let's see that but it's 5/2 here that's two plus one so that's three actually so our path this path here it's just equal to two to three and in this case this is in Python just fat to fight because again let's just add to our path so that it's length is 5 and now if you do path of two pack of 1 to 2 to 3 that just this value here at position 2 and yeah so we know that this works and so now what's just I'm right I'll give us that fine to for us the max path using DFS so this I'm you're going to use DFS you can use because I'm also and so the implementation of this first we need to add to the visited set we need to add T I and then for all neighbors who are going to visit unable to obtain the max bath that is coming from all neighbors so the max path among all neighbors that's what we want so the stick first all paths of all neighbors so that would be max path starting from that neighbor let's call it and then let's call it W the neighbor and then we all passed the visited set and what it's W it's the neighbors of V so that's adjacent a list of V but we don't want to visit a note that was already visit a neighbor that was already visited so we need to check that it's not in the visited site and now we want the max pad among things so our max path that we are interested in that's the math in max and paths and what is the key that we'll be using it's the length faith on you confess a key so that it compares using that so we are comparing all paths using their legs so that we can get the max path and now once we get the max path we will add the node here to it and this is what allow us to have at the end y at path 0 because we'll keep adding to the end so the last one would be added to the end and so that's why it's at that edge it's at that end of the path and at the end of interest rate on that and yeah that's pretty much it and so now we did all our steps one two three and then this was step four and this was step 5 so yeah that's pretty much it plus run it and see so we have a problem with this max so paths here may be empty right that's the problem because if we do so yeah it's saying an empty sequence it cannot accept a mix it you just sequence because if you do max off something like this with key is equal to length then we have problems so the way around this is you can say or if it's an until us let's just give it a list of empty lists so that it can return us just an empty list and so the way you are going to do that just of me that problem you just by doing this okay so we have the same problem of n equal to 2 1 solve that we'll just solve that by the minute n equal to 1 return 0 okay now let's take this to try that this work so state 4 and this okay so we still have a problem there so we have finished somewhere it's not just the first kids and this is so we add verify our work max path so we add to the visited set we take the max path among all neighbors and you take it only if it's not in the visited set and then you take the max path among all paths using the key length and append VF like that and we written that path okay that seems correct see our adjacency list so we have movie and then we add you to be and you to the adjacent V to the adjacency list of viewer and due to the existence of a stove V so that's good we do the first path from 0 and then Y is fat and 0 and so we do that we got a new plan yep the problem maybe is just the parentheses of this something maybe it's doing M minus 1/2 yes that's maybe it's doing M minus 1/2 yes that's maybe it's doing M minus 1/2 yes that's what it was doing and let's go back to that case that we had a problem with earlier ok so that case passes now let's just try on this with value 6 ok so that passes submit ok so that solution passes um and yeah that's all for now yeah so yeah sorry um I forget to say the time complexity of this so this is DFS so the term color complexity is usually just um we are doing DFS here Mach 2 times so it's 2 multiplied by V Plus E so it's around E Plus E what are both of you plus E power V is just an hour is n minus 1 and so it's kind of both n plus n minus 1 so it's around oath to n so it's actually just open that's the time complexity the space complexity is also we are having our paths that contains the longest path we are having two of them so at most each of them is n so both are n so this was the space from this world a time complexity and so the two paths that we are using here both also are at most n so we have also often in terms of space complexity yeah so that's it see you next time bye | Minimum Height Trees | minimum-height-trees | A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree.
Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`) are called **minimum height trees** (MHTs).
Return _a list of all **MHTs'** root labels_. You can return the answer in **any order**.
The **height** of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
**Example 1:**
**Input:** n = 4, edges = \[\[1,0\],\[1,2\],\[1,3\]\]
**Output:** \[1\]
**Explanation:** As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
**Example 2:**
**Input:** n = 6, edges = \[\[3,0\],\[3,1\],\[3,2\],\[3,4\],\[5,4\]\]
**Output:** \[3,4\]
**Constraints:**
* `1 <= n <= 2 * 104`
* `edges.length == n - 1`
* `0 <= ai, bi < n`
* `ai != bi`
* All the pairs `(ai, bi)` are distinct.
* The given input is **guaranteed** to be a tree and there will be **no repeated** edges. | How many MHTs can a graph have at most? | Depth-First Search,Breadth-First Search,Graph,Topological Sort | Medium | 207,210 |
994 | welcome to august leco challenge today's problem is writing oranges in a given grid each cell can have one of three values zero representing an empty cell one representing a fresh orange and two representing rotten orange every minute any fresh orange that is adjacent to a rotten orange becomes rotten return the minimum number of minutes that must elapse until no cell has a fresh orange if impossible return negative one instead we're given in this example we have one rotten orange here after a minute these two adjacent to the rotten orange turn rotten after two all these other oranges also turn run and so on and so forth initially you might think we could probably do this recursively but there are some problems with this um with this lead code problem like it's tricky because basically we have this initial state at every minute and if we were to make updates to the grid we have to do that one at a time but that messes it up because at the next minute if we were to say hey change these to rotten and then we check for the next orange now that we've updated it to make it rotten we're going to update these oranges as well but another minute hasn't elapsed so how could we store this original state while making these updates without causing um next stages to occur next changes to occur one way you can do that is to use a temporary object you know create a copy of this grid and make updates to that copy and once the minute has elapsed once we've checked every single cell then we update the original grid with our copy and so on and we can just continue that so that's going to be my first approach what we're going to do essentially is count the number of fresh oranges we will go through every single cell and update all the fresh oranges that are next to a rotten orange on some sort of temporary object if we've reached the end and found that there are still fresh oranges then we will replace that original grid with our temporary object and continue the loop and we'll just continue that until we see that we haven't been able to decrease the number of fresh oranges and if they're still fresh oranges we return negative one right otherwise we return the number of minutes that have elapsed so that's the tricky part because it's kind of hard to do call by values in python one of the tricky things about it is when you create a just do a normal like object equals object two everything that's immutable is actually still a call by reference so you're gonna have to make a deep copy of it and i'll show you how to do that in a little bit so here's what we'll do we'll first count all the fresh oranges okay so to do that let's first initialize fresh as 0 and we'll also initialize m equaling the length of grid and n equaling the length of grid column 0. all right so the first thing you want to do is count all these fresh oranges so for i in range of n oh i'm sorry m and for j in range of n we'll check if grid equals one that's a fresh orange we will increment our fresh orange by one and that'll be it so now we have the number of fresh oranges we have okay so let's initialize a couple more variables number of minutes have passed and we'll also store previous to equal the fresh and what this is going to allow us to do is check to see at every loop if we've been able to decrease the number of fresh oranges because if we haven't if we've made no change to the state then we should break out of this loop so i'm going to do a wild true loop here for now and um because we don't know how many times it's going to elapse and we'll break out of it when we haven't been able to decrease the number of fresh oranges okay so the first thing you want to do is make a copy right and to do that you can use the deep copy method from python it's the only way i know how to do it without weird things happening so what we'll do is create a copy of grid and now we'll check every single cell inside of our grid for so to be the same thing for i in range of m for j and range of n and the only thing we care about is when the orange is rotten right like we're going through each one of these cells and what we'll do is if it's rotten we'll make updates to all the adjacent cells we'll make sure that's in bounds and if it's a fresh orange we'll update that to a rotten but the key here is to make sure to make this change to our copy object not the original grid itself because if we did that the next time we move we might end up making more changes that we shouldn't have at this minute all right so for if the grid i dot j is rotten that's two then what are we going to do well we'll have to check up down left right so that's a little bit tricky what we'll do is do another for loop we'll say for rc in and we'll create a list of the four directions we'll do that by creating four tuples say i minus 1 j then we'll do i plus 1 j i j minus 1 and i j plus 1. so that's a lot of loops but this is only four so uh that's not going to be too bad and basically if we got first make sure we're inbound if we're equal to zero and less than what's rho so um for m and zero equal to c is less than n and we're going to check our copy object not our grid because remember we have to um uh make sure that we're only checking for the changes that we made in our temporary object right so check to see if our if this thing is a fresh orange then we want to update our temporary object to a rotten orange and we also want to recommend the number of fresh oranges we want to make sure we say okay there's one less fresh orange all right so that looks a lot more complicated than actually is once we have done that now we want to check to see if we've been able to make changes like have we been able to decrease the number of fresh oranges so if previous um well yeah if previous equals fresh we haven't been able to make any changes let's break out of our loop otherwise we've made changes so let's first increment our minute by one let's make sure to make our grid now equal to the copy object and also make our sure our previous is equal to fresh so that we can continue checking this so once that's finished uh now we should have the number of fresh oranges that we have left and the number of minutes that have elapsed right so the first thing is well if the number of fresh oranges is still greater than zero then we turn negative one because we haven't been able to make all the oranges rotten otherwise just return minutes because otherwise we've made all the fresh oranges rotten so just return the number of minutes that have elapsed so let's make sure this works uh didn't work why didn't this work uh let's see to be honest i'm not sure why this didn't work it should have worked well let's see what am i messing up here how many fresh and how many minutes have passed okay so we break broke immediately that's not good hmm okay i see silly typos like this okay there we go so i made i a j instead so let's go ahead and submit that and there we go accepted all right so this was my approach and one way you could optimize this is to not use this deep copy object because we are using extra memory doing this and we're also doing some unnecessary calls because all we care about here is the grid numbers where the oranges are rotten right we don't really care about the empty ones or even the fresh ones at that point so why should i even check them so one way to optimize this is to forget about this whole deep copy thing and instead use a cue we can think of it like a breath first search where we're only going to we'll store the representative state inside the queue itself that way when we make these updates like the number of minutes that have elapsed is inside the queue and when we're making changes to our original grid we'll still remember like how it looked originally because we'll have that information inside of our queue instead okay so we can do that let's make a cue and we'll use a cue object and what we'll do is say if grid that i j if it's a rotten orange let's add that to our q so how do we do that let's enter our q will put a tuple of the i the j and the number of minutes have elapsed and so far that should be zero so we'll only do this when it equals a rotten orange and now we have our queue so rather than just using this while true we'll just say while there's a queue forget this whole core copy and frankly forget about this whole uh nested for loop what we'll do is we'll pop off our q we'll say okay q pop left and now we'll have what i guess we'll pop it off by saying we'll have i will have j and we'll have number of minutes that have elapsed right so if the grid of i j is equal to two then we're going to do this whole thing and what we'll do is update the grid only when it equals one so we do that and we can decrease our number of fresh oranges here and we don't really need this previous fresh anymore because we have our queue to help us with that because what we'll do is just add it to our queue if all these conditions are met so what we'll do then is say okay q append we'll still have the i and j or the r and c rather and we'll increase our minute by one so that should actually be a lot simpler uh we don't need any of those nested for loops and we'll probably save a lot of time and memory doing this so let me see fresh if it's greater than zero still return negative one and we can just return the minute because in our queue since we're doing like a breadth first search the last one will be the maximum number of minutes that should have elapsed and we're only going to return negative one if we haven't been able to decrease all our fresh oranges me see if this works i may have messed something up here oop okay append oh make that a tuple okay so that looks like it worked let me go and submit it and there we go accept it so this is probably the optimal solution now my initial approach it still wasn't that bad you can see that it was still pretty fast but the problem was creating that temporary object is sort of cheating in a way using this cue i think is well i'd be pretty impressed if somebody was able to come up with this and you know starting with that first approach you can see how you can improve it slowly by realizing oh we're wasting time here we're wasting space here and slowly realize like other approaches to solve the problem so i really hope that helps thank you for watching my channel and remember do not trust me i know nothing | Rotting Oranges | prison-cells-after-n-days | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null | Array,Hash Table,Math,Bit Manipulation | Medium | null |
273 | okay so lead code practice time so two goals in this video the first one is to find the solution and then put some code for this uh for this problem and then the second one is to see how to solve this problem uh in the real interview so let's get started so remember the first step is always to try to understand the problem and ask clarification questions if there's anything that is unclear to you and then think about the ash cases so let's first read through the problem so it's called integer to english words so convert a non-negative integer num to its a non-negative integer num to its a non-negative integer num to its english words representation so for example for the first one 123 it is read as 123. and then the other one for example 2 12 345 etc okay so the constraints num is between 0 to 2 to the power 31 minus 1 which is within the range of a in 32 for the positive numbers so i think there is not much about the solution actually it is so if this question is asked within a real interview i think it's mostly looking at your coding ability because there are a lot of ask cases you need to think about so for example uh like the han so okay so it is like um for example under 20 there are one two three four five six five nine ten and eleven twelve thirteen fourteen something like that and uh above 20 there like for example 30 50 70 something like that uh yeah i would say um yeah i would say that's mostly about the coding part but let's give it a try by doing some coding things so um i would define first define some helper function let's say um let's say for the ones we are what we are going to do so for the ones suppose we are given the hint i let's say into num then we are going to switch the num as case 1 is equal to we are going to return uh one uh okay so the first one first letter should be capital and then we copy paste it to be case two three four five six and seven eight nine okay so eight and nine okay so this is a two digit sorry this is one digit i was thinking about one digit that i saw set two digits so and then three four five six uh seven eight and uh this is nine okay so uh that's it and this one we just return empty thing at the end and uh the next one i will think about is um under twenties so under twenties under 20. so if it is under 20 then i'll see num as equal to this i will switch the num uh so one two three four so this is one two three four okay it's eye line so we switch the num again it's about different cases um should we put the 10 here so if it's definitely um let's say for the ones that was just first case is 10 i would say uh 12 20 okay so 10 11 12 13 14 15 16 17 18 and 19 and 20 okay the last one is 20 so this one will be 10 11 12. how to pronounce it 2 12. okay 12 13 14 is it 14 and 15 16 17 18 19 and then is 20. uh should we actually put 20 here um because if it's 20 i think we don't need to put one here instead we define something else for it um so the next thing i would define is the tense so it's the ten so it's a tense so regarding the tense let's say maybe i can say so to match this one let's say two digits two uh not two digits let's say just tens okay so maybe this one we call it once okay then um uh-huh and then you do another switch uh-huh and then you do another switch uh-huh and then you do another switch um switch this time it's all the like 20 30 something like that 40 50 60 70 80 and 90. okay this one is 20 uh sir 30. 40 50 okay 60 and 70 uh sorry 80 and 90. this is eight this is 80. all right so we have the tens ones and the 20 and those are defined so let's say so let's get a something another helper function sitting on top of that um let's say okay so let's say how to say that it's let's say we have we define a helper function called the we call it two digits then it's mostly about handling everything under 100 so it's going to be numb like this so first of all uh this is 20. so if uh the num is smaller than so if num is smaller than if okay so if num is smaller than 10 then we simply return once with the num okay and then if um num is smaller than 20 then we simply return uh the 20s under 20 for this number otherwise it's larger than 20 uh we will need to compute how much the tens so in tens is equal to num divided by um num divided by 2 and then times 10 so this is the tens so those are the tens um okay and then we are going to compute the ones so this one it would be modular 10. all right so let's see so if because it's if once is equal to zero so we just need to return uh let's say 10 it's the same thing so 10 let's say just second digit um maybe just tens uh tens numb okay one's numb okay so if one's done is equal to this one is equal to zero then we return tens uh tens now other uh otherwise uh we need to say okay um it's larger than it's larger or equal to 20 and the ones are not zero we would return tens um tens num plus the empties empty plus a space in the middle and then we will call it the uh the one the ones and on top of the ones done once them okay and then let's define the private and let's define the three digits which is a 100 the anything under 1000 so three digits so this is the ins num okay um so um first of all let's say define the 100 hundreds num it would be equal to a num divided by 100 times 100 uh all right so just how many 100s are there that's just fine so and then we would define the rest of the two digits the rest let's say the rest is 2 rest is equal to num modular 100 okay so there are so there are several things we may need to think about so if hundred sum is equal to a zero that means it is not more than a hundred we just return two digits uh okay rest okay otherwise it means the hundreds number is larger than zero if it's larger than zero first of all we need to see whether the rest is equal to zero so if it's not if it's equal to zero we just need to return um so first of all we call the ones on top of hundreds num was equal to the am a space and then it is han third okay and uh otherwise it is actually uh so return the ones how many hundreds are there and then plus the two digits things okay uh which is the rest okay so we don't need this else here instead it's just you can just pull out this uh expression and that is number two words so we need to define maybe there is trillion right trillion billion something like that so i don't know if there could be like several trillion so two to the power of 31 uh yeah so let's say just let's define the trillion things so first of all we will define the trillions is equal to num divided by okay this is okay thousand million billion this is trillion okay um so first of all let's see like the max uh in 32 or what is that so it is actually a hundred this is the million this is the billion so the industry to it okay so it doesn't have trillion so we just need to care about billion so we just have the billion we have a million which is equal to num uh minus billion times the billion uh actually so in the real code you need to define this kind of constant uh to be uh you need to have some constant defined for it but here we just uh just listed here at least uh just refer the exact number um so minus the billions and then we divided by the millions okay and then uh the thousands okay so the thousands would be uh would be nums divided by uh okay so actually um we could okay so how to do that um okay so we could just do this so we could just uh minus equal to the so we minus our billions here because we want to make the expression to be um to be more efficient than it is nums divided by the million and then we are going to minus the billions taking track of that million times uh okay so in the thousands regarding the thousands it's the num divided by the thousand so okay after the thousand it is not okay minus the sound and time the thousand so it's then the num only contains the number less than the thousand okay so that's the thing and the one thing we need to think about as special case is if basically zero then we just simply return uh zero without doing much of the computation so um how to do that so if um okay so how to say that if it only contains a billion um so let's say the let's say we just have the ret as this one and if um if billion is larger than zero then we will um have ret plus equal to uh how many like how many billion uh this would be a three digit and called on top of billion all right so and then a okay then a maybe a empty thing here and then um if the mailing is larger than zero then ret plus equal to uh what is that three digits uh the mammalian thing plus the mammalian okay so and if the thousand is larger than zero then rit plus equal to the three digit again on the thousands and plus equal to the thousand okay so uh sure then if uh rest is larger than zero the ret uh plus equal to uh the rest which is the three digit and then the um then the uh the num okay this is num and then finally we return rit dot the strap is going to exclude the things okay exclude the leading and potentially leading and extra spaces there so let's see uh so i think yeah so we don't need having too much to yeah so usually for the testing if it's not some question like this we need to go through some test cases explain how it works manually but this one since it has a lot of branches so it is very hard to cover all everything manually so let's uh just run this code and use this platform to um to help us so runs the code two days some typo here let's fix it um if rest is it's not the rest it's actually the numb okay um sure so the compiler on line 50 okay so we need to return something empty all right so ret plus c code to uh we need to initialize it okay so it's except for this one let's uh submit it so for the wrong answer okay so we have typo here it is actually uh 40 x40 okay it's my bad okay now it's accepted cool so uh i think regarding the task case setup um it's very hard but that but it's very hard to mention what task case you want to set up but definitely uh say something like um for we are going to test all things like under 10 under 9 under 20 and on hundreds uh and and also including things like the billion million thousand so that would be i would say that should be enough for it um yeah so just mention that we have we should set up those test cases to have good enough test coverage but other than that um i think we should be good so that's it for this coding question so if you like it please give me a thumb up and i'll see you next time thanks for your time watching this video | Integer to English Words | integer-to-english-words | Convert a non-negative integer `num` to its English words representation.
**Example 1:**
**Input:** num = 123
**Output:** "One Hundred Twenty Three "
**Example 2:**
**Input:** num = 12345
**Output:** "Twelve Thousand Three Hundred Forty Five "
**Example 3:**
**Input:** num = 1234567
**Output:** "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven "
**Constraints:**
* `0 <= num <= 231 - 1` | Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out) | Math,String,Recursion | Hard | 12 |
545 | Hello friends welcome to my channel let's have a look at problem 545 boundary of binary tree in this video we are going to share a treatment based on traversal here we are going to use different kinds of traversals to glue the left boundary red boundary left boundary Leaf nodes and red boundary together first let's look at the problem statement so the boundary of a binary tree is the concatenation of the root the left boundary the leaves ordered from left to right and the reverse order of the red boundary so notice that we are going to reverse the reverse order of the red boundary so this is very important another thing is that so this problem distinguishes the root with respect to the left boundary and the red boundary so let's look at the definition of left boundary in the sense of the current problem so on the root nodes left child is in the left boundary if the root does not have a left node child then the left boundary is empty right so if a node in the left boundary add has a left child then the left child is in the left boundary um the third one is that if a node is in the left boundary and has no left child but has a red child then the red child is in the left boundary the leftmost leaf is not in the left boundary so this is an important point right so the red boundary is similar to the left boundary except it's the red side of the roots red sub tree again the leaf is not part of the red boundary and the red boundary is empty if the root does not have a red child the leaves are nodes that do not have any children for this problem the root is not a leaf so this is also an important point so the overall requirement is that given the root of a Banerjee Returns the values of its boundary so notice that there are two examples let's examine them with some detail for example in example one the return is 1 3 4 and two right so the left boundary is empty because the root has no left child right the ref and the red boundary actually is um following the following um the red boundary follows the path starting from the roots red child right two and four right so actually this one is very special so if we uh you we use the same conversion as the red left boundary so we shouldn't count four in the red boundary but you know this is the treatment detail we can control in our code so the leaves are three and four right so left so the root left boundary leaves and red boundary right so similarly in example two so we have a root that has one and the left boundary is two and a four and four is not so not one of the not belongs to the left boundary so two correct so one is the root and two is the left boundary and then four seven eight nine ten are the leaf nodes and six three are the red boundaries so however you know when we write the code so we can actually get all of these parts right so we just need to not we just need to exclude the leaf right in the left boundary in the very left boundary in the traditional instance right so with that stage so let's also look at the constraints for this problem so first the number node in the tree is in the range given by the closed interval so 1 and 10 to the power of 4. so this said that overall the tree is not now and the number of nodes is bonded above by 10 to the power of 4. the number 10 to the power of 4 gives us an upper Bound for the problem sets and the second constant is that the note value is in between negative vessels and positive resultants so in particular the node value can be zero or negative so with that side we are ready to do the analysis so here we're going to use traversal to glue the left boundary Leaf node and the red boundary together so our plan is the following we are going to write three hyper functions to achieve the following three tasks first we want to get the left boundary so here we are going to mimic the pre-order traversal pre-order traversal pre-order traversal in a second we're going to get Leaf nodes we are going to mimic the in order tools and the third one is gets the red boundary so they're going to mimic a traversal order as a right plus left plus root so let's turn this order as reverse post order traversal so here is an important note so when we do the coding we need to avoid repetition for example we need to avoid the node that is both in the left boundary in the traditional sense and is also a leaf right so in the Pro in the sense of the current problem requirement so the very left child is not in the left boundary right so this part is important we need to treat this case when we write the code similarly note that is both in the red boundary and in the traditional scenes and it's also Leaf is not in the red boundary in the sense of this problem so let's look at some illustrations before we write the code so let's first look at the left boundaries so this will going is going to mimic the pre-order going is going to mimic the pre-order going is going to mimic the pre-order traversal so this is the tree right so if in the traditional scenes actually van two three are the left boundaries so however we do not count the root and also we do not count three right so in other words in this problem 2 is the note in the um a left boundary so in this problem so if we use this definition in this problem so the left boundary is empty because the root has no left child right so this actually is according to the first atom so in this third one so we have one two three so in this tree so in the traditional stance so one and two are in the left boundary however we do not contract the root and also we do not count the leaf so this case the left boundary is also MP however the overall return for this one is one two three right we have root and we have two leaves so in this problem so the left boundary is also empty because the root has no um left child so this actually mimics an incomplete pre-order traversal in our code so now pre-order traversal in our code so now pre-order traversal in our code so now let's look at the leaf node so this is actually very simple right for example here two out of three are the leaves and in this example 2 is the leaf and in this example three is the leaf right so this is going to mimic an income an incomplete in order traversal so let's look at the red boundary so in this case so actually we do not have a red boundary so because here is a root so here's a left child so we do not have red child so this tree so in a traditional sense band three are at the left of the red boundary right so here I mean red in this part so but one is the root and three is a leaf so in this stance the red boundary is empty so in this problem in this example the red boundary using the problem order is four to one so this is in the traditional reverse sense but in the problem requirement one is not in the red boundary four is not so we have two here so with that said so we are ready to look at the code so we hope that we have again enough intuition to Reddit code with ease so I'm going to write some hyper functions so this function this functions has going to help us get the left boundary the leaf nodes and the red boundary so here at the very beginning so we're going to Define so first let's um maybe first Define this function so this functions has gone to modify a predefined list right so I'm going to call that list and say a boundary right so just to make that the overall logic is clear so first I'm going to Define DFS so let's see uh the left most so I'm going to left so in this case because in the definition of this problem we are not going to include a uh the leaf node but now and for now let's first include the node the root so that we can write it with some convenience right so if not node and so if no not note left and node red in other words if the node is now or if the node is a leaf node we are going to do nothing right and otherwise so we are going to um add the value of this node to the boundary right so we're going to use so let's use this boundary so we're going to append um node value and then we're going to check left right if node left what we're going to do is call this function DF node left otherwise so we are going to call it for the node right so this corresponds to the atoms here there's two right um this node check here it corresponds to the fourth Bridge atom right so this is the first function right and now let's look at the second function so we're going to call it DFS leaves so we're going to accept a node and then first if not node so what we are going to do is the nothing right we're going to do return otherwise we do DFS leaves um node left and then we're going to check right if note is not root right and so it's um it's a leaf so let's check its Leaf so it's a note node left and node right so in this case so we're going to add the spin to know the value uh choose a list we're going to initiate initially initialize so next we're going to call this if node right so this is the second function so this is going to help us get the node uh the leaves so also the sleeves are not the roots so the third one let's see DFS we're going to call it right so um we're going to get the right boundaries so if not node or it's not a leaf not note left add not node red so in this case so either is now or it's a leaf so we're going to return otherwise so we're going to try to do something to modify the bond and the boundary so what we're going to do we are going to first check the rate right in reversal so let's as we mentioned we are going to use uh right left and root so here if right we have red silver tree so what we're going to do is dff right so we're going to do node right otherwise so we're going to DFS red load and left yeah after we did right left then we're going to do boundary append node value so this is the three hyper functions right so lastly finish this so we can regard them as workers so what we can do is to do the problem logic so first if or not root so actually we do not need to cheat this case because the root the tree is not now so let's um delete that so let's call boundary let's denounce this boundary so we're going to have a root value and then first I'm going to get the red the left boundary so the left boundary is the dff left so we are going to do uh root left then after this so we're going to get the leaves so that is DF um leaves so we're going to apply it to root the reason is that the root is we do not regard it as a leaf in this problem so next we're going to get the red boundary so let's see it right and that's the problem logic so afterwards we can do the return after we have boundary so here so let's say boundary and Boundary yeah that's it so this com forms a solution now let's first do a check nanchep has no left so there so let's first do this so let's see because we have called this function so now let's if I'm not root so we're going to return empty right so now let's do the check remember it's line then O2 let's see uh 102 if not node and or so here I see um DF left so here is an or notice that is the logic right so let's do a check yeah it passes the example now let's look at the generic case it passes out case as we mentioned I think we could um comment out that let's do a check yes so we does that I guess that's about it for this problem so in this problem basically we used different flavors of traversal to glue the left boundary and the leaf nodes and red boundary so here in the writing of this functions we actually for example for the left boundary and the red boundary so we exclude the um Leaf right and also when we write we may do the DFS leaves so we exclude the possibility for the root right so yeah that's about it for this video thank you | Boundary of Binary Tree | boundary-of-binary-tree | The **boundary** of a binary tree is the concatenation of the **root**, the **left boundary**, the **leaves** ordered from left-to-right, and the **reverse order** of the **right boundary**.
The **left boundary** is the set of nodes defined by the following:
* The root node's left child is in the left boundary. If the root does not have a left child, then the left boundary is **empty**.
* If a node in the left boundary and has a left child, then the left child is in the left boundary.
* If a node is in the left boundary, has **no** left child, but has a right child, then the right child is in the left boundary.
* The leftmost leaf is **not** in the left boundary.
The **right boundary** is similar to the **left boundary**, except it is the right side of the root's right subtree. Again, the leaf is **not** part of the **right boundary**, and the **right boundary** is empty if the root does not have a right child.
The **leaves** are nodes that do not have any children. For this problem, the root is **not** a leaf.
Given the `root` of a binary tree, return _the values of its **boundary**_.
**Example 1:**
**Input:** root = \[1,null,2,3,4\]
**Output:** \[1,3,4,2\]
**Explanation:**
- The left boundary is empty because the root does not have a left child.
- The right boundary follows the path starting from the root's right child 2 -> 4.
4 is a leaf, so the right boundary is \[2\].
- The leaves from left to right are \[3,4\].
Concatenating everything results in \[1\] + \[\] + \[3,4\] + \[2\] = \[1,3,4,2\].
**Example 2:**
**Input:** root = \[1,2,3,4,5,6,null,null,null,7,8,9,10\]
**Output:** \[1,2,4,7,8,9,10,6,3\]
**Explanation:**
- The left boundary follows the path starting from the root's left child 2 -> 4.
4 is a leaf, so the left boundary is \[2\].
- The right boundary follows the path starting from the root's right child 3 -> 6 -> 10.
10 is a leaf, so the right boundary is \[3,6\], and in reverse order is \[6,3\].
- The leaves from left to right are \[4,7,8,9,10\].
Concatenating everything results in \[1\] + \[2\] + \[4,7,8,9,10\] + \[6,3\] = \[1,2,4,7,8,9,10,6,3\].
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-1000 <= Node.val <= 1000` | null | Tree,Depth-First Search,Binary Tree | Medium | 199 |
1,460 | all right so let's talk about the next two array equal by reversing sub array so you are given two integer arrays of equal length target in an array so in one step you can select any non-empty one step you can select any non-empty one step you can select any non-empty sub array of array and reverse it so you are allowed to make any numbers of steps so basically like how do i know the reversing order i don't know right so this is a problem if i do know that i can just using the logic behind and try to get it back so if i don't know then come on you can just use a radar sort but i don't care about what uh what's the math behind for the reversing this will be the easy way and when i compare if the array numbs are not equal then i can just basically just return both in this case right so um if the array i is not equal target i will return false y array right i will return true if they are equal and this is the solution and submit so here we go so uh let's talk about the timing space in this case so this is going to be unlocking right it doesn't matter which one is longer because they are equal length so it's going to be unloving and this is all of n so the worst case is going to be unlocked and right for the time for the space you are using a given value so it's going to be constant in this case and this is the solution and i will see you next time bye | Make Two Arrays Equal by Reversing Subarrays | number-of-substrings-containing-all-three-characters | You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000` | For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c. | Hash Table,String,Sliding Window | Medium | 2187 |
334 | hi this is truly today i will serve the problem three hundred thousand pounds their name is including three probably subsequence this description with the problem says that they're given only with all right norms and written to if their access are triple wind i said i jk sustain i is less than j and change justin k and the value at the each or each index i j k the value also the value at the i should less than the value at j and value at j should less than variate k so if we could find the values that satisfy this condition then we can written through so in this case the example number one we can simply easily find their service constant satisfied their condition one two three satisfies their condition triple conditions so it should return to but the neighbor's case the 5461 case does not meet and satisfies their condition but on the issues think about that for example three more detail okay two one five zero four six two one five 0 4 6 case in this case we can solve this problem by just using a stack first we picked the two and there's things empty so we just put the two into their stack and second the one is less than there too so we need to uh just discuss we need to just cut one but the more last value should give us more chance to get the triple conditions so we need to replace the two with 1 so the stack should be like this and third value is 5 is bigger than the one so we just add the 5 at the end of the stack and zero it also we don't need to care about the we if we replace the one with zero then we can get more chance to satisfy the condition and next value is 4. also we need to replace the pole and the rest value 6 we just add 6 so in this case the first time we met 2 and second with five and start with mesh six so two five six is one triplet and also one five six is also triplet but the zero is not f n so i what i want to say is the triple e can be consists of the value of here the first time it is c column the final value in the stack four five six but four five six does not define it but the value at after at the first time is very consistent tripling so two five six and one five six as well but the most definitely the two five six strip so because i very simply called this algorithm first we need to put some code to check there if there the given launch is not given for lump is empty way to return parts and the first value we do the glorious text and if the stack is empty then we just put the wire into the stack and if the rest value of the stack is less than the quantity varies more bigger than the rest value of the sex then we just put the value if not we need to rephrase and if the length of the stack is bigger than or equal to three then we need to return to you | Increasing Triplet Subsequence | increasing-triplet-subsequence | Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity? | null | Array,Greedy | Medium | 300,2122,2280 |
66 | hey everyone welcome back and let's write some more neat code today so today let's solve leak code 66 plus one we are given a non-empty array of decimal digits non-empty array of decimal digits non-empty array of decimal digits and so by decimal they basically mean every digit is gonna be from 0 to 9 right that's decimals any digit between 0 and 9 and this array of digits is supposed to represent a non-negative integer and our job is just non-negative integer and our job is just non-negative integer and our job is just to increment this integer by one so it seems pretty straightforward right and they basically tell us that the digit is stored such that the most significant digit is on the left side basically how you would assume that an integer would be and we can assume that the integer does not contain any leading zeros which is pretty intuitive right so for example let's take a look at this is an array one two three so this array represents the number 123. we want to increment this by one how easy is that well obviously we'd start at the right side right and then increment this digit by one so three plus one is of course four right so we change the three into a four therefore this 123 becomes 124 and then the output array becomes one two four second example is pretty similar this represents 4 321 increment the first the right hand digit by one so basically change it into a two and then that's the output array so that seems really easy doesn't it but it's a little bit misleading they don't show you one case that will basically change these two examples into difficult examples let's say that our array was this let's say this was our input array right and remember what we're trying to do here right we're just trying to add a single number so when i draw it like this it becomes a little more obvious of what exactly we're going to end up doing we're going to add 1 right so we're going to add 1 to this 9 right so 9 plus 1 becomes 10 right so can we change this digit to a 10 if we did that we would end up with 9 10 right and that represents the integer 9910 well when you add 1 to 999 it definitely doesn't become 9 000 so we did something wrong right we forgot one thing remember back to your elementary school math right nine plus one is ten right but we know that there's a carry so nine plus one becomes zero and we take a one and carry it over here right so that's what the algorithm is it's basically adding keeping track of this carry so again we're going to have nine plus one that's going to end up being again zero and we're going to have another carry over here so again nine plus one right so now you kind of see that this is this problem is not just a single addition it's going to be a while loop of continuous additions potentially right if we got an example such as this one so again 9 plus 1 becomes 0 and again we carry a 1 over here but in this case we ran out of digits notice that right we ran out of digits so what are we gonna do with this last carry one we're just gonna take it and add it over here so i know i'm kind of drawing over the elite code explanation over here but hopefully you can see this basically we got the ex the answer that we expected right when you add 999 with one you expect to get a thousand right so our output array is actually gonna have these four digits zero 0 and 1. so this is what our output array is going to actually end up being in this example and so basically these are the main cases we have to go through right if you have a 9 already here it's not going to turn into a 10 it's going to turn into a 0 and if we ran out of digits but we still had a carry we're basically going to be appending that carry to our integer array but notice how we are traversing the array in reverse order what i'm going to do though is i'm actually going to reverse the entire array and then so basically i'm going to turn it into 3 2 1 so that we can start at the beginning when we add our digit 1 to this and then at the end i'm going to take the array and then reverse it again so that we can get it back into the format that we want then we can return the array in that correct format so with that being said this is a this is you know pretty self-explanatory this is you know pretty self-explanatory this is you know pretty self-explanatory that this is an uh linear algorithm because we're having to iterate through the entire input array which is going to be size n so the overall time complexity of this is going to be big o of n we're not really needing any extra memory other than the input array so the memory complexity is just going to be big o of 1. that being said let's jump into the code it's not too bad just a couple edge cases we have to worry about so like i said we're going to first reverse this integer array and we can do that in python just like this pretty simple and i'm gonna keep track of two variables i'm gonna keep track of the carry and i'm gonna call that just one because i'm bad at naming things and we're also gonna have one other variable i for the index of the position of digits that we're currently at so one i'm going to initialize to the value one because remember we do have to at least add a single one to this digit i'm going to initialize at zero just at the beginning of the digits array so we are going to continue to iterate through digits while our one digit is equal to one and we can basically just you know say this as the condition now it's possible that our i could be incremented so much that it becomes out of bounds so one thing we're going to check is that while i is at least in bounds and the else case is going to be if the i goes out of bounds so if the i is still in bounds then we're going to be incrementing of course right but there's one case that we do have to handle one special case what if digits at position i is equal to nine that's the special case right that's the case where we get our carry integer so if this is equal to nine one is going to stay as the value one right and we're guaranteed that one is right now one like i guess i should have named this something different but this because this is gonna be the value one if our loop is executing at all so this is gonna remain one so we don't have we don't actually have to write that but as we add one to this digits of i is gonna be reset back down to zero but if we're not dealing with this special case meaning if the digit is not nine then we can ordinarily just increment it by one right so otherwise we're just gonna increment this by one and if this was not nine that means we're not going to have a carry anymore right so we can take this one and then change it into a zero because we don't have a carry anymore we don't have to continue adding anything we can take this back down to zero now the else condition is when we go out of bounds right that means we reach the end there's no more digits to add on to anymore but we still have a one value what are we going to do in that case well in that case we're just going to take digits and then append one to it right because we're adding a new digit into this digits array right and also since you know we don't have a carry anymore that means we can take our one and now reset it again back down to zero right this is going to terminate our while loop which makes sense right if we appended a one that means we don't have any more to add on to our digits array and the one thing you don't want to forget with while loops is to make sure you increment your index so i'm going to make sure to do that regardless of which if condition executes we're going to be incrementing i and last but not least we're going to be returning our digits array but remember how i reversed it at the beginning so we're going to undo that reverse and reverse it again so that we have it in the correct format that they wanted and to be honest you probably don't need to reverse this you could just traverse the array in reverse order if you wanted to but i'm really lazy and i don't like writing that code i like going from left to right so i just wanted to reverse this so this is the entire code it's not too bad when you make sure you handle the edge case of nine and you make sure you keep track of the what value the carry happens to be whether it's zero or one so other than that i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching you | Plus One | plus-one | You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s.
Increment the large integer by one and return _the resulting array of digits_.
**Example 1:**
**Input:** digits = \[1,2,3\]
**Output:** \[1,2,4\]
**Explanation:** The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be \[1,2,4\].
**Example 2:**
**Input:** digits = \[4,3,2,1\]
**Output:** \[4,3,2,2\]
**Explanation:** The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be \[4,3,2,2\].
**Example 3:**
**Input:** digits = \[9\]
**Output:** \[1,0\]
**Explanation:** The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be \[1,0\].
**Constraints:**
* `1 <= digits.length <= 100`
* `0 <= digits[i] <= 9`
* `digits` does not contain any leading `0`'s. | null | Array,Math | Easy | 43,67,369,1031 |
221 | hey everyone welcome back and let's write some more neat code today let's solve one of my favorite interview questions maximal square according to elite code it's asked by a few companies including google and also including huawei so i like it because it's actually a pretty simple problem so we're given an m by n matrix right so in this case it's 5 by 4 and it's filled with some zeros like this one and some ones like this one we just want to find the largest square we can create that contains only once and then return the area so if we look at the drawing like this is one square right because it's one by one but this is not a square right it's one by two that's not a square it's a rectangle but not a square we have one two by two square over here and we have another two by two square over here we can also make this three by two but that's not a square so we don't count it so the biggest square we can make is a two by two so we know that the area is going to be 4 which is what we return so it's pretty easy when you're looking at a picture right like when you just look at this you can tell that this is the biggest square we can make but how do you do this with an algorithm well in this case we have a four by three grid right what's the what's one brute force way we could do this well let's consider for each of our one by one cells let's consider that this was the top left corner of our square what's the largest square we can make where this one is considered the top left well clearly we can at least make a one by one square with this right because this is a one so what happens if we try to see if we can make a two by two square where this one is the top left well what do we have to check okay can we at least make a one by one over here and can we at least make a one by one over here we see that this one is not a one so then what does that tell us that tells us if this is the top left corner then the greatest area we can do is one by one which is also just one right and what we can do now is basically repeat that process for every single cell in the grid so for this one we see it's a zero so we can't even make a one by one square with this so we don't even have to check the neighbors now this method is going to require some nested loops right so some for loops some more for loops we're going to have to starting at each one we're going to potentially have to go through the entire grid and the time complexity of that is going to be let's say that the width is m and the length is n so that's going to be m times n because we have to go through the entire grid right so we're going to go through the whole grid and we're going to do that for every single cell in the grid so it's m by n squared that's pretty inefficient right big o of this is not that great so is there some way that we can do better than this so with a problem like this it's good to ask is there any repeated work that we're doing or even can we break this down into sub problems so if we're looking for the largest square that we can make where this is the top left corner we know that if theoretically just looking at the grid the largest would be a three by three right because that's the biggest square we can even make starting up here what about this one this theoretically the biggest we can make over here is a two by two because there's not even any space down here if we try extending it to the right it's no longer a rectangle it's no longer a square right if we want the largest square we can make starting up here let's first check down here what's the largest square we can make starting over here and let's also ask what's the largest square we can make where this is the top left corner and also we know that we got to check this one too what's the top what's the largest square we can make starting here so we're breaking this down into sub problems right if we want to solve the problem up here then we have to solve the sub problems as well and if we want this one if we want to know the largest square we can make starting at where this is the top left we gotta check down here we gotta check diagonally over here what's the largest square we can make where this is the top left and we also have to check over here but you see we already did that so this is the repeated work we don't have to check this twice so the solution to that is i'm gonna create a cache and if we want to know what's the largest square we can make from here we also have to check the sub problems now notice we go down here well we don't need to go here twice right we already went here starting from this direction so we don't have to repeat this work this is repeated work so i don't have to check down here again but i do have to look over here i have to know what's the largest square i can make from this position as the top left and i also have to check over here because we have not checked this one yet either now last but not least we have to look at this one as well we took to make this as large as it can be we have to check below it but we know we already did that we have to check diagonally but we see we already did that and we also have to check to the right which we have not done yet now just bear with me a little bit longer because we're almost done so starting from here we have to check below it but we see there's nothing there we have to check diagonally but we see there's nothing there we have to check to the right but we see we already did that and now starting from here we're going to do the exact same thing and the process is repeating right we see we go here we already checked that we don't have to so starting from here we go below diagonally and to the right which we have not checked yet but we can see we're starting to get to the base case right and then we just have to do these two as well we look down we are we've already visited that we check diagonally we've already visited this we go to the right we have not visited this yet and this is the last one we have to look at we look below we've already visited that diagonally we've already visited that to the right we have not visited this and now we don't have to check any of these because they're not real cells this one will look below we've already done that diagonally there's nothing there to the right there's nothing there so what does that tell us about this cell so i'm actually gonna draw the output right i'm gonna draw our cache and what this cash represents this cash is going to represent for each of these rec each of these cells what's the max area we could get where this is the top left position when we look at this one we see there's no space there's no cells anywhere whether they're zero or one there's nothing here so the largest we can make at this position is a one by one and the area of that is going to be one now let's look at this one we're going to be going in reverse order right so we're going to start with these red ones then we're going gonna look at the pink ones then we're gonna look at these dark blue ones and then finally we're gonna get to the top left most position so we're gonna look at this in reverse order and see what happens so for this one it has nothing to the right nothing diagonally it does have a one below it so we see that we can't make anything bigger than a one by one over here so in this position we're also gonna put length one so for this cache i'm actually gonna put the square length not the area itself just because it's a little bit easier lastly we check this one we know that there's a one below it but there's nothing diagonally and there's nothing to the right so the largest we can make with this is a one by one so this is part of our base case now we're going to start looking at these pink ones and let's start over here so we know there's nothing below there's nothing diagonally there is a one to the right but the most we can do with this is a one by one the exact same thing is going to hold true for this one we can only make a one by one and the exact same thing is true for this one we can only make a one by one next we look at this zero now this is the interesting part if we look below there is a one if we look diagonally there is a one if we look to the right there's also a one but this is a zero so starting at the top left with this we can't even make a one by one so we're gonna have to put a zero here the last pink one that we have to check is up here we know there's a zero below it there's a one diagonally and there's a one to the right unfortunately this zero limits us so the most we can make with this as the top left is going to be one now we're going to start looking at these dark blue ones starting with this one we look below there's a one we look diagonally there's a one and we look to the right and there's a one and also the value in the cell itself is also a one so we know that this is a two by two next we look at this one below there's a one diagonally there's a one but to the right there's a zero this is getting really messy now but we're almost done so we know that at this position the top left we can do is a one and for this zero we know we don't even have to check down right diagonally because this is a zero the largest we can do is a zero okay and the last one we have to check is the top leftmost one we're gonna do that last we look below and actually you can check over here we know that the biggest you can make here is a two by two the biggest over here you can make is a one by one the biggest you can make here is a zero so since there's at least a one here though we know we can put a one here so now we've transformed this into new matrix will tell us for each position what's the max square we can make at that position as the top left corner and now we can just basically iterate through each position like checking each one this is a one zero one this is a two this is a one zero one so we know that the biggest is two so therefore the max area is going to be two by two because it is a square and we know two by two is and because we are using a cache so we're not repeating work even though in the picture it looked like we were repeating a lot of work we're not actually doing that so the time complexity is actually going to be m times n because we're really just scanning through each position in the matrix and then when we have our output we're also doing that same thing we're just checking each position to find what the maximum is so now let's code it up and you might have noticed that this is a dynamic programming problem it can be solved with dynamic programming which is considered bottom up i think and we can also do it recursively in that case it's top down most people will just skip to the dynamic programming solution so i'm actually just gonna show you the recursive one so first i'm just going to get the dimensions of this matrix just so we can store them when we don't have to keep getting them so to get the number of rows we can just get the length of this matrix and to get the number of columns we can get the length of one of the rows also we know we're going to be doing some repeated work so we're going to store the result of that work in a cache this is a hash map in python and we're going to map each position so each row column position to the max area of that position basically and i'm going to do this recursively since our original function max square only takes one parameter the matrix i'm going to get a helper function that we can pass in the row column position as well we don't have to pass in the matrix because we can access that because this is a nested function basically right so as in most recursive functions first i'm going to check the base case if our row is out of bounds so if r is greater than the number of rows we have or if the column is out of bounds we know that the max area we can get is zero or even the max length now if this row column pair is in bounds first we're going to check if it hasn't already been computed and stored in our cache if it has then we know we can just say this right return cache of that position row column pair meaning we already computed the max area at this position but if that's not the case so if row column is not in the cache then we have to compute it now how are we going to compute it just like we did in the example we're going to look first we're going to look down so we're going to recursively call our helper function in the down position how do we get that well we can just add 1 to the row because adding one takes us down a position and we can stay at the same column we also want to check the right position what's the max area we can get in the right position so recursively we will leave the row the same but we're going to increment the column so we can check the right position lastly we also want to check diagonally meaning bottom right so downright which we can increment both variables so remember when we call this function we're trying to cache what's the max area in this position initially we can just say zero right that's just the initial value i'm gonna give but how do we compute it how do we know if it's more than zero so this is one little tricky part you have to notice that in our matrix these are actually strings so each one and zero is a string it's not an integer so we got to do some annoying stuff so first we want to check at this row column position is there a 1 or a 0 in our matrix so we can check if matrix at row column is equal to one but this is a string so we got to put some quotations around it so if it's a one that means that this area is at least a one or the length is at least a one so what we're gonna do is say okay cash in this position is at least one plus whatever the minimum of these three is right because if one of them is a zero then the max we can create is a one here but if all of them are one if there's a one in the down position a one in the right position and a one in the diagonal position then this is going to be one plus one right so in python it's pretty easy i can just take the minimum of three values down right diagonal and i actually made a slight miscommunication so we said we were going to map these to the max area but i'm actually going to say the max length of the square so i hope that's not too confusing so in this case if there's a one here and the minimum of these three is a one then we're gonna store a two in this position but what that means is the max square we can get is two times two which is going to be four so now we've defined our helper function but we haven't actually called it yet so i'm going to call it first i'm going to call helper passing in the top left position which is 0 because we're going top down recursively and once this function has been called we know that our cache is filled with for each position we've mapped it to the max length of the square at that position so if i get all the values we have in our cache meaning all of the lengths that we computed that's what this gives us so cache.values is giving us cache.values is giving us cache.values is giving us a list of basically all of the max lengths i can take the max of that entire thing so the max of every position and then i can square it because we know this is the length not the area so we're going to square it and then all i have to do is return this value and i also want to say that the time complexity is big o of m by n since we're also using a cache we also have extra memory complexity which is big o m by n as well i'll say that the dynamic programming solution once you know how to do this is not much more difficult you don't need to do it recursively you can use a loop and you can go bottom up so and you can also actually use the matrix itself as the cache in a way which saves you a bit of memory so we basically get rid of one of these dimensions for memory if you're doing the dynamic programming solution i hope this was helpful it's a tricky problem but it's a common interview question and i hope this was helpful don't forget to like and subscribe it supports the channel a lot and hopefully i'll see you pretty soon | Maximal Square | maximal-square | Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_.
**Example 1:**
**Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\]
**Output:** 4
**Example 2:**
**Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\]
**Output:** 1
**Example 3:**
**Input:** matrix = \[\[ "0 "\]\]
**Output:** 0
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is `'0'` or `'1'`. | null | Array,Dynamic Programming,Matrix | Medium | 85,769,1312,2200 |
1,036 | 10:36 escaped a large maze in a million 10:36 escaped a large maze in a million 10:36 escaped a large maze in a million by a million quid the coordinates of each grid square XY with civil is with x and y between zero and a million we started the source square and want to reach the target square each move we can walk to a four directional directionally adjacent square and the grid that isn't in the given list of box squared we turn true it's reachable to the end essentially okay so I think the thing that they try to get you here in this problem is that N is a million way or I guess in this case yeah and it's a million base and square human right so and that's what a thousand billion it's a trillion okay yeah so it's like a trillion right so you can't do way now you think things let's see blah so there's only 20 spaces that I bought yeah so you don't have to worry about like I don't know anything too crazy and blogs okay cool yeah I mean I think a way a really a basic way to attack problems like this let's say you don't have a million by million there and you have like you know some other end then you can solve this by like that for search of binary search of weight very simple connectivity problem and it's not even distance or in the sense that usually not usually but sometimes they ask you for like what is the shortest distance from X to Y or something like from X well point A to point B way and in this problem so this is just an extension of data is accepted as a million by a million right so I think what I would say and there's only 20 block lengths and that is a number that jumps at me and what I would try to attack on this problem is kind of well like you have this million by million quid but you could actually come because you are you don't have to care about the distance then if you care about the distance you can still figure it out actually it's just that you're probably have to use like some kind of dice tree album instead of black research but you actually compress the graph because most of the graph is empty right and that's what I'm going to do here where and well and you may ask yourself like well what does it mean to compare to compress a graph well because what dot length there's only 200 black points that means there's at most 200 unique X points right 202 of you want to count just zero and 1 million or something like that depending on uh well 202 we want to count the source and the target there we go right but so yeah so that's kind of and now your end when you come so basically you would think about it as all the stuff like between two points like in this case not this case but you just compress over to space and then and now you have a 200 by 200 grid instead well Toni on two by Toni on two grid and then dad is only like what forty thousand cells so where you use it do the prep for a search so that's what I'm going to do here yeah what I said hopefully that was understandable if not hopefully Mike holy explains in a bow so explain in the end definitely feel free to ask some questions yeah Coenen our coordinates I guess coordinates but I mention no how about it maybe I just ate it through this tent it should be okay wasn't sure actually maybe that would've been okay anyway if you're in Python definitely let me know maybe I would have done this in this queen away sometimes I worry about the order of operation that's all also pi should keep a counter instead of doing this all the time I hope length is constant or maybe I'll just keep a counter it's finding more responsible thing to do oh yeah I mean basically it's just that blocked is a list of ends and then I just this is a pen stuff I mean not quite a pen but it's just so that I go for the entire thing well I don't know that make sense enough already but basically it's just instead of doing like you can imagine a Paulo way of doing it's me doing this you know code here not this like infarct and then the same code for like for coordinates and I think this is understandable hopefully right like it's just put some another so that you do the code for each of those source and the target you know same code here right yeah so then now here I just doing one away because for now I don't care about it because this code just Maps kind of a coordinate to a compressed coordinate if you will so basically what I'm doing here just to explain this a little bit is like okay let's have one fun and you can even sort these I don't think I don't know actually now it does matter whoops because then it would be not in the right order my dog sorted good cache stuff I've ever wanted hopefully but up basically let me explore finish a clever idea five one six twenty five so for something like this right well now we will what I want to do is compress this to one two three four oh it's technically still indexed say so actually some just this and that's what my code is doing so dad like it compresses two numbers together except that's not what my coach doing because I forget to sort but that's fine let's just do it yeah okay fine and this way yeah and the way I do this is so that I don't forget to map their Exxon device and the source and the target to know this or know you could actually do something functional in this actually but I you can refactor this but I already had it way now to just being a helper on because it's just on XS and X mapping way so yeah actually find out if you factor it you try to be there yeah whatever and I actually won come on tiny Texaco I guess huh well I guess not really at the end I should just take this out it's more effort to write so basically now just allow us to do come back everything together and then now it is a straightforward ish prefer search or theft research whichever you like but for 40,000 elements I guess I worry a for 40,000 elements I guess I worry a for 40,000 elements I guess I worry a little bit about which record stackoverflow so yeah so now we want to append mapping and I guess startling that we do is now provide a bot hookup but that's fine like these are things that when you encounter it's like a few lines so okay just let's just convert on a map no map is a just name that's just food saucepan new coordinates which is that's just X you told me is they gonna have a good to them look up easily oh this is actually a list not a top of that's annoying pay it that's fine doesn't really matter okay and now we want to look up table for what this is one of those things where I feel like we've really good Empire fun you get to in one night or maybe even just moderately because maybe I could do it hang on yeah okay that it's not that bad that's for fun that's gonna be the new part mmm yes that way I start from 0 and integral 0 to 4 waste of one I know this a no this Stephanie uh definitely feels wrong Oh hmm well I just didn't I think I said it out loud but I didn't actually sort it okay whoops I think I mentioned it like three four times I just did the reef fact and then do it okay there you go that makes sense and just for kicks we could see what happened well there's no part on this one so maybe that's not interesting anyway so I was just simple native okay well you know just well it's where you stand it would I want action static know why and then now everything is in the new coordinates so now we have to do that directions right where was it is it just okay for directional okay so now we just do that for this I recommend having a systematic way that you typed it the same way every time is that sometimes I miss it if I don't but okay so now this gets popped off if no and I guess it just ends with just being cue list and just returns force well actually I think one thing that I'm just looking for now is what happens if you try to go out there having that is an edge case because I'm not out of balance bed but if you try to like of you I think the way that we've compressed a map you actually said two boundaries at left and the right by accident after the min and Max elements but what we actually want to bound by is there's several elements oh okay zero and yes this is it okay yeah it's less ten so yeah so now to put these elements India so yeah so this way if you think about it as a box these two numbers were always compressed to you know the well zero would always be compressed to zero for the first element and 9999 luzie the last element whatever that might be so now we can so then was one edge case I'm thinking about is that like if you have someone like I'm just drawing dots and whatever but like that's how you're trying to go from here to say here and then now you have brought here if you compress it and then you don't go outside the bounds then you can get there but the obvious value is to go you know to go left and the Dow and then around way it should be up space which my initial case Dylan to kill so that's why we needed to add these things here so that the mapping handles it correctly cool okay yeah for down reaction okay make sure I get this way better I wish there was what you might call topple addition something that I always like in theory okay now we just have to check that this isn't bound this is actually where we need to this is actually not good we need this because wow that's the way we did it we actually did do so mmm that's just cash this is this shouldn't change afterwards oh good well if they're not import what did I do this I mean it's sensible but actually we want a hash table or a set let's do a set actually and also we haven't seen it before them let's just say we've seen it before and then we move to it by pushing it and now we can also terminate early by if you know key is you go to new target then we turn true that's it hopefully that's it very my screen is a little dirty okay well it's good to get at least one case right let's try this case that we talked about which is necessary doing this is actually the same as the first one except for that's just offset it by 1 and this should be good or should be true well yeah if not that maybe I just misunderstand upon so it's a good test to know obviously on the contest you may not get that you don't get a response back sir hmm joking it's a little ooh that's a good oh okay so it's not me okay let's just save okay cool yeah didn't I explain this problem okay now if not priest into well oh yeah but I think two trickiest part about this poem it's just gonna take about 20 minutes I was talking to it but yeah right but I think the hardest part about this poem is just kind of compressing the space I mean other than that because after that is dynamic I mean a platter when you go so choose your favorite search as long as research maybe a little bit at Casey on the things but I think that actually may be a case that they try to get you on actually and I guess this case but otherwise straightforward once you've got the space compression and kind of mapping them in a good way and this is a pattern that I've done a couple of times so I am but the idea is yeah given like let's say these are your x coordinates of all your points are so they could be repeated you know in some way and they sort it because well if they're not just sorted here and I guess our so it contains this yeah you're just mapping it so that now you know this is civil one this is still one but two three four five six seven right so there now these are your points on your x coordinates and then we just have a lookup table that allow us to map it or figure out like okay this is this and that's pretty much it and then you have two Y coordinates which is the same and then now you just do your breadth-first now you just do your breadth-first now you just do your breadth-first search on your new grid graph yeah there's a lot of typing I mean I well this was typed this way just because I don't know because I was copying from nothing but it definitely could have been a little cleaner I mean it's 61 lines which is a little bit long I miss fing about when oh yeah for kind of complexity where n is the number of block length this is N squared because that's the most space and buffer searches linear quest that's the number state so it's n square just trying to think whether like you would see this on individual I would say definitely breadth-first search you see definitely breadth-first search you see definitely breadth-first search you see the first search stuff on an interview or you know I did that for Social Research I think on interviews fresh air if you're by boiling you could actually do recursively and because you don't have to worry about Stack Overflow things though the caveat is I would also double check and aster asked interviewer first but like I am I'm gonna try to do this but their first search I know is recursion and I know that there's a possibility that my overflow is that okay and some like that way communication is probably the number one thing when you don't interviewer just you know don't try to guess what you're in the we were one just ask usually they don't penalize for you they don't penalize you for it unless you're like asking for how to solve the problem type things very obviously but if you have two or three different approaches and you kind of analyze them and talk about the complexity and stuff like that and you want to choose which one they implement I think just ask us why and he's at the higher level I mean with this one otherwise yeah I mean this is a lot of typing but I think the core concept of it the two components may be a little bit separated out is definitely you know breadth-first search and search problems breadth-first search and search problems breadth-first search and search problems are very easy to give and get on interview so don't expect that and the space compression i've seen a couple of times I don't know how yeah I don't know how often that comes up an interview and I've seen no compounding you know these can't read Co things but I don't know if I've ever heard someone really done it so I don't know but that may just be me let's not take a quick look and hint before I met his father we come started some new problem just wow yeah that's what I was saying come on Italian there's something fun to say what's the maximum grace you can have maybe there's a more clever way around it I don't know maybe there's a mathematical solution yeah I don't know maybe there's some I guess this so I definitely with space compression and breadth-first search because it applies breadth-first search because it applies breadth-first search because it applies to more stuff but I think what these hints are saying is that there's a way to like just search the space around it because I think if you have 200 watt that means you only have to search actually I think that's a clever solution as well that I did not do but which may be worth kind of exploring is construct a graph or whatever or grid of just like you know your starting point and like 2 3 or 200 points to laughs windup down or something like that I mean I guess that's where you your mouth is trying to go or actually I wouldn't be that it wouldn't be done Tiger graph would just be like if you imagine like a grid where you know you have to Manhattan distance so you have like essentially like a time and evening given the block length so foot so you do math on that and kind of then you could after two hundred steps or something like that like you're always gonna be done and that's only on one side right so you have to like do some math quit but I think that their point is that yeah at some point you can actually just return true because they can't hold you in you do like an ibuffer search to some distance and that's something that you get for binary but obviously did the way that I did it you can extend it to you know dice try to get the distant much easier though maybe now maybe just a few more education in early case but uh yeah Oh wah cube bomb but good luck you get is on any of you but yeah | Escape a Large Maze | rotting-oranges | There is a 1 million by 1 million grid on an XY-plane, and the coordinates of each grid square are `(x, y)`.
We start at the `source = [sx, sy]` square and want to reach the `target = [tx, ty]` square. There is also an array of `blocked` squares, where each `blocked[i] = [xi, yi]` represents a blocked square with coordinates `(xi, yi)`.
Each move, we can walk one square north, east, south, or west if the square is **not** in the array of `blocked` squares. We are also not allowed to walk outside of the grid.
Return `true` _if and only if it is possible to reach the_ `target` _square from the_ `source` _square through a sequence of valid moves_.
**Example 1:**
**Input:** blocked = \[\[0,1\],\[1,0\]\], source = \[0,0\], target = \[0,2\]
**Output:** false
**Explanation:** The target square is inaccessible starting from the source square because we cannot move.
We cannot move north or east because those squares are blocked.
We cannot move south or west because we cannot go outside of the grid.
**Example 2:**
**Input:** blocked = \[\], source = \[0,0\], target = \[999999,999999\]
**Output:** true
**Explanation:** Because there are no blocked cells, it is possible to reach the target square.
**Constraints:**
* `0 <= blocked.length <= 200`
* `blocked[i].length == 2`
* `0 <= xi, yi < 106`
* `source.length == target.length == 2`
* `0 <= sx, sy, tx, ty < 106`
* `source != target`
* It is guaranteed that `source` and `target` are not blocked. | null | Array,Breadth-First Search,Matrix | Medium | 286,2206 |
1,819 | hey what's up guys uh this is chung here so uh this time let's take a look at this one okay 1819 number of different subsequencies gcds okay so you're given like an array numbers right and consists of positive integers and your task is to return basically the number of different gcds among all the empty subsequences of nums so the gcds of course you guys all know that it's a greatest common divisor right so for example the gcd of this four six uh 16 is two right it's the greatest common divisor and our task we need to find all the subsequences the distinct value of the gcds among all the subsequences so for example we have these nums here right so the length of three so in example one here we list all the possible subsequence and the uh and here are the corresponding gcds for out for each subsequence and in the end we have one two we have uh five distinct gcd values that's why the output is five right and here's another one and the constraint is like this ten to the power of 5. right so i mean at the beginning right so if we follow the examples we'll follow the description of the of this problem by calculating uh sub ogcd for a subsequence then we need to basically enumerate loop through all the subsequence of this problem and given this kind of uh constraints it will definitely tle right because the subsequence is like a combination right well yes like combination of all this kind of each of the entire numbers which will be too large to be uh to be enumerate right so that's why you know we have to somehow figure out a different way a different strategy to solve this problem and you know to stop to be able to do it we have to be able to make some observations where we have to be to know some of the characteristics of the gcds so the first things is this so given like the range of the numbers so the numbers the biggest number is 2 times 10 to the power of 5. so what does this one tells us tell us it tells us the range of the distinct value of gcd is from 1 to this 2 to the power of 5 right because the gcd can never be greater than the number itself that's a fact right so which means that you know with this given range i think we can just actually enumerate each possible gcd value right and then we check with that gcd value is that given that gcd value can we find a subsequence let me find a subsequent that can have electricity of that value and if that's the if that's true and then we simply increase the answer by one right for that specific gcd value so now the problem comes down to given like a gcd value uh x let's see all right given x as gcd as you see the value right how can we find a subsequence that has this value x as a gcd right so to do this we also need to know some we also need to make some observations again so first you know the possible subsequence the order possible numbers that can form this g axis gcd is a it must be the multiple of x so what does this one mean it means that let's say for example if x equals to four i'm just using this as an example right so the possible gcds the possible like sub the possible sub subsequence that's going to form the conform can have this uh fourier gcd is what it's a four eight 12 16 20 24 and then so on so forth until the uh the limit of here so this is kind of obvious right because you know only then we can have we can we could possibly find like a subsequence from here whose gcd is four otherwise you know if we have like a nine here you know that knight definitely will not give us like a four because you know the gcd what is gcd it's a divisor right so divisor means that you know we have to be able to find to be divided right that number has to be divided divide divided by this uh by this x here that's why the potential candidates of the numbers are all the multiple of this x value here so that's the first observation and the second one given this kind of like a possible candidate and the gcd depending how many depending on which uh numbers we're which number we're picking here you know the possible gcd values of that any subsequence can only be either greater than x or equal than x and so the this is also kind of uh not too hard to realize that because you know let's say x is four right so no matter how which number we pick no matter which number we pick from this uh candidate here know how many numbers you pick the gcd will at least be four right let's say if we pick eight and sixteen right so obviously so for eight and 16 the gcd for this two number is eight right eight is greater than four right but if we pick the uh eight and twelve right so then and eight and twelve right so then the gcd of this these two numbers is what is four right so given like this kind of the multiple of this gcd here you know depending on which the what are the subsequence we pick right which numbers we include into our subsequence the gcd will only be either greater than x or equal to x and the last observation is that you know the more value the more numbers we include into our subsequence the smaller the gcd will become okay so what does that mean let's say we have 20 and 40 right so at the beginning you know let's say we only pick these two numbers obviously the current gcd of these two numbers is what is 20 right now if we include more numbers it did include more numbers from this of course from this kind of candidate space here you know the gcd will only go going down so let's say we pick uh 10 sorry not 10 actually uh let's say you if we add 80 uh you feel like at 60 here right so by adding a 60 here you know actually the uh the gcd will stay as it's 20 right basically it will not uh decrease but if we add uh let's say 16 in this case yeah if we add like 16 here i believe this if we include 16 here so the gcd for this one it's gonna be actually so yeah if i had this one the gcd will become to four in this case right yeah so this is the basically that's the another like uh fact that you know some of the more values we include from this candidates list the smaller the gcd will become and the smallest it can get is the x itself right so and then okay we find like a solution already basically you know for each of the x here we will we'll get all the candidates of this x which is the uh the multiple of x from the x itself to the limits and then we'll try to build the gcd we'll try to include those uh numbers one by one of course we also need to check if this like number exists in this uh in this num number itself right so if it exists then we'll basically will try to include that subsequence so include that number into our subsequence and we'll try to calculate the uh the gcd for all those kind of uh the worst case scenario is that we have to basically include each number into our subsequence and then we'll see if we can find like the gcd equals to x because like i said the more numbers we include inc into our gcd the smaller the gcd will become right so basically so what it means that if we have include all the numbers from this candidates list and the gcd is still greater than x then it means that you know we cannot find a subsequence from these nums whose gcd is equal to x all right cool so i think that's the logic and so if we have find the logic here actually the coding is pretty simple you know so first you know we need to find the limits right so for the limit actually we can do this so we don't have to use this we can either use 2 10 to the power of 5 or we can just do a max of number of the numbers right and yeah so basically we're getting the max number because that's going to be the limit upper bound of the gcd values right and then like i said to be able to find if the number exists in these nums here we're also going to create like a num stat right so that the check can be a one time okay and then we have answer equal to zero right and then yeah we have i in range of one to max plus one right so that's going to be the check range for each gcd value okay oh and for to calculate the gc gcd first subsequence you know i think this is kind of also kind of obvious because let's say we try to include the numbers for 4 8 and twelve right so to calculate so first we'll calculate the gcd for this two you know so the gcd of this uh so the gcd of this three numbers equals to the gcd of the first two numbers right the gcd of the first two numbers and then for the third one we also we can simply do another gcd on the result of the first gcd plus the card number that's going to be the gcd right of the three numbers because the first one is four the four of gcc of 12 equals also equals to four right that's how we calculate this gcd okay so now which means that you know i can just do a like a current gcd here right let's start from zero and oh this is going to be x right so and then for each number in the range of the x of the we need to find out the multiple of x right and the max plus one and then the step will be x itself right that's how we find all the uh the multiple of the current x from the uh within the range and then we check if the number if number is in the num set right so if this one exists in the current numbers here we're gonna update our current gcd because the gcd of current gcd of num right like i said you know so the more numbers we include into this uh into our current gcd the smaller it will become basically it will only go going down and the smallest it can get is the axis x itself so we can have like simple uh we can do an early termination you know basically if the current gcd is equal to the x right then we increase the answer by one and then we do a break or we don't have to do this or we just simply find all the possible multiple numbers uh in this in these nums here and we just do a gcd among all of them because like i said you know the smallest it can get is the is x itself if we include all the numbers you know right so if in the end it still cannot find the gcd if this in the end the gcd doesn't equal to x then pro or simply just uh ignore it will simply not increase that so here just like early termination or we can just do so let me or we can just uh in the end i we do this right so if the current gcd is equal to x right and then i increase the answer by one this is a this is the same thing right here just like a little bit of termination because you know since it's all it's only going down and as long as it has reached the uh the number itself you know we know okay we don't need to include more numbers because that's because we have find the smallest uh number that gcd could ever get right yeah i think that so that's the basic idea so for the gcd i you can implement yourself right so the gcd is very kind of straightforward basically we have a and b here you know right so while b this is a template basically and then we do a equals to a b equals to the b and the a modular by b right and then in the end we return a that's it so the reason i include this gc uh current dcd a defined size 0 is because you know with 0 with 3cd zero to any numbers so zero gcd zero and any number x the value is x itself right so you can take you can just verify it so if a zero b is x you know so b is not empty another m d so the b will be big x will become to a and the b will become to zero so that's why we just stop we return a so if b is zero and a is x uh we simply will not enter this while loop and we simply return the a itself right that's because you know at the beginning if there's no gcd at all right i mean the current gcd will be that will be the number itself that's why you know we define the current dcd start as zero as the initial value cool i think that's it right so now and we just run the code i think current oh i think there's a typo here current yes current so accept it right submit yeah so it passed right so the reason it passed is because the time complexity you know so what's the time complexity for this so at the beginning at the very outer loop uh we have like n here right assuming n is the ten top ten to the power of five right and other loop is n and for the inner loop is so this one is a little bit tricky because you know for each number depending on the number itself right i mean depending on the number so here it's more like a login because you know for when the one when the x equals to one right here it will be n itself right and then when the x equals to two uh it's going to be uh and divided by two right so when the x equal to three the number of the inner four loop will be undivided by three so on and so forth so actu so it's so this one is close to what it's close to unlock and actually right unlock it and that's going to be the tool uh the two loops time complexity and for this gcd here you know i think for gcd we uh um someone think this gcd is off one you know some might think this one is a it's a login because here as you guys can see it also basically uh do a modular of while so this one is also similar with the login so um depending on how we measure this gcd function itself you know so it could be at base we have a log n so here we have a another login based on this gcd function here yep i think that's it for this problem right i mean it's a pure math problem you know uh to solve this one we have to know some characteristics and facts regarding the gcds you know like the uh the only possible so the first one like i said you know the first for given like a gcd here you know the possible numbers that can have this x as a gcd is like the multiple of the zags here and the second one is the so the more values the more numbers we include into our current subsequence the smaller the gcd becomes and the gcd can only be as small as x itself right if we are like trying to find the among other multiple of the acts here and then yeah there you go cool i would stop here and thank you for watching this video guys stay tuned see you guys soon bye | Number of Different Subsequences GCDs | construct-the-lexicographically-largest-valid-sequence | You are given an array `nums` that consists of positive integers.
The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly.
* For example, the GCD of the sequence `[4,6,16]` is `2`.
A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
* For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`.
Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`.
**Example 1:**
**Input:** nums = \[6,10,3\]
**Output:** 5
**Explanation:** The figure shows all the non-empty subsequences and their GCDs.
The different GCDs are 6, 10, 3, 2, and 1.
**Example 2:**
**Input:** nums = \[5,15,40,5,6\]
**Output:** 7
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 2 * 105` | Heuristic algorithm may work. | Array,Backtracking | Medium | null |
349 | foreign we know that 2 repeats spicier and two repeats tires by CSU intersectional Commodore the resultant array should be unique so 2 is uh written only once here if you see 495 here okay 4 is present so 4 is intersection then 9 also present in the second array so these two other elements which are in the intersection so we could see whichever element is present in both the rest they are the intersection arrays and we written them only once so the concept come in unique is function you could use it so we know that set contains a name that's a difference between set and list may have uh repeated elements but duplicate elements but set will have always unique elements so that's why we'll use set here we will have one set called set one so for this set one we will add the elements of array1 so the arrayment contains 495 so is there any duplicate Element no so set one will also contain 4 9 and 5. so now other set we'll create call set two this is the resultant array uh logically if you say so set 2 will contains elements contents now promise to the secondary go to nine check if 9 is present in set one if it is present in set one that means this element is present in Array one also yeah 9 is presenting uh so what you can do you add the nine to the resultant set to X go to 4 check whether 4 is present in set one yes it is present so add that as well to the set then again nine is present in set one but it's already present in Z2 as well so it will not um elements X move to eight so eight is not present in set one so it will not add it coming to four is present in second but it's already presented set to as well so these are the elements which are in set now this is the intersector uh set but we need array as a result so how do we get the array as a result we are not directly using array because one thing is a duplicate element another thing is we do not know the size of the resultant array so that's why we will create set to and add elements between unique values so it will automatically add your request then later you convert this to say uh so now create an array resultant of size set dot size so once you create the array of this now each element in set add that to the array so create the index equal to zero so each time you do index plus so array of index will be equal to early element in the set that is how you solve the problem so two arrays you have you create set one add all the elements in the array to this for that you add those elements I mean by traversing the array2 and check whether that element is present in section or not if it is present settlement you add it to set then you convert it set to end one all right result so that's how you solve a problem now I'll create set of type integer set one equal to U hash set same thing but in this case we will have set 2 that is a result and set HG so new hash set now for each number in numbers one set one dot add off so add all elements in the set one so while traveling to the set two I will do how do you do is for each element in the array so again for now it comes to in this case we have to check if set one dot contains of then what do we just added to the set to dot add-on so after this you have resulted you have to convert into array so index will have equal to 0 and I'm going to create a record result or something so we'll create a array of type integer let's name it as result equal to new end of the size of the resultant array is set to dot size so next adding elements to the setup so again Travis to set for now each element in set to result of index foreign so instead of doing here we can add a over here itself so you know this will what will do result of index it will assign the normal basic result of index then in next we need to return by 1. so at last you return the result okay spelling stock is successfully submitted if you understood the problem please like the video and subscribe to our Channel and keep learning thank you | Intersection of Two Arrays | intersection-of-two-arrays | Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000` | null | Array,Hash Table,Two Pointers,Binary Search,Sorting | Easy | 350,1149,1392,2190,2282 |
546 | hey everybody this is larry this is day 14 of the august eco daily challenge hit the like button hit the subscribe button join me in discord let me know what you think about this really tricky problem we've moved boxes so i actually really recommend um watching my video on 2x um not right now but i'll do the explanation first as you can see from the runtime that this is a very long video but actually to be frank i actually wasn't didn't spend that much time on it's just that i spent a lot of the time thinking there's an n cube algorithm but it turns out that the optimal algorithm is end to the fourth so and i actually had an end to the fourth album very quickly so maybe not that quickly but i did stumble uh across different ways of doing it so um so definitely watch that um first of all i am doing this explanation live so it's a little bit slow fast forward to whatever you need to do um i am going to do this explanation now but i do actually like i said i think i do i did not remember this problem enough as you can see because it took me 90 minutes to do it but so at least in the first 20 minutes or so you can kind of see my dark process about this problem and kind of getting it from dynamic programming and kind of get it through so i definitely recommend watching that um and for this one i would also say that you don't get if you don't get this one it's okay work on other dynamic programming problems first there is the so my explanation is going to assume that you have a good working knowledge of dynamic programming and for me yeah the first thing that i would think about is um yeah and it's gonna be a little bit too tricky for interviews and also it's very one-off e you'll notice a few that very one-off e you'll notice a few that very one-off e you'll notice a few that way um some of that is as i said because i thought that n to the fourth may be too slow but it turns out to be fast enough if that was the case i actually would have gotten it much earlier but that said you know you can kind of watch my video to see what i did but anyway um yeah so for this one the first thing that i notice uh is and you can watch this in the video is that there's gonna be n square or like i diagnosed the n cube solution very quickly but the thing about these dynamic programming problems is trying to do it in a way such that you're effectively doing a brute force but in a smart way um but yeah in this problem because i got i it was became a long video so i use this thing called lru cash um i do as i say this is only for people who are more experts in dynamic programming so you don't know why you're using llu cash or cash um don't use it especially because in an interview you're going to be asked to explain the complexity and stuff like that and you're not going to be able to then that's going to be a little bit tricky also this is no longer needed because i thought i could do an optimization but um so let me actually clean this up a little bit um but yeah so this is the code but the idea is that okay so for this goal we have a sub array we want to solve the problem of the sub um array of boxes a sequence of boxes where count is the number of consecutive boxes and everything so i think i said this in the other video as well is that the idea here is um is that this is an asymmetric kind of problem in how you handle it and what i mean by that is that for example let's say you have the sequence um the way that you may think about is okay let's see let's think about the next move and then do a recursion for example let's say our next move is 2 and then now we do recursion except for the overlapping segments because if you kind of think about this thing say um you may want to do this you want to remove this chunk and then this chunk or something like that and then they overlap right so we want to think about how to do the segments in a way such that they don't overlap and in that sometimes it makes more sense to figure out the last thing that you remove and in this case the last thing that we're going to remove is some combination of ones and i think i had a good case um yeah i think the good case is something like this where basically the case is something like this and i think i have maybe even additional ones here but the idea is that okay um the first the so the optimal move here is actually to remove this one first and then this sequence of twos and then now you have this one that pairs up with this one and uh let me just keep it this way um because yeah um the ideal move here is to remove the one and then remove the twos and then the one will pay up at the end so yeah so now the way to brute force that is saying okay now let's keep track of the consecutive number of runs per box and i think this is very hard to kind of conceptualize and i only got it during the livestock because i kind of had experience with this otherwise this is very hard but basically here then let's say that's the case well we start off the base case by going okay we want the entire input where there's zero consecutive numbers then here the base cases if we have one number left then and we assume that this number um matches the current count so that means that the score would be count plus one times complex one so here if we have no boxes then we return zero let's say we just want to end the series then that means that now we want to take the we consume the current box of left um yeah we consume that and we have this score of count plus one square and here we just take the rest of the suffix right otherwise um otherwise we um we go through it and we go for each box because the thing is that okay we moved to sub the test case for some reason um let's say we have something like this right you could but you can keep on constructing a case such that um you basically have another symmetry here uh let's just use threes now um where the ones that you care about is this one your last move may be something like this and this where we skip this one and skip this one right so for each one we ask ourselves we have two choices um we can either partition this here or we don't partition this right um so here we can say okay we partition or we don't partition here we partition or we don't partition and so forth um here if we do partition then we basically partition the left and this is if we do partition then everything here we put it in one chunk and in there in that case you have a one of zero and then you increment the number of count to the right and you move the index along because here um we use the same box but now we're looking at a sub problem of this sub problem where the box is this box plus one um yeah so what i will say here is that um i'm not going to do a good job of explaining this because i'm a little bit tired because i am recording this after working on this for two hours um but i would say you know maybe you can watch another video that has a better explanation it's fine um the reason why i say that is because um no the reason why i recorded these videos my way is because i think that what's unique about my video is my thought process and that you get to see a regular dude um kind of attack a problem and kind of struggle for it and kind of stumble through the answer uh my own way right um because there are probably 20 videos out there on remove boxes and mo and some of them are going to be good i might my goal is not to create the 21st good video of remove boxes my ideas kind of create a new different thing where you're like okay larry's solving this problem let's see where he stumbles on how he fixes um like he gets stuck and then you know i fix it while i'm getting stuck right um so i for that reason i urge you to kind of watch my video on like 1.5 x or watch my video on like 1.5 x or watch my video on like 1.5 x or something like that next um but i'm going to skip a little bit because also to be honest i'm a little bit tired today um because i spend like two hours on this forum so definitely watch enough of that um i think don't mind but i would also say that the only reason why the video was so long was because i thought there's an n cube solution i did figure out the end to the fourth solution pretty maybe pretty quickly especially if you watch it on fast forward or if you skip ahead um so yeah um yeah uh for this problem just for quick complexity's sake um is that here for the left we have left input can go from zero to n right can go from zero to n go from 0 to n so you have n cube possible inputs and for each input we have of n time because of this for loop so it's going to take off n to the fourth time uh for each of the input we have all one space so it's going to take o of n cubed space and that's fine um so this is going to be o of n to the fourth time and of n cubes uh space um sorry if this video is a little bit weird let me know what you think um yeah this was hard so yeah so watch what i uh so yeah now watch what i did live but i hope that sets up the context and yeah and that's yeah okay hey everybody this is larry this is day 14 of the august leeco daily challenge hit the like button to subscribe or enjoy my discord let me know what you think about today's farm this is today's bottom is gonna be remove boxes oh boy this seems like it's gonna be one of those traditional and cube dynamic programming ones let's see if that's actually the case uh hit the like button wait did i say that already probably uh but yeah i usually solve this live so it's a little bit slow or hard um fast forward or maybe just ask questions do what you need to do um yeah day 501 let's go okay so you're given boxes different colors and each time you choose some container boxes of the same color remove them and get k times k points remove the maximum points you can get so i'm not going to lie this is actually this is exactly the type of dynamic program form that i'm really awful at it's going to be n cube in some way so because you have n squared states and then some way of dividing conquering left and right and then merge them together the tricky part about this and i know i'm handwavey a little bit but i would also say that if you are struggling with dynamic programming maybe try another problem first because this is non-trivial and i struggle this is non-trivial and i struggle this is non-trivial and i struggle with it a bit to be frank and then the other thing is that um what is the other thing uh yeah so there's gonna be n square states uh left right and then maybe uh o n loop that is what makes it n cube and this is just me guessing because from experience i don't i probably have done this problem but i still struggle with it because it just doesn't come up that much and also they're always like it requires to think backwards right so the what's the intuitive thing to think about is okay given you know given these things what is um like what is the first move that you do right um and the first move you know you're just like playing around with the problem and you should explore the problem a little bit the first move you may say is like okay let's point out um let's uh remove twos and then see what happens and then you know you get three you have these things and you move a four and then three and so forth right um but the thing that i've known and this is where i'm gonna get or try to practice is that you have to think about some of these problems or be able to think about some of these problems backwards meaning that okay you start at the end and then what happens when you kind of go backwards right so that's basically what we're going to do here um yeah just start at the end and then go backwards and then you have some scoring function um yeah and then it becomes a question of yeah and this is gonna be a little bit tricky to explain so if this is gonna be a little bit of a sad video uh i apologize in their fans because this is something that i struggle with as well so um so i may not explain it very well uh you know and people always ask me why i don't you know just go over the perfect explanation uh just to give you a little bit of reasoning and the reason is because i want to show people how someone who may or may not be good uh solve these forms live and what their thought process is as well um they're like if you google this problem or you search on youtube or whatever they're probably like 20 different videos on this problem and maybe they even just go over the perfect solution right and to me that's fine it's just not you know like i don't need to be the 21st video explaining how the perfect solution is so that's why i do it this way so that it gives you a little bit of a different perspective and if it's a little bit long then you know that it's okay that is that someone struggles as well uh and so forth but my question is okay i think i have an idea though now that i'm talking foot a little bit as we said we know that this is going to be um you know something like this right where um so basically we have the subsequent uh sub array of boxes inclusive left right left or remaining maybe that's a better word for less confusion what is the best score and i'm gonna name it gold i mean you can name it like best score or something like that it doesn't like to me it's almost just as bad as a function name so it doesn't really matter um i'm gonna do the memorization later uh maybe i forget but which sometimes happens but we'll see anyway so okay so what happens if left is equal to right then we have one box so yeah if left is to go to right then we have one box so then we just return one right um okay and there are a couple and there come something that i'm thinking about right now is okay so given a bound of sub array of boxes you know and i skipped ahead a little bit we can go over why this is the case and stuff instead of recursioning on like a sub array but this is basically how you represent a sub array again this is a little bit skippier heady um so if you but that is like a core principle of dynamic programming or a very common uh pattern if you will on dynamic programming so again practice uh easier problems if that isn't you don't know how i got to just use the indexes here but then here now let's say we have let me just copy this over a little bit just for uh visualization let's say we have our left is here and a right is here right um as we said we do want to think about this backwards being like okay now we have only have these this array um how what is the last thing that we're doing well the last thing you can enumerate things in different ways as long as you do it in a way that considers every possibility right and for me um at least to kind of keep the recursion consistent in a way and because we cannot go outside the box for a reason that we will probably visit later if we are forced to do this then uh one thing that we can do is just look at the first cell and then also there is um yeah we look at the first cell and then go okay let's what happens if we use this first box or okay because then they're how do you what was the possibilities right the possibilities are okay so yeah that let's print this away here i say okay a lot and i say you know a lot i need to get rid of some filter words but yeah so let's say we you know this is the box we're concerned um if we ought to remove the last thing then we have to remove one of the boundaries right otherwise there's no recursion um because that's uh yeah i mean maybe not strictly speaking but you can also say that okay so what i said was probably a poor reasoning but the reason why we can do this is that if we remove something in the middle let's say for whatever reason we remove these things in the middle first but that's equivalent because in this problem um the order doesn't matter per se yeah because the order doesn't matter if we are given let's say the optimal way to remove stuff is kind of these three segments um what we're saying is that okay let's say the optimal ways to remove this chain uh this thing first uh this chunk first um then we can remove this um well that's the equivalent of just removing this first and then removing this right actually i don't know if this is a valid removal because i don't know if you're forced to uh remove all the boxes of the same color or you can kind of separate them out uh it doesn't actually matter in this case because of k times k p point scoring because of the scoring is quadratic you always want to be greedy in that way that's another thing that i'm not going to prove and it doesn't matter because we're going to go through it but in that case i hope that makes sense is that okay let me give you a better example is okay let's just say we have you know this is the optimal solution which i think it is because just by looking at it oh i know i think the optimal solution is actually um doing the four and then well and then in a recursive way doing the left and right but in that case it doesn't matter which order you go i think that's my point is more that it doesn't matter which order you go and also um the other thing that i was going to say is that there is some symmetry here meaning that it doesn't matter whether you go from left to right or right to left in this case because again because the order doesn't matter um a song like for if you have an optimal partitioning the order doesn't matter so therefore we force an order because it doesn't um as long as you do it in a way such that every possibility gets checked then that's okay um so okay so let's just say then in this case we start with just removing one cell so let's just initiate best to that i mean you could also do something like this um plus one right uh so this is you know obviously this is going to be bigger than that so we can just remove this is just us removing the first box by itself okay and then now it's the last move and this i think is a tricky part but maybe i am a little bit more practice than i did when i first got getting back into it which is that okay um let's say is this a color or color okay let's say our last removal is of um boxes of this color right then what does that mean right so that means that in this case well this is not a good example but let's just say we add a i don't know three five in here right that means that okay um our last boxes can actually go through the entire span right so our last span could be this which is just one two um which we already did or it could be two twos or it could be these two twos and this two right here right and what does that mean that means that when we do the recursion this is going to be its own sub um segment that means that we moved them individually earlier and also we removed these things individually earlier um okay so that's basically uh maybe not gonna lie that's gonna take a little bit of a leap of faith um i'm gonna go i'm gonna continue a little bit because it's kind of hard for me to explain this uh so let me know what you think but basically um okay so let's just do a running score maybe so basically now what i'm doing here is that okay let's just say we want to calculate what do i have this for right uh this is so that if let's say we remove twos last then that means that we have to remove another other stuff first which we do a recursion on that means that we have to remove the five and the three and then the one by itself and then the three five and three and the five and then the three four three right um so those are the things that are kind of partitioned by our twos so in that case we just want to get the sum of let's say we want to make our last move these three twos then we have to get the score behind here and the running score just lets us keep track of that um you hopefully you'll see that pretty soon as i kind of do it um oops so yeah so now let's just say for an index is in range of let's see let's just say left past one um we want to go over this inclusively maybe yeah okay we might have to think i have to think about the indexing here because if it's inclusive okay that should be okay but that now it just means that if oops if left is greater than right we return zero we add that base case um yeah and okay so that means that okay la we want to keep track of last boundary as well is you go to um so yeah this is a lot of indexing but i just have to keep tr track so let's say this is the thing oh wait so we have to keep track of the last two which starts at left okay so then now we want to calculate the score of the thing that's in between so running score we increment this away this is only if this is a two or this is the same color as the first one so if boxes of index is equal to boxes of left then we do this thing we're running score we increment it by um go of and to be frank everything i said could be wrong like i said i'm not very strong on this so we'll see where i go with this um but yeah so this is basically the last bound three plus one because this is going to be inclusive of uh left plus one and then we want to be index of minus one because again these are inclusive bounds so we wanna for example if we have these two twos then we wanna consider these two boundaries right so it's this um and oh let's just do also count is equal to one this is basically the number of boxes that we're using so far uh we want to increment boxes by one and then we want to set last boundary to um so now index is the last boundary so we set last maybe last same box maybe it's a little bit better we set this to index for that reason but then now of course the current score um but the best score that so what is the scoring function right so this is just the running score which so the running score plus this count square thing which is kind of what we have here uh the count square thing so what the currents is going to be this plus um count squared plus goal of index plus one to the right because basically this is the auto partition so basically for example if this is left or variated with l if this is the index which is i and this is r then basically the running score will give the running score gives us everything in between so let's actually move this in a little bit the running score will give us the sum of this plus this dot and the count will give us the score removing the twos which are all these things and then this thing is just the score that you get for the rest of the components right um the rest of the subarray so this is a possible score and we basically take the max of this and the current score and then at the very end we just return best i think this should be good maybe or close to it am i missing any cases maybe definitely way possible at the way and we just go from zero and minus one for inclusiveness uh and this is gonna be endless to go to link with boxes obviously um so yeah so we didn't do that memorization yet i know don't worry about it yet uh we'll just take a look to see if this is right and then yeah for smaller things you don't you know this is just proof force and then now we will try maybe some randomly generated uh and by random i mean i'm banging on a random thing on my thing and then kind of see hopefully this is all right this looks good i mean am i super confident it's very easy to have off by once as we talked about so maybe not but for the purpose of speeding ahead i'm just gonna you know get this in there um oops uh but yeah for memorization right so what are the number of possible inputs well left could be from zero to n inclusive um n minus one inclusive and right can be zero to n minus one inclusive so this is going to be all of n square possible inputs or sometimes refers to states they're more nuances than that but i'm just skipping ahead a little bit and for each one um we do all of one space because we're going to store it down and we can store it down in linear way so let's do that so here we have two things to i always try to write it this way uh let me actually put this comment closer to here but yeah so we have cash is equal to doesn't really matter but uh for this is just an n by n array and then you have hash cache as you go to the boolean of the same thing i don't know why i wrote billion but i think because i was saying brilliant um so then now the caching becomes a little bit easier because then it's just if has cache of left right then return cache of left right and then at the very end we want to set the cache which is uh that's the way that i like thinking about it because it's just way more easy to think about right because you just get to restart your cache later and yeah um if i could have tested a big one first hang on oops as well oh maybe that's more than 100 actually i didn't check oh yeah what got 180 whoopsie daisies is this 100 this is probably less than 100 but that's fine it's big enough that it should time out if it doesn't isn't fast um and we can test that by saying that we don't cache it will this timeout it should be big enough to time out we'll see yeah so basically it should time out and make our cache is working as expected so let's give it a submit after this thing finally gives us the ends uh gives us a status and then we of course correct it and make sure that we run the code quick again okay so let's give it a submit possibly missing some cases but that's okay oh wrong answer what am i getting wrong here that's a little bit awkward um let's see hmm like i said there could be a off by one so what happens if this is on the right so that's a little bit awkward a little bit sad but at least we're close um i think like i uh yeah i think i'm just missing some weird um thing let's see warning score should be okay this is right but by doing this right yeah we definitely want to consider all of it would that give me a wrong answer i hope so nope that's annoying and this is basically like it's probably way tough to figure out like this is a hard problem to debug for this at least this um case is very hard to debug oh no that's right i think because this is okay so i'm way close but um so i'm just checking my stuff my base case should be right because this is inclusive um this shouldn't be this should be good removing the first box by itself i think maybe so what i was going to say that is that maybe we uh maybe we didn't look at the constraints enough in that you're forced to remove the same color boxes um like so you cannot remove just like in this case you cannot remove one two by itself you have to remove two twos um but in that case that would only be the case if it if but we know that's not one of the reasons why it's wrong because if that's the case we would have the wrong answer because we found that logic through um having that restriction means that our output would be better than expect the best possible answer but because this is lower than the best possible answer it means that we're not exhaustive in a way so there may be an edge case that i didn't consider or something like that because if we did then we would have like so that and maybe a little bit but generally um if this if your answer is better than the best possible answer that means that um you didn't respect some restrictions uh and if slower i mean it still may be the case i didn't respect some restrictions but for this particular test case it means that you didn't consider enough cases because that means that there is a way to break this such that um i didn't split it apart um so there yikes this is kind of tricky to debug because there's just a lot of boundary conditions i do think that i am off by one here somewhere but i'm not quite see it i don't see it innately because if index so this is inclusive and if this is right then let's see what happens if i do this okay so this is what i would expect is that i just get a really low answer so this part is right or at least not as long as it could be but then why am i getting this wrong don't in order one seems okay well we get the one where we get older once um so one thing i would try to do is just see if i can construct it easier to explain wrong answer um and sometimes i do that by creating my own or sometimes i take this but take a similar subportion of it but this is just ones and two so this is essentially the same idea um but all right maybe take half of this and then figure out if this would give us so what i'm looking for is having a wrong answer that we can debug from uh so this is good in that now we have a simpler case that is wrong but why because basically what i'm trying to do is maybe get a case such that i can do um i can manually try to figure out the answer and then look at my code what does my code actually does try to figure out the discrepancy and then handle it a little bit better okay this is going to be a little bit tiring yeah huh okay maybe i was wrong about one of the symmetry things i think i could be a little bit more exhaustive but so some combination of this weirdness is enabling a wrong answer hmm yeah right now i'm in debugging modes i'm not really talking that much because i'm as you can see what i'm doing which is that i'm really experimenting with uh with things in general with kind of getting a similar case i think i'm getting close though so because we know that this is the wrong answer still let me think okay i think maybe one of my assumptions is wrong i think it's something like this i don't know if i could remove that part but where hmm no okay but i think it's something where i try to remove the one with the one instead of just the one if i just we've moved to one then i could be okay um and i think i was wrong in my assumptions that about what i said about the segments so so then the question is how can i remove this one by itself um at least in a way that is consistent so i was wrong about the some part of the uh because the idea here then is that i think i was wrong i thought that it would be exhaustive but as well so i have to kind of modify this a little bit but the idea about this test case that makes it wrong is that okay you have this um i think the optimal move is to remove this one and then everything will fall in place uh first but what i did my what my code does is try to remove this one with this one and then separate out the two twos the twos um or and that yeah and i think that may be the reason why so i have to be able to remove this one by itself um and how i would do that is kind of consider actually just removing the twos so we have to figure out how to remove the twos by itself but we keeping the one so the way that my initial dot was that i could if i backtrack how i think about this is that if we want to remove the twos say all the twos here um yeah then i would remove the ones this one and then by removing this one i could remove all the twos all together but it turns out that's not the case in the sense that we actually don't want to remove this one we just want to remove this one so that we can remove these twos and then now at the very end we have this one and matching this one together um let me think about how to exhaustively do this in a smart way um huh so how did i just remove this one in the middle well you the thing is that you would not remove the one in the middle well the alternative way of saying that is that you will remove the two first and i do know how to implement this such that we can do it in an exhaustive way but uh but it's just the coding is gonna be messy so i'm just trying to think whether there's another cleaner way of uh doing this without uh without making the complexity way crazier was basically in this scenario actually the last move that we want to do is going to be this one with this one but maybe without either with or without some of these internal ones and i don't know if that's just an edge case because that's the other thing i'm thinking about is this an edge case hmm huh what if we want this one we're going to keep this one because this is a three right then we want to do what the last move could be um yeah after this is done and this is done we have three ones left so we cannot just assume that we will do the two once and then do the middle so okay how do we do that maybe my running score is incorrect hmm maybe i tried to be too clever so right now i'm just thinking about the recursive divisions and whether um there's a smarter way of handling it or maybe i don't know how to solve this one as a result because this is gonna be a case that haunts me um as well maybe it gets it right now but it's gonna be a future problem um okay so even then this is wrong which is kind of good i guess but well that's going to be a struggle did not consider this case where we have to remove an internal one hmm well that means that there's another property that maybe we can figure out how to subdivide i mean this is going to be like i'm relatively sure that this is that kind of divide and conquer but because even if you do going from the right to left you have this one and this one um you would separate these components and that's not what you want to do because in a reverse thing you just do this and then this part so you actually want this one and this one to be your last move um and in that case well but not this one how do i do that in an exhaustive way in a clear way right and also another thing that you can imagine is that there's another you know this thing here say so that now you cannot just like you know you cannot do the naive end cube thing um you have to separate out this thing because you don't care about this thing and then you want to separate these things right so um and you can also even like play around with a case where you have this in the middle so that now you have to get rid of this one but not you want to keep this one so yeah right so there's definitely more constructed cases that i have to i had to think about but i was wrong okay yeah i mean this should give me a wrong answer if it's the right answer just by luck um oops i guess i have to put it here more than the other voice so how do i do this how did i because i did have an assumption that on the greedy maybe where if these are the same color boxes then we can always suck petition the middle but i guess maybe that's not the case but if that's not the case we can't really do it in an exhaustive way in a reasonable way hmm so how do we care about only this one i think this one and this one at the very end can we think about this backwards and emerging kind of way no because there's no way to divide this into two components right um because this answer requires four partitions on one two three partitions and four things um and you can't really separate it out without the score function well at least not without another state i guess that's the other thing uh maybe i was too stuck on thinking about it like this what i should do is add another state which is the number of running count then we can do it okay fine oh man this is such an annoying file okay i got it um okay so then okay uh yeah so basically here we want to add another state so we have to kind of okay let's change this for now do i guess this is these parts is true um okay so now we want to so this is the definition so far and also we have uh maybe a sort of count so far this count is actually exactly the same as discount um but then now we have two states right of okay it's the same thing which is that now we're running here and we can either include this or not include this so let's do the map both ways and then we can play around with it i don't know if the one um i don't know if all these make sense anymore so let's remove this doesn't make sense um we move the first box by itself so this is going to be removed and then this is going to be zero as the new count um okay let's say unless we move this to the thing so now let's we loop the middle um if the boxes are the same then we can we have now we have two choices we can either remove this box last or it gets swallowed up in the middle so what i mean here right that means that for example if i had this thing that means that i have this thing and my index is here we can choose either to include this in or not inside this box right or inside the current thing that we remove so what does that look like um if we remove this um well right now is n to the fourth so we have to figure it out a little bit first but before we try to figure out how to be better i'm going to figure out yeah before we try to figure out better let's get correctness first so okay so yeah so let's say we're at this one right so we have two things one is okay so let's if we use this box we can continue the chain oh well even if we don't use the box we can continue to chain so let's think about this um okay if we use this box what does that mean if we use this box then we just have this thing and i think this actually is basically right i mean some of these states are a little bit weird now but let me think about this okay we have one box left or we have no box left and this is count oops times count um count plus one times cap wait how do we oh this is the number of current um count is the number of current one with the same boxes as boxes of left something like that so then this is going to be count plus one and in this case we just do count times count okay then in this case we don't actually need to press one because the count is summed up okay and then here we don't need this um okay so then now let's go back again okay what happens if we keep the box then we do this well we don't need the running score anymore we can just like do it well we could do a recursion so the recursion here if we use the box okay if we use the box then we do go of left plus one index minus one um count plus one it's going to be the score yeah okay if we don't use the box what is the score then best is equal to max of this we go left plus one well we don't use the box then we just ignore it yeah if we don't use the box then we just ignore it okay that makes sense because then and we'll get to the next one before we use it right so this is this um this is the left part and i didn't do it but we have to do the right part as well so this is index plus one right um and this is zero maybe i'm not sure about this zero maybe it's one but hmm i think this is one this is should be plus count times count when uh let's this is just and this is not removing it's end the series here because if we basically end our removal at this current point this is going to be the thing right and then we have to add the score as well okay we don't need to bound you anymore so we don't use the box now do we just ignore it yeah because by definition if we do use the box then we will have this partition so then we shouldn't need to know this okay um well this cache thing is it's weird so let's remove it for now and then let's take a look it may time out actually so may okay i'll do the thing the other way in a bit but let me just cache this for now um it might still time out to be honest because uh this is n cube or something right now maybe or n to the fourth side but i just want to see for correctness um this object not callable 19 what hmm this object not called what does that mean i don't really have i don't have this object do i hmm oh i see because i call this cash whoops uh okay fine okay so this is drastically wrong so i'm a little bit off here but why am i off by so weird though at least like even this case are my states really wrong maybe oh this is wrong no this is true oh i messed up this no i messed up this should be zero um where this should be is this should be zero as well no way what am i doing this is really weird that's why uh i don't understand what i'm doing here which is probably why it is as well so this is the right side and this is the left side is left plus one index minus one um this should be just zero um and then here is the this part doesn't make sense for the right side so the right side of using the box is that we okay this actually goes to index and then we do count plus one okay and i don't know what i was thinking when i typed that was just very weird again just made time limited because this is end to the fourth right now i'm just hoping to at least kind of see if i'm on the right track i think this is these are the right answers for these but let's remove the big case for now so we're going for correctness and then we could kind of figure how to condense this so this looks good now more confident about it and then now i can figure out how to reduce this um because right now we do this for loop thing which is why it's so slow but can we do without the for loop so how do we do this in a way with our for loop how do we do um compress this path into something easier huh can look at does that wouldn't really work hmm i'll think about this is end to the fourth right now can i there probably is a way to compress this to be better what if we don't then we go to the next one hmm i don't know man this is hard oh did i not have a thing is that why wait i thought i had a thing okay so this is actually fast enough what's a hundred times um i guess a hundred to the fourth is it is fast enough but hmm i don't know hundredth or fourth is a hundred million which for if i'm not using python maybe fast enough let me just actually construct a case i don't know if this is the worst case though so we'll see it runs but very slowly i would i think on a faster language this is not that much of a concern but i don't think this is going to be fast enough so how do we optimize this to end to the cube can we optimize this to end of cube um we end the series here that's good if we don't then what do we do well then we continue to find the next part but i'm trying to think whether i can um think about this in terms of yeah like if we do use it then what does it look like well we do or we don't use it then what does it look like i don't know how to do it without thinking about a box because then now we could compress stuff then can we do something like go of index right count so that's what not doing it means right this is the equivalent of this for loop so that now once we do this the rest of the for loop uh this is the equivalent of the rest of the for loop and then that means that we can return uh best say so this is much faster um and then that means that i mean and then the other case is going to be just like awkwardness maybe i don't know this may be fast enough by itself to be honest but i'm not sure which one but let's do one more optimization 12 24 36 48 uh 96 is close enough so maybe it is fast ooh but this is wrong also this is wrong okay at the sun so is this right i forget if this is right anymore no this is going to take a long time i this is the part where i wish i have my computer because then uh like i'm doing it locally because then i could at least get the answer even though oh okay so this is still wrong for some reason actually i even got this one this big one um that's weird i actually thought this was right uh because i was focusing on these but then it turns out that this is actually still wrong so before i make this optimization i have to figure out why this is wrong so i'm off by a little bit i think maybe this means that this only comes up yeah maybe this doesn't come up anymore i don't know if that's enough to do it yikes hmm is my answer better no my answer is lower so i think i'm missing a case here where ending the series here is a little bit different because that means that um maybe this constant is wrong maybe i need to start this at one so that we can end the series properly maybe that's why nope now i'm wrong on a lot of things i think that is why though i'm not i think this one is giving me the wrong answer ending the series here um maybe this is compass one because we started off zero and we ended here using this left then i think maybe that's why now i'm just like guessing a little bit to be frank but it looks good um so then now we can add this thing back in as a as an optimizer and okay so that looks good and then that means that now instead of this for loop we can optimize this array to have a pointer that goes from for every boxes or whatever we you know now we can just figure out what the next boundary is and then we do this just to write right and we can do that by just pre-calculating that um okay let's just say the next what's it's called a center no processor what's the word processor whatever let's just call it next i think next is the keyword though um so yeah for each thing we want yeah the next cell so it's going to be um yeah just this times n and basically this is the next index that contains the same value and then here we do something like for um we'll do it backwards i guess one uh let's do previous is it so uh yeah okay but this is looking backwards so previous of boxes of index is equal to index but before that if boxes of index is in previous then next of index is equal to previous of boxes of index okay and then now so instead of this loop we can skip straight ahead to if next of boxes of index is not negative one then we basically do this is left otherwise indexes you go to the next of boxes of left and then now we have this thing and then we don't have to return past here but yeah okay let's take a look oh whoops this is not an if statement oh maximum recursion did i mess up somewhere probably on this thing um huh i don't know i don't get it okay i don't see anything obviously incorrect do i've been saying that or problem so uh yeah okay let's just print out this okay so one is negative one this is seven which that seems good negative one this is four let's do one two three four yep three this is five which seems right this is eight okay i mean this looks okay on so i don't so that part looks good what happened here left right index apparently i'm doing something where the index is weird how did i miss something hmm because now it is left right in the indexes what why would we the index is four oh this is uh this is i am dumb okay fine well this is negative one so i actually have to fix this as well but i think this should be good now maybe i mean better i don't know if it's good okay uh but now i have way wrong answers like this one which doesn't even make sense hmm yikes how did that happen before we had a solution that worked but now huh this is if we don't use it is this right oh this is should be right yeah okay well i mean it's maybe more right but sorry friends this is a long video i kind of knew this was going to happen but this is a hard problem but uh i feel like i was close but then my next thing is not working index is the next index that contains the same thing so this should be good this is using it i think this i mean this is just a fold of compression right do i get rid of the fold up the for loop should be good why i mean it terminates so i don't think i this is going to give me anything all i do is just come just caching what that is that folder yeah and this should be good wow and because this is big it just means that we're doing some really weird thing don't even know how that can be this big to be honest what is that 1707 like what is the square root of that it's 248 that doesn't even make sense so my math is just really off somewhere end the series here how does this even happen this the negative one because negative one is something funky well we had something that was right but then now it's not hmm next index okay that sounds like it should be good but i don't know i just want to see what happens so that's still like really awkwardly wrong it gets the wrong answer way faster which is good how though how does it get a number that big i think that's the question i want to know because even 100 square doesn't get that big so something else is a little bit wrong here and this is ignoring it okay this is keeping it i'll just do worse hmm how do i get this ridiculous number that doesn't even make sense is there anything in this input that it's just this like big giant randomness like i get it could be wrong but why is it this isn't even like possibly wrong in a good way all right well let's just print it out then sometimes i just have to do the hard things you know that was of course i feel like we were we got the right answer with the for loop so this is just making it n cubed but then something is off by a little bit like how okay so the oh and diaper oops how did i scroll up okay like do i have some weird order of president's thing why would it even um that would be funny if that's it but i don't think so like how does this combine like this should be another so zero four is there zero four this is very long so five eight after two count it's gonna give us this ridiculous number but how where how does this combine stuff like this is just adding right i have like how this should be oh this shouldn't be 0 and 4 it should be 1 4 what is 1 four one four zero no hmm that's very weird that it has 582 but we have a two count which is just 281 with a one okay so that now it goes to the first two has a one and then it just takes one okay fine maybe and that means that three four yeah okay why is three four zero as you go to this thing thickens do i multiply something wrong by accident huh index we don't only way that we have scores here print go of what's it three four zero is that what we said and this is going to give us like some out of bounds okay fine also the sad thing is that i actually should uh got rid of a lot of our test cases i was gonna paste it somewhere but i forgot oh well it's fine whoopsie daisies why uh what's it three four zero one two three and four why is that returning 29 000 as the answer let's see oh i okay i am dumb okay is this and also indexes less than a and oh my okay i am dumb uh i actually was thinking about that but i forgot uh at some point because this has been very terrible okay let's actually at least paste this one in and then if this looks good i'm going to give it a quick summit uh invited test cases oops whoops this is why we want them okay oh no this is wrong again what was it didn't we get this one right before did dive off by one now i wish i'd have all my test cases because i think this thing is not doing enough where we don't do anything yeah i see because this is not doing this correctly this is not doing the skip correctly um because basically we want to get the score of everything in between um basically we want to do something like this but we don't want to do something like that because that will increase space uh okay hmm so that's why we do it this way but then now it doesn't calculate the insights in the future in a easy way so um can we do this compression i thought we could but then i think i forgot a case hmm i took my i mean this is the same as the full look though i maybe i just missed red and i thought they were correct now because on the for loop what i did was that i had this sister left or something like that doesn't make sense maybe i just was maybe i misread it on the for loop uh hmm how do we express not doing it yeah maybe i don't know hmm i thought i was close but that was for a while i thought we had this though let me bring the full look back oh so good let's just double check that this that we're getting back to the correct code okay so now this is correct and what i had was so return that's what i had and i thought this part was good and that didn't really make sense that this should be good yeah i don't think that this makes sense otherwise okay because we basically need so we need to follow up how do i compress this code so this code is right let's enter the fourth or is that fast enough i don't know well this is a whole one second already so we probably need to be faster um it's this part that i have to figure out and that part is maybe non-linear i mean so we have a working end to the fourth solution which we did probably like 10 20 minutes ago but how do we compress this what about the nut case do not case can't look at it backwards because now we're doing a chunk no because it's still a loop and you need an entire chunk hmm this was always my arch nemesis and this really showed even though i have all the tools i'm still struggling with this and that's the answer's end to the fourth and i'm just uh kind of annoyed but i don't know yeah okay maybe i don't so the thing with this one is that i don't know if i could prove that and fourth into the forecast too so let's just give it a try um and see how the test cases matches up um i don't know if there's an end tube solution i think maybe that's the reason why i'm okay so maybe i was wrong now let's kind of take a look at let's see if i can learn something here because i this is end to the fourth for sure and it's a little bit on the slowest side but what is the end cube solution let's take a look let's see take a look at the discussions hang on okay and also how i feel like i probably have done this one but that's the thing right is that 100 million is a huge number in python so i wasn't able to so i guess you can make some argument about that is actually 100 million over six so maybe seven seconds right so that's a pretty long time and actually i did it um in c two years ago two and a half years ago how did i do it that time i guess i yeah i did it and end to the fourth as well so i did enter the fourth is there an n cube way of doing this um let's see let's just throw in one solution nope this is end to the fourth okay so i mean i guess i just actually had gotten this but um but i just thought it was going to be n cube or i thought there would be an n cube solution because the thing is that with a hundred to fourth is a hundred million even though it's technically n choose three maybe ish so it's actually closer to uh 16 million so maybe i didn't think about the math that way but the timing is so tight that it's kind of hard to be confident about it which is why i was thinking about an n cube solution for a long time but yeah um this is a very long video so i'm probably going to redo the explanations in the beginning anyway but yeah but i skipped ahead with the caching a little bit um but you can think about like yeah in this case left right and count can be from 0 to n and so this is going to be o of n cubed possible inputs the number of states is going to be yeah which is number of states and or one per member uh per input um space so you go over and keep space for time it's going to be o of n time per input so it's going to be over n to the fourth time um that's all i have for this one i don't know i don't think i did the visualization very well and this was a very long video so yeah let me know what you think hit the like button hit the subscribe button join me on discord hope you all have a great saturday have a great rest of the weekend i'll see you later uh to good mental health bye-bye | Remove Boxes | remove-boxes | You are given several `boxes` with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. Each time you can choose some continuous boxes with the same color (i.e., composed of `k` boxes, `k >= 1`), remove them and get `k * k` points.
Return _the maximum points you can get_.
**Example 1:**
**Input:** boxes = \[1,3,2,2,2,3,4,3,1\]
**Output:** 23
**Explanation:**
\[1, 3, 2, 2, 2, 3, 4, 3, 1\]
----> \[1, 3, 3, 4, 3, 1\] (3\*3=9 points)
----> \[1, 3, 3, 3, 1\] (1\*1=1 points)
----> \[1, 1\] (3\*3=9 points)
----> \[\] (2\*2=4 points)
**Example 2:**
**Input:** boxes = \[1,1,1\]
**Output:** 9
**Example 3:**
**Input:** boxes = \[1\]
**Output:** 1
**Constraints:**
* `1 <= boxes.length <= 100`
* `1 <= boxes[i] <= 100` | null | Array,Dynamic Programming,Memoization | Hard | 664,2247 |
654 | foreign uh in the lead code you can go to the stack topic and sort it with the and solve all the question on the basis of uh difficulty then you will get all the 11 percent at all and you can check it out I have solved each type of question of the easy level or and every question as well so let's I'm very excited to start with the middle level I hope you are excited if you are not then it starts okay every UI then it's also good I will make a decide on each and everything whatever we are going to do in our stack series I hope you have also access the stack series if not access it will give you a better understanding of how the internet structure will come back and it will help you in your coding interview as well so let's start and it's my request to you if you haven't subscribed the Channel please like And subscribe because I rarely say this I am saying this maybe some of you have seen the videos but not subscribing if you like it then only subscribe if not don't worry it's not complicated you should always like And subscribe okay so let's start with the one with our media level question so this is the first medium proportion here it is given that you have an array and you need to find them like so magnetically means you need to just build up by the tree and force the condition of building the binary the condition of binary building or binary trees like at the top it should be the maximum one and at the left so here if we will take a look so this is the six so this is the maximum now this is the left part and this is a light tight part and from left part construct the left part of the tree and with the help of right part you have to construct the right part of the subtree so here we have a three two one so what is the maximum history now again there is no element in the left of three so we have the right part so means there is no element on the left side there is only right elements and there is only right sub tree it could be constructed with the help of element so here we have a two n one so the maximum is one now we have to check the right element of F3 that is 2 then we will try to build the left one so between 3 and 2 there is no element so we can construct all the right subcrete because we have here because I am still remaining with the one element so I will so I can construct the right side of the pin and here we have six five right side so we will go to the right side and take the max that is 5 then again we will go we will try to construct the left part there is zero element is remaining there is zero element is there so it will construct the left part and there is no element in the right side so we cannot set the right part so this is very simple we need to just find the mid of it and just pass the left and right side as we pass the root of left root of right so here we need to just pass the random software and lumps of right and again you will find the mid of it and again we will try to pass the left of it if there is no element just return none if there is right element or null if there is right element then you need to again find the mid element that's all so first so I will just write by writing a register to that we will follow the same type of so we will first construct root with Max element then construct left with Max element again construct root with Max element here construct left child with Max element after finding the max element no I think construct the element with the right element then we need to pass the left side of nums faster right side down no so here we need to First find the construct then we need to pass if it will pass again I will come here again I will find the middle of it again I will come here again I will pass the left of it so all these two courses I have so what I can say if my element which I am passing is equal to random oh sorry my num so this is a base condition and we need to Simply return then so let's build our Logic on the basis of that only so this embed to learn the python as well then you can come and click on this on the below that you need to learn the python I will make a series of the Python and I will make you understand detail of the topic so if you find this quality in Python to write the code please let me know I will make a cities so I hope that all of you have should comment so that I can make I can start series if anyone if only two or three will see yes you have yes please make then yeah I will try but if some more will save this one then it will be obvious for me to write to me so now the base condition is equivalent again we need to construct the root with the max element and before constructing I need to what I need to so I will give you the first translate so find Max element and index of it so I am giving it one because these three are the most important steps so I am just giving it I like this one before doing before performing all these three steps first I need to do the testing okay so here I am taking the max element here because Max is the reserved keyword so I'm taking here in 20 you can also take the largest negative element so this is minus infinity now with the minus infinity I need to take the index Alpha because then if we find the max element that I need to store the index so I am taking here the minus 1 foreign foreign zero worry about that if you find the max element and you get two element Max then which element you are going to pass so here's a six element if it is a Max element then this is the left this then this is the left and this is right so this is a Max element this is a zero one two three so here 3 will be stored so what will the left to start from 0 to 2. so zero two index it will go and root of right go from the root of height will go from here to here means index plus 1 to length of index so this will go and that's plus one two length of num foreign so that's it so here we have taken the Max and index so here it is numb so we are storing both of them now we are calling the left part and then the right part is yeah let's try to ask you to sign in micro should not go yeah that is here let's try to submit it and let's try Google okay that should be I so you need to take the you will take care of two things first is the name convention and the second thing you should not do that much of History you should not do that mistake which I am doing like there is num and England and you need to take the better name convention so that it will be easy for anyone to understand what it is and okay I need to store and store I man I need to call the next one then I need two thumbs up see that index 0 to 10 times let's find out the mistake here so here Max One here we have index then I am going to one by one this is my next one is assume that my Max 1 is minus and if I find 2 that it will be updated then if 2 is less than six will be updated I will also be up to it I will also get update and I am finding the root is also correct now Maxwell now I need to build the net profit so we'll lift will go from zero to the index grounds will go from index plus one to the length of nouns then I need to return through here so here what the mistake I'm making I am passing here to remote I need to call our health and for the left and right side so that's why it is giving them error so it has been Underside to submit it so let's talk about the bank complicity and space complexity that I'm going to use because of n square right because here we are constructed our free Indigo event time and also we are traversing the and so we are finding the left and right so we are again traversing we are again working big off and time so it is because of an extra solution what is the space is because n because we are constructing our three so that will also uh taking big open to space so I hope you have enjoyed guys thank you for watching the video and keep working hard as cosellers as much as solved question as much as possible and yes you've been stuck as well do not worry about it will be easy when you solve more than 200 percent so keep working hard I will meet in the next video with the next video till then bye take care | Maximum Binary Tree | maximum-binary-tree | You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm:
1. Create a root node whose value is the maximum value in `nums`.
2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum value.
3. Recursively build the right subtree on the **subarray suffix** to the **right** of the maximum value.
Return _the **maximum binary tree** built from_ `nums`.
**Example 1:**
**Input:** nums = \[3,2,1,6,0,5\]
**Output:** \[6,3,5,null,2,0,null,null,1\]
**Explanation:** The recursive calls are as follow:
- The largest value in \[3,2,1,6,0,5\] is 6. Left prefix is \[3,2,1\] and right suffix is \[0,5\].
- The largest value in \[3,2,1\] is 3. Left prefix is \[\] and right suffix is \[2,1\].
- Empty array, so no child.
- The largest value in \[2,1\] is 2. Left prefix is \[\] and right suffix is \[1\].
- Empty array, so no child.
- Only one element, so child is a node with value 1.
- The largest value in \[0,5\] is 5. Left prefix is \[0\] and right suffix is \[\].
- Only one element, so child is a node with value 0.
- Empty array, so no child.
**Example 2:**
**Input:** nums = \[3,2,1\]
**Output:** \[3,null,2,null,1\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
* All integers in `nums` are **unique**. | null | Array,Divide and Conquer,Stack,Tree,Monotonic Stack,Binary Tree | Medium | 1040 |
925 | Ajay Ko Hello Everyone - Mysterious and today we are going to Hello Everyone - Mysterious and today we are going to Hello Everyone - Mysterious and today we are going to shoot a new topic of Level-2 shoot a new topic of Level-2 shoot a new topic of Level-2 Admission is ok so the first question of Edison screen is quality keyboard so let's look at the question together and melt it. The question is asked and how to turn it on. Okay, so let's go to the board, but yes, the question is said something like this, my friend is called my name type but he has a quality keyboard, when Bhomaram types or So once that character is there or it happens more than once, then what do I have to do that whatever he has typed is possible, he could not make it in my name, okay, so like once in the name, example number. One let's see I type you today Mannu ok and type whatever happened he type try Mannu but see this was typed double M that 8877 do and how it happened positive and was so when he once we pressed So M is more than one time, I could have done it, I typed it once and, I typed this about it twice, it happened once, diet, it happened twice, okay, so I have to tell you that whatever he typed is my name. It also did not mean to type. What is typing can be done. No, okay, like look here in the question once, but I wanted to type M once, then if seen continuously, then we are there twice, okay, that means this. I can make the part 'A' in the future. I had to type 'A' once. can make the part 'A' in the future. I had to type 'A' once. can make the part 'A' in the future. I had to type 'A' once. If I also keep looking ahead, I wanted to try it only once, but due to the quality of the keyboard, it was typed twice, meaning this section also. I can make a light, it remains that he wanted to type 'and' twice and ' that he wanted to type 'and' twice and ' that he wanted to type 'and' twice and ' end' was typed twice, I end' was typed twice, I end' was typed twice, I can also create this part in the diet. Okay, it remains ahead that he wanted to type 'u' once and ' wanted to type 'u' once and ' wanted to type 'u' once and ' u' was typed once. Okay, this means that whoever u' was typed once. Okay, this means that whoever u' was typed once. Okay, this means that whoever wanted to type this name and whatever was typed can solve this problem, that is, this name can be typed, this name can be created, okay, so this means that the answer should come, Rooh, so this is Take a look at this example, two answers are coming, see what is given in the explanation, like if you look here, it was MSW and typed www.new, was MSW and typed www.new, was MSW and typed www.new, then it was a prank again and M typed twice in his tractor. It has also been mentioned in the explanation that M has been long-pressed once more, okay, it is very long-pressed once more, okay, it is very long-pressed once more, okay, it is very good, it means cannot do the job, now let us give some examples as you see Sumit and this time a little for implementation oriented discussion. Will do it and I type and come and play a little bit, it is good that once I do this time, I said that we used to use further in the last section, understand once in the last section that here A point has been placed and one point has been placed. Yes, right, so I saw that this and such are equal, so go ahead, I have also come and this has also come, Vijay Pandey, Yes, it is gone, okay, so again, now I see that this And I are equal from here so we both are equal from I explanation area but when my eye reached here I saw I and J are different but information question answer is that if there is a party poll then there could have been more than one type. I said that once I came on a holiday, there was probably a previous player from Begusarai who was not interested in the same type of cricketer. So, I saw here, erase it from me. I said, yes, whatever you do, then go ahead, it's okay, reach here, let's go there too. Aa bhi is saying the same thing, now I am writing what Aa is equal to and is equal to, Hansi Aa and there is one more Aa also go ahead and will increase more Ok increased I Aa ahead Voice mail moment I should see what Aa and J a absolutely So I came to know that it is not organized, there is one here, Emma Butt, as the question is, can sleep on the room, then I said once I came, let's take the last in desperate, did n't it happen like this, so once I saw it on today's date, then this Crackers just did Jai Ho Kar Diya Plus App Jhal Here once we kept our eyes fixed, I and J are now equal, what is done when both of us are equal, if we move ahead of both of us, then I will also move ahead and It will go further than this, it has come that on and this has also come on, okay see this both are equal, let's it has been increased that further in Chief Vijendra is equal, let's given it has increased more, okay that unknown fire shot It was removed equally and increased more so that now look for [ __ ] Akbar, both the entries have that now look for [ __ ] Akbar, both the entries have that now look for [ __ ] Akbar, both the entries have come, it means that I can make Ali skin tight, what is the answer to this or is the answer to this through, so once how much is the dip, complete explanation in this note. Once you type kitna ko lite, here I did not see an item, initially 804, quite amazed, reliable, what did I say, till when will I go, till when I also come, it is shorter than my , so there used to be a length function is shorter than my , so there used to be a length function is shorter than my , so there used to be a length function in sting, so Practiced and JB my tab type daughter was in the same. Okay, as long as both J and I are small, keep moving on the road. Now see what I am here from here. We did it after. If both I and J remain equal then you will move ahead. And if both of them will move ahead, then I said, okay, now without thinking, what is written here that if there is Neem dot Carat that we are dad, if it is equal, , that we are dad, if it is equal, , that we are dad, if it is equal, , if both of them then what will they do, then it is even better that if one Bar Bhi Kisii Neem - 1898 So if one Bar Bhi Kisii Neem - 1898 So if one Bar Bhi Kisii Neem - 1898 So if it is just right then here that if not if as I speak, therefore pass in it this Neem which was typed and what I wanted to type was something that I typed. I want this BBC and tight, what has happened, it has been typed, the tube of Android apps, how to speak like this, it has been typed, now what should I say here, it is here and here, yes, it has been mentioned only once, it has been typed, and J has come, and that is equal. Se Aai has moved ahead and Se has also moved ahead Now what should I do here Na Aai and 69 are equal to each other and but I don't care hatai na both cracks are equal to Use nor their previous character is equal to I - Vansh What does it previous character is equal to I - Vansh What does it previous character is equal to I - Vansh What does it mean? Non-NDA Goosebumps mean? What does it mean? Non-NDA Goosebumps mean? What does it mean? Non-NDA Goosebumps What do you do here, I will return this karma that Paul, don't you come with the type of this one that you used to make job, type this type, you can make this name with Singh anytime. If you ca n't, then I did this pattern. Falls came. What did I say as soon as I came out? I said without thinking that if I went out, then you can make this team. Okay, so let's see if there is so much Code - It will be see if there is so much Code - It will be see if there is so much Code - It will be good, bring it. So what have we put how have we put that if in the second I am saying from character strings and Twitter that if held is equal then increment IA and also increment G Okay if it is equal to I - one then what Dhal Singham used to return as - one then what Dhal Singham used to return as - one then what Dhal Singham used to return as editor of The Falls but for about deficit, here is NDA and here is BB, okay so search as you come, here came and here what we saw, what about the attack, organized is equal, okay, organized is not equal. So I came here, I saw an ad in it, J is equal to come, I have read 100 index mother and sister, is that ok on MS Word, then we will get stuck here and how because here human intestine is the reason or index of contraception will come from it. To save myself I should add a WhatsApp I have to keep in mind that whenever I am trying to reach time - one then mix this is time - one then mix this is time - one then mix this is greater than the phone now you can see it so what I said here I Said friend, check this without thinking, first mix this once - daily mix this once - daily mix this once - daily 120 otherwise, you will go to do this and bring roadways true. Okay, so we have done this thing, let's go, now one more time, anyone else can say here. This kind of thing or butter will not be in a hurry till now and also the thing was done properly so that it can be done at one time, now look carefully I have to do it here, I have put in my hard work, now I say this about 2010 Suji and what else Okay, so if there was some system like that, BBC and the type here is Parvez Pet and these are some other types exposed, then let's verify right now, it seems that the type here is D is extra whereas the name had vitamin in it means that I am this type distance, this can never happen, so fry it, our code, so if you look at our carefully, how long has it been going on, till I and get both from here. What is happening here? Did some fairy come here? If they say, then come Rathore cumin seeds of 2 inches came here, both are there, will move ahead, here But as it is disgusting and disgusting that I have come out, what should I do, should I come out and do something and I did this which is typed in the last, as once I have come out, I am in this position and that here But take the network, let's put the custom, which is this and jewelery so that there is confusion that I will be here, I am this recipe, I will show you this, what you have to type, which is typed on the skin, if rice was a hymn to return to education, then there was only one from Amazon. I had made it available, so the typing last here did not look like the paint I saw, friend, here I had to type C and divide is done, I have passed, so see how I am doing this thing, I am applying glue here, I said until Drink welder because debit friends, please do something for me, so I said, if it is my gel, as long as it is velvet i.e. is my gel, as long as it is velvet i.e. is my gel, as long as it is velvet i.e. smaller than the type dot length, what else should I do, from here I typed it like this, the spelling is wrong, click type. Yes, as long as we have Gmail, this is about index-one or not, this is about index-one or not, this is about index-one or not, if I what I when I write the message, I will write the message as soon as it is not cycled, tomato sauce, otherwise, keep this going, okay? I wrote that if the name.in study is not equal to type the doubt is if the name.in study is not equal to type the doubt is if the name.in study is not equal to type the doubt is clear then it is that those who have gone there after thinking once again came to know that it is Meghnad and if I typed the name then it is believed that BBC will ask this but I had to type the name and I typed GBI to get it more eligible, you will see but let's keep the call recording from our court. Come first and till the time it is valid, you are a bachelor, so come put it here and eat here now. Both have equal income and this one has also come, increasing further through IPO, both equal income has come here and here it has come that at this time both of them are equal, I said that I was backward but on the heat, this one would have been bigger here. Equal only developer in the morning ok yes here again i and j equal so come also plus and j b plus si here and here both equal ghr plus and a plate here and here again i director and more character both If it is not equal, then what am I saying? Go to the job link and see if it is equal. So, if I looked at the mention, it was equal, then what happened to the head, when it seems that it has been done. I have been given entry in Intact with Aa Gaya Hero. Next. Now see, what will we do now, our code is looking at Mara that if any one of I and Jim melt then come out, then what I said was that check the inverter, if you see here, then Z to is valid, then end up. If it has already been paid then some tax has to be levied. Now what should I do here? I have done it directly through the returns which is Paul because it is type C here otherwise if it is not typed then how will I be able to make the name, so I said here one check this. Feel free to go out right now, yet Unique ji has checked you completely, okay, we will continue to meet such incidents, even if it seems like an organiser, and even if you have ever gone out till Z, it is over, now too If you had left over, if you want, then it has its own indicator without entries and now you can make it, if you want, you can also make it a bell, so what I said here when you return, keep in mind that it should be done if I am my last. The day of birth is name.in. If Ireland is Ireland then birth is name.in. If Ireland is Ireland then birth is name.in. If Ireland is Ireland then return it. It is Poles. Otherwise she used to threaten. So it is okay. So I thought Abhisarike is for this match. Now one more case should always be done. Yes, what should I say here friend, remember one thing. For this, they have to type the name ABCD and the name has to be typed as this is the name and whatever they type less is ok, what is that made ABC, here the length of the name is already long and the type is already short, so this is what I have just made. I will not kill you, I tried to identify it, what did I write, I gave it to you that if ever the length of the link name becomes greater or the length of the great and type is then this name is a return gift because if you ever come online then type whatever you want. If it is small then it is easy to type and if it is there, then how will you be able to make it tight, so I think it is in all the cases. Now let's talk about ad. If there are ad, then we beat something on one side and got the end symbol, ok simple. I got the spelling of Holland in it, how to get it here. But what is written in the middle, is it okay so let's talk again. I think brother, it is written for everyone. Let's get the curtain raiser checked by the doctor. After submitting the question, it is blank. Yes, it is mentioned that stomach is there. So, I hope you understand the question. Tandon came in and if you found it informative then like our video and subscribe to the channel so that as we move forward in our body you get more questions updates, similarly what should I write, see you in the next process then can buy for up to | Long Pressed Name | construct-binary-tree-from-preorder-and-postorder-traversal | Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times.
You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed.
**Example 1:**
**Input:** name = "alex ", typed = "aaleex "
**Output:** true
**Explanation:** 'a' and 'e' in 'alex' were long pressed.
**Example 2:**
**Input:** name = "saeed ", typed = "ssaaedd "
**Output:** false
**Explanation:** 'e' must have been pressed twice, but it was not in the typed output.
**Constraints:**
* `1 <= name.length, typed.length <= 1000`
* `name` and `typed` consist of only lowercase English letters. | null | Array,Hash Table,Divide and Conquer,Tree,Binary Tree | Medium | null |
376 | Everyone welcome back to the video like share and subscribe ok happy this is what I did here a while back if the video had not been for four-five minutes video had not been for four-five minutes then maybe it would have been a little less to explain so try and ok so the disclosure is over happy back. Let's come e will subscribe difference between richest person's hot chick like number next number should be two his number should be 20 - his be two his number should be 20 - his be two his number should be 20 - his number should be 56 more than that he should be getting less letter of being different here we are not Okay okay let's go Muslim let's go deep together 174 25 this is a big head small subscribe from 4922 now this one that was in 1,250 videos in 1,250 videos in 1,250 videos so does something like this over here and just try to at least on this somewhere You can also remove from means you can remove one or two anything in between but at least remove channel second name return length of the largest vehicle subscribe a different least element come only then you will get the largest subsequent comment from us okay then What we just did here first is not flaxseed from 1749 25 website point long term check takes a big clean vikram 409 to 2.5 inches 409 to 2.5 inches 409 to 2.5 inches 127 tractor 724 less for the greater noida glass 250 liter milk 6 state president of women want to greater than 025 pass torch light greater 263 remove 80 lets 32500 can * 60 so in this way we 46 32500 can * 60 so in this way we 46 32500 can * 60 so in this way we 46 along with this according to that 2017 25 2009 then after that back now this subscribe don't forget to subscribe the channel that now in a way here But what to do, well, first of all, let us see here, if there are two elements, the real sacrifice sequence is the limit, put all School of Economics Trivedi, till the traffic SP says this, then first of all, if my length is just name short. Length is less than two means one so here I will hit return name is start that second less I can write it like this Electronic 2011 maybe here in this post it is written that I have to wait a little on one minimum I am here I took the same card, now what to do after this, let us understand the call of the High Court, what is the semen level question in this question, you will have to understand a little, so see the phone number near you from here, like for example, when it is normal, then here we are. People have said that it is above Celsius, a little above what, I have come down, then what is above 986, I have gone to the head, at this time, I am running, so first of all, we are the people, how is this in the first place, then starting is a colleague, so it means first of all, we People, Ajay, the type of SIM is active in the condition, my Tashan is hello, in this way we will get the name of cost index - 140 and these people have checked that I have cost index - 140 and these people have checked that I have so much strength that if Bigg Boss had to come to the right elemental city, please do Bhumro auditor. Dravid will now be the mentor of the school. Previous Page Next Page The previous page has become one and the current has become one, that history is different and what is the definition of Karan, which is soon capital, what is shining, if my hello viewers are from different districts, then my current reference is Which is 0.5, it is necessary to then my current reference is Which is 0.5, it is necessary to then my current reference is Which is 0.5, it is necessary to support the resolution, the current is stronger than this loot, my previous Candy Crush is to be played, that a cyclical kiss is made, or the reverse of this is to be done, I am great alliance and previous, hence the current ran that maybe some elements can be EM. It means that perhaps something may have happened in the past that if this person does any of this, then increase the counter brother, keep increasing the counter, then friends, he has to update everyone's decree, eliminate the pimple toe correct, and there is something else that he has. So the thing to do is to refer to the previous one. If you want a writer on 'Who's It's Political Prisoners?' If you want a writer on 'Who's It's Political Prisoners?' If you want a writer on 'Who's It's Political Prisoners?' If it's a current account, then this certificate is nothing else. If the application looks very good, then please request my channel. If you are a fan of mine then it has been activated. This means that if the table of recent, if it does not exist in half an hour, then wash the environment. Now 200 posted for land I love you, successful in registering victory in I love you, taking good current affairs, set a record to 9 high - Name Whiten record to 9 high - Name Whiten record to 9 high - Name Whiten Previous Do Previous Different Either this is something else that a little why sports1 then do this loop also happens that party wear tax refund tax medicine at 4 p.m. That this small logical point is shown by appointing a judge that unless the producer subscribes to the union, you will become the subject, then this becomes the goal positive, a very small character, doing B.Tech, only that option, the importance of quick decision doing B.Tech, only that option, the importance of quick decision doing B.Tech, only that option, the importance of quick decision should be more. Front can be done ok notice can be received solution festival also appointment at 1237 70% solution festival also appointment at 1237 70% solution festival also appointment at 1237 70% an alarm was set when government code its answer solution for vehicle subsequent aa mummy a little bit in this video explanation type players had just broken the position time record And it's 2030 Show Me The Mission Accomplished And How To Solve This Problem But Like Subscribe And | Wiggle Subsequence | wiggle-subsequence | A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.
* For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative.
* In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`.
**Example 1:**
**Input:** nums = \[1,7,4,9,2,5\]
**Output:** 6
**Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).
**Example 2:**
**Input:** nums = \[1,17,5,10,13,15,10,5,16,8\]
**Output:** 7
**Explanation:** There are several subsequences that achieve this length.
One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8).
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6,7,8,9\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 1000`
**Follow up:** Could you solve this in `O(n)` time? | null | Array,Dynamic Programming,Greedy | Medium | 2271 |
7 | hello everyone in this video we're going to be going through leap code problem number seven which is reverse integer this is a medium problem um and it says given in assign 32-bit integer X return x with its 32-bit integer X return x with its 32-bit integer X return x with its digits reversed if reversing X causes the value to go outside the sin 32bit integer range then return zero the assume the environment does not allow you to store 64 bit integer signed or unsigned so in example one we've got 1 two 3 as our input the output should be 321 now we've got the same thing only the negative should also return the negative and then input of 120 should remove the leading zero and just return 21 okay so we're going to pass it an INT and hopefully return the INT in reverse order the first thing we're going to do is Define the result equal to zero this is what we're going to pass back so while X is not equal to zero we're going to Define an INT called tail and it's going to be xod 10 and all this is going to do is strip off the last digit so for example exle we passed in the first example says 123 so 123 mod 10 is 3 so 123 divid by 10 is you know 100 or 12 with a remainder of three and then we're also going to Def find a new result that's going to take the current result times 10 plus the tail so what this is doing is um r or it's preserving the reverse number so let's say we have three initially so you take the tail would be three but then the next pass through you'd have a two and so if you just add three plus 3 plus two you'd get five so they take 3 * 10 two you'd get five so they take 3 * 10 two you'd get five so they take 3 * 10 to get 30 and then add the tail plus two to get 32 so that's all that's really doing and then if we go outside uh the range we have an overflow this is what this takes care of that problem so if the new result minus the tail divided by 10 is not equal to the result so this is just the reverse of the previous line so we're just checking that the result you know this equals the result is the same as the new result we did up here and if that's not the case then return zero and then assign the result equal to the new result because that's what we're going to pass back and then we do x = x / 10 which will remove the we do x = x / 10 which will remove the we do x = x / 10 which will remove the last number so for example 123 divid 10 we'll just remove the three and yeah so then it pass back 12 and that's pretty much it return that result and there you have it so let's go through the debugger I picked the first example 123 so here the tail is now going to be three we just took off the last digit and we're going to take that times 10 so the first um result is just going to be three because result is zero so 0 * 10 three because result is zero so 0 * 10 three because result is zero so 0 * 10 is 0 plus three so the result is three and we verify that we didn't get into an overflow situation and then it just aign the result equal three and divided by 10 here we'll just remove the three so we're just going to repeat that step a few more times so now we've got 12 modulus 10 will give us two so now we have 30 + 2 to get have 30 + 2 to get have 30 + 2 to get 32 check again for the Overflow assign that to the result and then chunk off the two so we're just left with the one and one modul 10 is one we're going to add that to the new result to get 321 check the Overflow assign it to result and modulus 10 which is now going to be zero so we'll break out of this while loop and return 321 which is our answer I'm fairly straightforward let's run this through Leo just to make sure looks good submission o 39% still 39 can't get oh there we go 100% okay so now we'll just go through 100% okay so now we'll just go through 100% okay so now we'll just go through the space and time complexity so time complexity is O of n as the input parameter gets bigger the time to run it you know through the while loop increases the space complexity is O of one all we're really doing is taking a number and just reversing it so we're not um taking up any more space and that is it so thanks again for watching let me know if you have questions and we'll see you next time | Reverse Integer | reverse-integer | Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1` | null | Math | Medium | 8,190,2238 |
1,481 | hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my darts I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screencast of the contest how did you do let me know you do hit the like button either subscribe button and here we go cue - so - to least number of we go cue - so - to least number of we go cue - so - to least number of unique integers after K removal so this one I read it I had to read it a couple of times because even though there's a short statement I was just having issues of reading today maybe but yeah basically when I first saw this I was like this is just greedy right and I think to be honest I was a little bit distracted with the other palms downloading so wait after that I was just like let's go okay I read this I know what I need to do it's greedy that's count them well III didn't know how to write the greedy to be honest when I started this but I knew that I needed to count them first and I should have used collections that counter which is a Python thing but that's precise aport but yeah now I'm like okay what do I need well I just need I was thinking about making a Paris and then sorting them later or something like that but I was like oh actually we don't even need to X we just need to count so yeah so then that's what I basically recognized and then I needed I knew that I needed to sort it so basically that's you see me start doing that and now it's greedy you have Caleb you have to take care of them so it just remains a bow loop that gets the K amount basically now we restored it from the smallest to the largest in terms of count so now we try to remove the beginning and then see what's left and that's essentially what I'm doing here there's some carefulness around the servos and stuff like that in educators basically you know you take part only partial off over the way of a number you know that numbers still exist so basically that's what I was doing I knew that when I was running this test I knew that wasn't complete but I just wanted to at least see whether it is ballpark correct so that I could you know like if it's really wrong that I go grab took I have to do something else but the good thing in this case is that the example actually has that edge case I was gonna test it anyway because I don't know we recently have been more careless and more Yano so now I've been trying to go the other way a little bit Graham a little bit less Yolo and in just getting it right but yeah so now I did okay so if this they say okay if they we went over k then we have to then we overcompensated then we just put it back in I ran the test submit and that okay I don't send me yet I actually run more tests I definitely test a couple of cases on this one don't server it's not as fast as I would like but and also I went into needing premium mode paid to ran maybe Oh as soon as I get to zero case I submit and then the week Q to least number of unique integer aside to K remove those yeah so this one I was a little bit careful while I was doing it because I didn't want to get off by one oversee you saw me test a lot but the idea is that it's greedy and what happens is that to get the least number of unique integers we want to remove them from the viewers to the most often and I did that by putting it in a hash table I guess I could have used a calendar actually in this case and I sort it by again from minimum to Matt and then just we move from the beginning until we meet okay I have to check for the zero case because of just removal but otherwise this is an space of n log n time because I saw it but uh yeah um an interesting problem ish definitely something that also comes up in other competitive old women problems by itself it's okay as an interview I guess is okay you just have to I mean it again is sorting it's greedy is always a little tricky if you ask me so I don't know how to tell you about it you just have to kind of Reason it in a good way and intuition and practice and so forth yeah that's cute too | Least Number of Unique Integers after K Removals | students-with-invalid-departments | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
**Output:** 2
**Explanation**: Remove 4, 2 and either one of the two 1s or three 3s. 1 and 3 will be left.
**Constraints:**
* `1 <= arr.length <= 10^5`
* `1 <= arr[i] <= 10^9`
* `0 <= k <= arr.length` | null | Database | Easy | null |
790 | Loot Hello Everyone Welcome Back To My Channel Backward Classes Intuitive Ka Shraddha Problem Problems Domino And From Now Doing So In This Problem Will Give Two Types Of Tiles To Improve With Like This And At Rome E No Him Like This Tumor Half Hour Subscribe This Video Give In increased number of ways in proven answer very large written in these models these were battered main to itna time gender more taking condition 200 tools and will be given a n but 302 the board vittu cross guest sangrampur vaikuntha 63.23 63.23 63.23 solid sep Of Ways In Which Place You Are So Is You Were Given Any Shrinking Means You Have To Cross Three Boards Solid Will Be Something Like This How To Cross Three Pieces Woman Em Now How You Can Play The Times When They See We Have To Ko T-Shirt Raju T-Shirt Raju T-Shirt Raju Loot To Hydride They Can Place All The Dominant Leg This Sweet Will Power Which One Way Or Another Where Is That What We Can Do Is We Can Place Elective Way Like This 9th tweet place one like this and the two like this the freedom with ka like right on your need admin for this is a na doge coin you can check tha they also like crow the amazing people like this a strong 123 lo 123 like comment here But will understand and so when iron for they three do it means said site board the number off do love of fuel 16th pain type questions very hard to find number of where didn't give me to and 323 148 149th board will visit Be Like This Cricket That Is Make A It Is You Cross Four One To Three Legs So How Make The Total 1211 The Wheels Of Arranging Major Changes Different Leg If Styles For Using Arduino And Means 16 Possibly They Live With You Can Do You Can Place Domino Like This Is One Way Or Rather Way Want You Can Do You Can Place All Domino Like This Covering Toot I Don't Know Welcome To Times Ne Or And Will Lead You Want To Meet U Want A Divine Udayveer Hai And One More Visit What You Can do it is that is love you can place at rome it's equal to this that and others like this that dada to terms and one year will not deserve to be with a trek and that when is equal to one left turn to begin 9th discharge when is one medium and board virat is sky above that typing tools - like this that typing tools - like this that typing tools - like this how to cross want to here you can be sworn to meet the only one to me Devendra all the best way is two plus two then means like this Your Body Will Be Too Here You Can Be Sworn To Meet You Really Want To Meet You All World You Can Do You Can Place Vitamins Or Like This And Vinod Dehratu Which Mins To Go To Hai Tu Of Calculated For Test Cases For Cancer Calculated Now Will C pattern between this I will see this pattern is a so let's start with this 5c and 5s 5c it is like two into two plus one aright to know and we give electric energy 2017 is equal to zero 12330 the real right to *govt CEO of Jobs To real right to *govt CEO of Jobs To real right to *govt CEO of Jobs To A Fattu This 222 * A Fattu This 222 * A Fattu This 222 * Mein 150 Something Like This That And Udaipur Office For What Should Be And Late Say For This Ki Tarf 2012 Na Maine 2012 Will Be Using Please Like She Was In His Language Divya 10000 Damdaar 1999 Dhund To Sirf 10 days to that airways eleventh you will see it will be to * the five plus one to * the five plus one to * the five plus one 1125 right something like this point to with her 111 25th that which was the answer of the previous and gracious and current events for a p In front of former 40 inches right now 11th that and five it off N - - - - 153 A 153 that and five it off N - - - - 153 A 153 that and five it off N - - - - 153 A 153 202 two into a safe and minus one so this is a lot of plus two believe previous and value 100 plus one my tab our way can Contribute There Decent of Relationship Where Getting a Good Friend Request You Too * Egg - 121 What I Friend Request You Too * Egg - 121 What I Think They Should Not Be Constrained Chandragupta Dushman Video Apke Where They Can Take Place Where the Answer is 98100 * * 98100 * * 98100 * * That 11th WhatsApp Reviews and Value is eleventh class Arnold welcome to go the page you see now this to on this is reduced to value is not one is not a note of ₹1 value is not one is not a note of ₹1 value is not one is not a note of ₹1 concluded that you are most welcome to this hair pack that which is And to karengi bhi more 125 and this to value it mention to meet istri less that show yudhishthir visit will come the kid will come a half and minus 3 guest relations with relations are using fifty solving the problem solution per current and value the a request Toe Girl Friend - 110 - Reap the a request Toe Girl Friend - 110 - Reap the a request Toe Girl Friend - 110 - Reap Ki Sudhir Duniya Required Every Time So Let's This Was The Code You Want Toe Protect Siddha Who Is Aaj Tak Loot Handed Resonance Approach Garlic Ginger Aur Sundar Ko MD Value Of Duty Which Is The Smallest Value Dynamic Investor Vettori And TVS Result Saunf Bajao That Point Is Equal To One Values In Any Point Is Equal To One Values In Any Point Is Equal To One Values In Any Security To Values To ABC123 Lave The Security To Values To ABC123 Lave The Security To Values To ABC123 Lave The White Tiger Suggestion Or Storing Former MLA Paul And Ise Zinc Iodine In The Morning No The Answer Will Be The Black 123 Dowry To Day Canonical Rating I Will Be Chatting from Physical 214 344 Jashna Vittu * from Physical 214 344 Jashna Vittu * from Physical 214 344 Jashna Vittu * Wheel - Vansh Ki Wheel - Vansh Ki Wheel - Vansh Ki 5852 Into IT - One Plus and Minus One So 5852 Into IT - One Plus and Minus One So 5852 Into IT - One Plus and Minus One So Taking a Modest Taking a Modest to Subscribe 5 Extremely Vitamin B12 This Code Simple A Fitting Key Setting Show Time Complexity Positive of NS VRV Singh Travel and Space Complexities and Fennel and Requesting to Withdraw All Ways Can Avoid Using Decided to Find This Value Vishal Uses Wikinews Pimples But Also Can Do Fennel Fuel the Video Please Like Share and Subscribe as a Reader | Domino and Tromino Tiling | global-and-local-inversions | You have two types of tiles: a `2 x 1` domino shape and a tromino shape. You may rotate these shapes.
Given an integer n, return _the number of ways to tile an_ `2 x n` _board_. Since the answer may be very large, return it **modulo** `109 + 7`.
In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Explanation:** The five different ways are show above.
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 1000` | Where can the 0 be placed in an ideal permutation? What about the 1? | Array,Math | Medium | null |
438 | hello guys welcome to deep codes and in today's video we will discuss liquid question 438 that says find or anagram in a string so yes this is one of the very famous question and also you can see the number of likes here it's nearly to 10K so this is one of the famous creation of a string data structure with the hash or sliding window data structure so yeah today in this video we will discuss uh the com complete approach as well as code for this video so let's begin so here you were given two strings S and P and we need to return the starting indices of P anagrams in s so what does another mean so another means it's just a rearrangement of letters of a word or a phrase okay so enroll them you can think of its as a permutation ah so let's say you have some string like uh a b x y so what are different possible anagrams one possible anagram is a x b y another possible anagram is a b y x so similarly x b y a so these are different possible anagrams or you can say permutation of a string so you need to find anagrams of a string p in string as and you need to return the starting indexes of the anagrams okay so let's say this is the string S L A this is the string pin so what where you will find uh the first diagram of p is so as you can see here this is the first anagram right CBA this is the anagram or permutation of the string right so yeah this starting index is zero so we put 0 into our answer then where is another e a b no EBA no b a b no ABA no bacc this is the second anagram of this string p in string s right and starting is this so letting me number is was Row one two three four five and six so six ah is the starting line so we push that in our answer vector is there any other anagram of p in S no so yeah till here we will written our answer okay so I hope you guys understood the question in the state case so if you take a look at this test case so here A B is the first diagram at zero index then this ba is the second anagram at index one and this a b is third anagram at index two right so this is possible of the string pin in this string s so here let us say ah let us let me take this example only what we are doing we are checking let's say we are checking for this window right uh what is the windows is the size of the window would be equal to P dot size right the size of this P string okay so we are making a window of this piece size and we are checked that's the frequency of all the characters in this window matches the frequency of these characters see ah we need to check uh nnf until for a tostring S1 and S2 true string would be analogs of each row then what would be the case the only case would be the frequency of all the elements of S1 would be equals to frequency of S2 see as you can see here a repeat once bdp turns x epitons y d bet ones so any of the anagrams the frequency of the characters remain the same so in order to check if this window is a this window substring is anagram of P then what we need to check frequency okay and so for that what you we can use uh hash table or hash map you can say hashmap so yeah we will do this so this is our first window if you get our answer then we will push the index in the answer table then we will move up ahead now and we will take this as a second window so every time we've changed our window what we will do we will push the we will remove the frequency of the last character and add the frequency of the new character uh so for an example let's say the frequency of this window is F1 now in second iteration uh the second iteration what we will do F1 minus character of C that means reduce the frequency of characters of c and F1 Plus in character of E u with English that means you are taking this window then this window what you will do then from this let me know so this becomes F2 so from F2 you will what you will do we will remove the B that means remove the frequency of B and add the frequency of next character that is this being right so this is how you will try to make all the possible windows so as you guys uh understanding the intuition of why we are using sliding window because for each index we are checking thus uh the starting means let's say this is the starting index is a diagram is possible then this index is another possible then this index is anagram possible and for that to check if the anagram is possible we are taking a window of size P dot size okay so for this till this window then this window so we are changing this uh index starting index position on the window each time and we are checking for the frequency right and this is how we will check for the frequency only in one group we want again start calculating frequency of all the characters we will just remove the frequency of previous character and add the frequency of a new character so this is how we will maintain the hash table and this is how we will slide the window and whenever if the frequency uh matches with the frequency of S2 then what we will do we will push uh I to our answer so yeah that's all for the approach part so I hope you guys understood uh how you build the intuition and also how we would approach this question our approach would be this by adding one frequency and removing the previous frequency uh yeah and maintaining the this window of size speed or such so this is our approach to solve this equation so now let's move on to the coding part where we will code for this solution so let me write initially one base condition that if P dot size is greater than s dot size then what we will do we will simply return the empty Vector so why this because let's say we need to find permutation or anagrams of p in the string s but if p is only greater than size then as that it there won't be any possible analogs in the string s that's why uh this is the base condition we wrote now after this let us take two frequency map frequency one of size 26 and initialize it to 0 and frequency 2 of size 26 and initialize it to 0 as well so this is where we will store the frequency of a window of size P dot says in s and this is the frequency of all the characters of size of a string P okay so now what we will do we will look from I is equal to 0 I is less than P dot size I plus so we are initializing the window of size P dot size okay frequency fun of s of I plus and similarly we would do for this another string p now after this what we will do we will Traverse from I equals to zero up till I is less than s dot size minus P dot size okay because this is the last this is where our last window will be there and we'll do I plus now we will check if frequency one equals to frequency to or not so since this is the vector you can directly check uh if both the vectors are same or not okay so uh so here this will check all the 26 elements of frequency and all the child 26 elements of frequency two and if all are matching then what we will do we would simply push the index to our answer so for that let me make one answer variable and what we will do we would simply answer Dot push back the index I okay now afterwards what we have to do we have to Simply do frequency one of s of I uh so here one thing I forgot I have to do minus say just to be in the brackets of size 26 so yeah and for that I did minus a H now here what uh what one thing I have to do is remove this current element I so s of I minus a minus remove the frequency and added the frequency of the next element would be in frequency one of s of I plus P dot size why P dot size because our window is of P dot size right minus character array plus okay so yeah and in the end also using this um uh all the windows will be checked but our last window would be remaining and for that uh what we have to do if frequency 1 equal equals to frequency two then in that case we have to take this last window that is this I we have to do answer dot push back s dot size minus P dot size okay so yeah and here we would simply return answer so I hope you guys understood all the code we are simply doing this remove the frequency of previous and adding the frequency for next element um IF frequency what is the okay so now let us try to submit this so yeah as you guys can see our code got accepted uh so I hope you guys understood the approach as well as the scoring part uh and if you're still any doubts then do let me know in the comment section so that's the size of string s is L1 and size of string p is L2 then our time complexity would be L2 plus 26 times L1 minus L2 Why by this because this run for l two times okay and this run for L1 minus I do times but this checking of this frequency this will internally take what S1 26 times because it is of size 26 so we are in so our time complexity is this and our space complexity would be big of 26 or for the frequency or you can say it is as a big off one so yeah that's all for the time and space complexity uh so make sure you like this video subscribe to our Channel also one thing to note here is that I'm posting the job opportunities in the community section so make sure to subscribe to our channel to get the notification uh and yeah make sure to also like this video thank you | Find All Anagrams in a String | find-all-anagrams-in-a-string | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters. | null | Hash Table,String,Sliding Window | Medium | 242,567 |
680 | what is up youtube i'm xavier and today we are going over about drum all right so valid palindrome 2. um given a non-empty string as you may um given a non-empty string as you may um given a non-empty string as you may delete at most one character judge whether you can make it a palindrome um so they just give us aba if we delete b um it's valid palindrome and if we delete c well i guess no this is a palindrome in itself so if we delete c here um it's aba it's a valid palindrome so what we want to try to do is um use recursion to help us because we don't want to have to actually like delete the character but we can skip the character through recursion um so we can do consider like it's going to be two parts one part is going to be um we're going to have used two's pointers again if you guys saw my first video on val palindrome one we used two pointers so start and end so for example if we have start here and end here these two are the same so we move them in and then we have b and c so what we want to do is increased start but keep end the same and check to see if that'll be a palindrome so if we do that we'll see that it's equal they're equal to each other so we return true um and we reach the end and but if we have a longer example so for example a b c d b a um it would go a and a are the same oops something's clicking my mouse a and a are the same b and b are the same we move them in this is still a bad example um so now we'd be at d and c um so they're not equal so we could pass uh start plus one and end as the same so it would start would be here and end would be here um those aren't equal so then we could try uh n minus one but start is the same so start will be here we'd move we'd decrement ends basically like mimicking deleting it we don't actually have to delete it because we just have to return true and so now these two are the start is at the first the end is at the second c we see that they're the same and then we return true so let's do that so we're going to use a helper function because we're doing recursion um so we're going to have the string s in start int and there was one more thing oh boolean deleted so this is what we're going to use to determine if we are deleted a string or a character i'm sorry so um let's just return helper s 0 s dot length minus 1 and false okay so if start is greater than or equal to end then we are just going to return true that's um that's basically signifying we've reached the end without returning false and so then the next thing is if s dot car at uh um start does not equal s that car at end then i don't like that sorry if uh deleted is true we need to return false otherwise we're going to try the two solutions that the two possible scenarios where we either increment one or increment start by one or decrement end and keep start the same so let's do that helper s uh start plus one keep end the same and um true so this is where we're deleting it so we have to pass it as true and oops helper s start keep start the same end minus one and true and then down here we're just going to recursively call helper s so we're just going to keep them the same here and pass false this time because we haven't used our deleted character yet um actually we're going to pass deleted we don't want to pass false because we might actually have to um change it so let's see if that works return helper s start stack overflow error is it false i thought it would be deleted s start and um so there's something i'm not seeing here oh okay so i didn't freaking decrement increment them and wrong answer still so what are we doing wrong let's debug this uh oh yeah we need to so we do need to pass deleted i was right the first time i just forgot to change it so yeah there we go um it's not the fastest solution um i'm sure it has to do with the recursive slack i thought it was an easy solution though um so we're just passing it i believe it's o of n i actually never checked so o of n but we're our space complexity uh i think it should be o of n because we have a recursive stack i'm not 100 sure i actually do need to research this one but um that's how you guys solve it if this video helped you guys smash that like button i post videos every weekday so i'll see you guys in the next video | Valid Palindrome II | valid-palindrome-ii | Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_.
**Example 1:**
**Input:** s = "aba "
**Output:** true
**Example 2:**
**Input:** s = "abca "
**Output:** true
**Explanation:** You could delete the character 'c'.
**Example 3:**
**Input:** s = "abc "
**Output:** false
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters. | null | Two Pointers,String,Greedy | Easy | 125,1178 |
252 | hey everyone in this video let's go to question 252 meeting rooms on leak code this is part of a blind 75 list of questions so to speak in this problem is actually a premium problem and that's why we're doing it on this lint code website and you can see the number is different but otherwise the question and the test case this should be the same so we'll do it here so let's take a look at what this problem is given an array of meeting time intervals consisting of start and end time so S1 E1 S2 E2 where SI is less than e i we want to determine if a person could attend all of the meetings a further piece of clarification here that if we have these two meetings start time of zero and end time of eight and then another one start time of eight and then end time of ten this is still possible and this is not considered a conflict even though these eights here are the same basically you can start a meeting and stop it at the same time so that's not a conflict okay so let's take a look at the examples that we have here to better understand this question and again this website allows you to do the premium questions so we'll be using it whenever we want to do a premium question that's only code okay so let's see in this first one what do we have well we have a couple of starting and ending times here and we can see that actually in this first meeting here we're going to be starting it off at time zero and it's going to end all the way at time 30 which means essentially that these two meetings over here we cannot do them regardless because this one meeting room will take into account all of these like it will overlap with all of these meetings here so in that sense we cannot do it what about in this one over here when this one we can't do it right because we have a meeting that starts off time eight times five and ends at time eight and then we got another one that starts at time nine and then it ends at time 15. so here we can do it the times will not conflict now one of the things about this problem that I guess they should have mentioned that they didn't is that the intervals that are given to you they won't necessarily be in sorted order right so for example we might get an interval where we have something like this right we have something like this and so if you really think about it like when we are processing this just looking through it kind of makes sense for us to sort it right like when we are looking through these meetings what are we doing well what we're doing is like we're going through the meetings and we're essentially just checking to see that like there are no overlaps right there's no overlaps and in order for us to determine if there's an overlap or not we have to somehow determine like an order we have to understand that there's an order to these intervals so we can see here that in this first example it's actually already sorted and really the question is like what do we want to sort it based off of the starting time or the ending time right because we have the starting time here and the ending time here if you really think about it like if I was to kind of ask you this then meetings they start at a specific time and they end at a specific time and if we want to find out whether there's any sort of over overlap then the ending time is like what kind of determines that right because if this ending time for example like ended at like time for example 10 then okay maybe like we can't attend this meeting here but we can definitely like attend this one here right so it kind of makes sense to sort it based off of the starting time here because we want to know the meaning that we can attend the earliest and essentially if that meeting we can attend the earliest if that one finishes then what can we do well then we can go ahead and run the other meetings so we need to like obviously like start the early earliest meeting and then see like if we can go through the other one so this problem is actually not too difficult because if you think about it all we really need to do is we just need to sort our results or sort our intervals so I'll sort our intervals and I'll sort it based off of the start time so that's this Lambda x zero is a start time and then essentially just want to go through my list and I want to make sure that I can visit every single interval or every single like every single meeting so how can I do that well we can maybe have something like a for Loop here we can do 4S and then e in let's see it would be intervals and then we can actually start off at the first one right because or like the first index because we'll obviously visit this initial meeting here so really if you think about it we can just check so if um if not intervals or length of intervals is equal to one well then we can just return true right but otherwise here we have at least two intervals so then what can we do well what I need to know now is like I want to go to the previous interval and I want to see if I can essentially take its place right so maybe what might make more sense here is we have like um maybe for index item in enumerate intervals and for item here I will actually just put like start and end time here right start an end time here okay so what can we do now well now I'm on a specific interval right so I've skipped this first one here now I'm on this one what I essentially need to check is like is this the end time over here is it less than or equal to the start time over here maybe this is a bad example but if you take a look at this one is the end time over here less than or equal to the start time over here right so this is start this is end as long as the start time of the new interval the new meeting is greater than or maybe it's equal maybe like this is also eight then it's valid right so we can do something like if the start time of the new interval if this is greater than or equal to the ending time of the last interval which we can get at intervals and we'll do index minus one that's why we have the index here so this is currently index and the index minus 1 is here and then we'll get the ending which is this value here if this is the case then we're good right so then we don't have any problems but if this is not the case then we have a problem right because then we have something like some sort of scenario where we have something like this so I'm basically just going to go ahead and invert this entire thing and if that is the case then I can go ahead and just return false otherwise if I have never returned false I will go ahead and return true and so this is how this question is so let's take a look okay I realize there's actually a few errors that we need to take care of here so first of all this interval object is not subscriptable the reason we're getting that is because our list that's being passed in is actually of class interval so like there's no such thing as X at zero so this x at zero should actually be X at start and then similarly here this should not be um like the end uh the like index one it should be dot end and then similarly this one should be interval dot start and so that fixes there one more thing we have to handle is in this like Loop over here because we're doing enumeration um I don't know actually how to start my enumeration at index one but we do want to start at index one because otherwise like we don't have like a index negative one if we start off at zero so it's going to error out there so we can do if index is equal to zero let's just go ahead and skip this iteration but otherwise it should be good so let's go ahead and run this now and we can see it passes so don't really worry about like the submissions be like um this is the best solution that we can get so for the time and space here well because we're sorting it to n log n and it's the size of the intervals space we don't really have any um spacers like constant space okay thanks for watching | Meeting Rooms | meeting-rooms | Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106` | null | Array,Sorting | Easy | 56,253 |
279 | hi everyone welcome back to the channel and today we to solve lead code daily challenge problem number 279 perfect squares so uh we'll first check out the problem statement uh and after that we'll look into the approach which you're going to use and towards the end we'll see the code uh as well so starting with the problem statement it is given that uh given an integer n return the least number of perfect squares that sum to n okay a perfect square is an integer that is a square of an integer in other words it is the product of some integer with itself so of course like you know the definition of uh what is in square right so if I say uh 2 squar it means 2 into 2 and it will end up being four so they have given the same examples here as well for example 1 4 9 and 16 are perfect square one will be square of itself two will be square of 2 3 4 and so on so forth while uh 3 and 11 are not of course you cannot have any integer uh you cannot Square any integer which will end up giving you result of three and same with 11 as well right so we have to uh figure out for example in this case we have to figure out minimum number of squares we will have to add together to get the number for example in case of 12 if we add uh two squares three time so then we'll get 12 here right so this is what we have to find and uh we will be using a dynamic uh programming approach to solve this question and here is the approach which we'll be using so I'll start with uh okay so for the reference I have already mentioned a few of the you know uh possibilities over here the best possibilities or the minimum squares which we will need to make any of the numbers and I'll also add one more thing V cases worst case for n will be to add 1 square n times right so this is uh you know this uh we should keep in mind this is the worst case scenario and uh this will be the formula which we will be using so I'll tell you what we'll be doing but before that let's just uh populate the values over here uh taking the reference of this so for preparing zero uh we need not to you know consider this because it is not a valid integer so for one we will have one square like uh if we Square One itself we'll get it for two it is not possible so we are adding one square two times okay so we get two over here for three as well uh we will be squaring one three times so three now four is a square of two so uh it just need one single square right so this is the two Square uh okay now we have five is what 4 square + 1 square oh sorry 2 square + 1 square + 1 square oh sorry 2 square + 1 square + 1 square oh sorry 2 square + 1 square right can we write that this is the solution Bally this is the possible way so we will have two operations for this now if you uh you know look into it and see what we are doing over here uh we are taking the reference of all the previous uh values which we have seen for example if I had to find uh possibilities to get five what were the options were uh 1 + 1 + 1 + 1 + options were uh 1 + 1 + 1 + 1 + options were uh 1 + 1 + 1 + 1 + 1 right or we had 3 + 2 okay 2 + 3 1 right or we had 3 + 2 okay 2 + 3 1 right or we had 3 + 2 okay 2 + 3 will be same 4 + 1 right so these were will be same 4 + 1 right so these were will be same 4 + 1 right so these were the options I have if you go to get the you know the uh the square which will need to make one the perfect square which will need to make value one you can basically access that here right so it will be what 1 square + 1 square + 1 square five what 1 square + 1 square + 1 square five what 1 square + 1 square + 1 square five times basically and the answer will be five right now we have 3 + 2 okay so for five right now we have 3 + 2 okay so for five right now we have 3 + 2 okay so for making three we needed three perfect squares and for making two we needed two perfect squares so this will also end up uh resulting five perfect squares to make five now in case of four we needed one square right uh the one perfect square I should say okay so it will be 1 plus for one we needed one so we have uh two as the answer and this is exactly what we are doing over here so for uh for filling this uh this DP array so this is my DP array and I'll just erase all this and uh you know so show you the resemblance of how this formula is working for us so now let's say I have this much of uh my this much of the DP AR populated already now I want to find for ials to 6 okay what I'll do I'll run a loop for uh everything so if you take the square root of 6 it will somewhere uh it will be somewhere around 2 point something okay so we'll take the Seal of it and we'll run our loop from 1 to 3 okay so these are my this is my concern range now uh let's take we'll start with one okay uh let's take x is one now okay take a temp variable and uh do the uh square of this one 1 * 1 will be square of this one 1 * 1 will be square of this one 1 * 1 will be one I want to fill the value in six right DP of 6 is equals to minimum of DP of I also what you can do you can initialize every uh every index with a value itself for example I can do this because as we saw the worst case scenario is have having uh the sum of uh once n number of time okay so this is it and uh we have 1 + DP of IUS temp so my and uh we have 1 + DP of IUS temp so my and uh we have 1 + DP of IUS temp so my temp was 1 and I is 6 right so can I write 6 - 1 which will be write 6 - 1 which will be write 6 - 1 which will be 5 okay and this is uh this is six now if you do this uh do the calculations we will get minimum of 6 and dp8 5 is 2 + of 6 and dp8 5 is 2 + of 6 and dp8 5 is 2 + 1 okay because we have this so the answer which uh you can have over here is three so this is three so we use the same formula and if you try to you know uh verify this see here we have 2 s + 1 + 1 square + 1 see here we have 2 s + 1 + 1 square + 1 see here we have 2 s + 1 + 1 square + 1 square so we needed three perfect squares to make six over here and you can uh you can process for all X = to 2 can uh you can process for all X = to 2 can uh you can process for all X = to 2 X = 3 as well okay and this will be the X = 3 as well okay and this will be the X = 3 as well okay and this will be the answer and we'll have to follow the same procedure for all the variables and at the end like uh if you are a concern for example Nal to 10 okay let me just clear this a bit and we will just solve it for 10 quickly okay so uh we have already calculated these values before so let's see for seven we needed four perfect squares for two for 8 we need two for 9 we need one let's calculate for 10 okay square root if you'll take the square root of 10 you will get uh 3 point something I'm assuming okay if you'll take you'll get 3 point uh something so let's consider X from I to uh 4 okay your I is 10 at the moment X will consider from 1 to 4 let's take X = to 1 temp from 1 to 4 let's take X = to 1 temp from 1 to 4 let's take X = to 1 temp will be 1 again and for uh for the value of value you want to fill it here you will have minimum of uh d P value at 10 currently okay which will be 10 by default because of course like this is the worst case scenario and 1 + 10 - 1 the worst case scenario and 1 + 10 - 1 the worst case scenario and 1 + 10 - 1 because I was 10 so I was 10 and uh temp which is X squ is 1 uh so DP at 9 was 1 so basically you will have two here like uh minimum value will be two for now at least I don't know about uh yeah so it will be two for now and you can check for other uh values as well if you can get anything smaller than this uh that will be your answer but I think uh this should um you know this should satisfy the uh requirement as well and uh if you try to calculate like uh so if let's just check out all the possible ways so it will be 3 squ + 1 be 3 squ + 1 be 3 squ + 1 square then we have 2 s + 2 square which will be 8 + 1 have 2 s + 2 square which will be 8 + 1 have 2 s + 2 square which will be 8 + 1 square + 1 square + 1 square + 1 sare and what else we have 6 + 10 that sare and what else we have 6 + 10 that sare and what else we have 6 + 10 that will be almost the same so yeah these were the two possible ways and this was the smallest one right so uh we'll be considering this one and uh we'll put the value of this let's check out the code as well so if you see the code uh I have taken a base condition in which if your n is smaller than three you need not to do anything and we can simply return n into it and that's why I have initialized DP till my third index or fourth index I should say third value and if n is greater than or equal to 4 then we are uh using the logic which we have so what we are doing over here we are running a loop from 4 to n + 1 are running a loop from 4 to n + 1 are running a loop from 4 to n + 1 because this is not the last value in the range is not included so this is what we are doing and uh basically dp. upend uh you know goes with the worst case scenario we are appending or we are having the same number as a result or the smallest possible number of squares you will need in the DP array after that uh this is the part where we are calculating the square root of I for example I wanted to calculate 10 in the explanation you know the minimum possible perfect square Ro needed for 10 so we are calculating the square root of I taking the Seal of it okay seal will give you the next uh next integer if it is a if it's a decimal number right so we are running a loop from 1 to that number after that uh we are taking a square of X whatever value you are at you will take the square of X of course like if it is greater than uh greater than the number you're looking for or the I value of yours you need not to check any further and you can break the loop otherwise what you'll have to do you'll have to populate the value with minimum of current value which will be like you know initially which will be your I itself or minimum of current value or 1 + DP of i - 10 okay so i- 10 come + DP of i - 10 okay so i- 10 come + DP of i - 10 okay so i- 10 come because uh it is possible uh temp is a perfect square and we are looking for ways to uh reach the difference between perfect square and the current value so this is why this formula works and at the end we are returning the uh the value at the nth index of the dpay let's check out the test cases uh the test cases got clear let's submit for forther evaluation and the solution got accepted uh I'll show just a sec the solution got accepted and uh we have performed average I would say so yeah this was the solution guys thanks time for watching other video stay tuned for the upcoming ones and don't forget to like the video and subscribe to the channel thank you | 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 |
5 | Subscribe to our channel Computer Sibble and press the bell icon so that you can get updated with all the important questions of C plus python and rice. Hello friends, today we will keep the program of long distance auctioning, so what is pan garam hota to simple hum. When you say madam, you do not go opposite to madam, from the beginning to the last, after all you will get madam, then in this way, what is the word, main string, now in the chapter, we have to make a program of moon screen and there is a chance of clove effect mostly in it, subscribe and office. The trick is that we have taken it out, so what will we do for that? Simple, first of all, take out whatever screen is there and check from it, which is my long span office, which substring, which is that name, arrest, which pen is hot. Which one is it and after removing the panel, which one is the biggest? So what will we do for this? First of all, my only extra point in the matter is that you are a baby, yet this has happened again, then AB, this is BC. Your baby ABCD has become simple, this has become my lowest, then we will do from this, still it will happen, still this will happen, still it will become AC, then BABCD, that you will do this When we come in the condition that what is mine, a pan is hot, it is elastic from the beginning or the star is the last, then starting that you will get the pan now, then the best recipe channel in this we are watching, the thing is of tractor, what is it is mine. The leader will come and the Defense Minister will take out, in this I will use a lot of scientists, be a citizen, quantum is there - in the hotel and the quantum is there - in the hotel and the quantum is there - in the hotel and the second point will be different and what will we do with it, people will start from the beginning and will be the last one, they will have the best experience, if I got a character then I will be the first character, what will I do? What to do or character was looted in the North Nation like we who - character was looted in the North Nation like we who - character was looted in the North Nation like we who - turn both eighth what we will do and that they do not hold IPL position this one of quarter inch which I alone will love now then what is my program in this condition If it is not clear then what will we do, we will not put it that what is always there is that great 10 should be above the first character and what will we do in the problem that we should not be out of the last that less name length you You should not get out of this trick, like, my counting will be out, what will happen to my people, will I move forward and turn off the mode by doing the character of, this is my first time, what happened to me that today was my paper, now what, even after turning I came, they Whenever you brought me, it was as if my brother was out of reach. If he went out, then what happened to BP? Well, he has just come, so both ji and Zero should not go out and from the length of the string that mine is not out that this is mine what will happen that this page will come and this page will come only yes so what will we do now we will increment again so what will happen - Will increment again so what will happen - Will increment again so what will happen - Will come to the forest and will be done, mix my BP like this, it is going out again, so what will we do to I, after increasing it, I have taken BP again, now friend, will the living being remain or will it go to ghee and that? If we are here, then what will happen - - how long will it happen - - will happen then what will happen - - how long will it happen - - will happen then what will happen - - how long will it happen - - will happen till he goes out of zero, here is the net, then what will happen in jail - - will happen, and then what will happen in jail - - will happen, and then what will happen in jail - - will happen, and my soul will go out and I shook hands and fell in love. I have gone out and that is my lovely relationship, at this time we are seeing that my skin is in condition, so in that condition, my last character is coming, if I get out, then he will not be my CM, this program. My heart will work less when it is in condition, as long as my heart was in condition, what will we do for these conditions, what will we do to reduce it, understand simple that it is for these conditions. What will we do, we will keep ji off and we will make it i plus one and now tell me, half step of mine will remain only here today, then what will happen to me ji in the year that it will remain like this and i plus one will remain on Camila side, now the limit will be If you do this, then I will be out and I will continue to run on it until you are like that, yes, my look is mine, this is my increase to increase the height, then what will happen to me, I will come and yes, my SIM will come. The position will be that we will increment, Kotak, this will come for me too and you will come for me, then as you increment, it will be wound as soon as it will be out, then what will happen in that condition, come again, mine will come, one will come, then 8 plus. Will it be done on one or not? My P will be incremented again. As long as we do the increment, it will be done. My song will win on the seat. Then what will happen if it is intimate? In that condition, my DP will come and this friend of mine will go here. When we are watching this front mission, my match is happening, we are able to check the whole character, now first let us keep the victory, if we have kept the IPL and the process of IPL on class one, then my heart condition and condition. We will create our program and this is what we have to do: will create our program and this is what we have to do: will create our program and this is what we have to do: first of all we program, first of all what do we have to do, we should not go out of the boundary, and so to start with, first of all we do one thing, get Spring Boot done, yes G B A Baby boy has become a straight student, what to do now, Mirch celebrates a function, diggi app, Ajay that Islam is the religion, passes the intermediate, gives two pointers first of all, gives string, measures TRP and says half point at the lowest and last, you guys will put 10. And the last one takes this should not blur the screen. Mission is done. What are you? We will create our program for Phantom. No problem. To click here, we will click and mark S8 voice mail. The people 222 ad blouse that it will be on the key till then it will be mine but it will keep going like this out of equal and or what do I do with mine, it should be out of equal, the second reason is also it should be out ad went out of zero for the last time then it is mine Today 's position of implement is this bell's position, 's position of implement is this bell's position, 's position of implement is this bell's position, we will - - do - we will make a post, you will we will - - do - we will make a post, you will we will - - do - we will make a post, you will intimate by one click and we will increment that you have commented to me, what will we do after this, we will return a return on the festival r Voice mail plus one Hansla, we do this, we will understand it in this, first we will understand you in oats when you are in the program, this is done, now what to do, we will create this program which will explain my various and vote, put loop and move and check Will I check if my pan is hot or not? For this we take BF Loot Ukti. So this is done. Now for a result, let's take IS Black Label and apply the form and if the iodine ranch goes till today, then the length was off. It is simple. What will we do now? What did we do for the court case and I skin what will we do simple both my G and K IP should remain and which clinic click and that in I will a luck will come that in my relationships we are the channel this simple is an impossible in which We are going to start my skin banega so that we can compare and take out my long distance from the string, then it was cheek or chicken attested 400g. You have understood that this is my audition. Click here for the plate. Now what is found in it is this. The only trick is that the plains of the team and the dam length of the army chief are that if it is big then it is coming and store it here so that then my makeup in the improve label of the team is bigger than this. My result meeting is If it is bigger than that, then we turned it and made it equal, we said, I do office, this thing is mine and for the believe in condition, how will we give a plus here, if we feel like it, then this is done and in the last we return. Let's give so that when we do, then the word request is simple, now we call the function, you a that green hua tha ke seeds for long distance from hua, to understand it better, what we do here, a madam should keep that the film Nothing madam, mine is being printed, you can mix madam in the middle, here and there, you will give something on them, even now if you see, madam will be different and different from madam, what has become mine is also DJ's last, dear, it is here and this. Then there is Amy from here too, we got every dear like this, we got it barefoot, rather, the print is a little clear, now in the last part, to understand the lighting by applying the lighting, I will link it in the description below, the complete video is made in it, the second one will understand it. Whatever we have done here and plus one and you will understand this life, understand it in a simple way, what will happen to me when it is mine, but what will happen to me, simple Aamir, what will happen on that condition, yes, what will happen to me will also come and what will go to me, I am above this. Okay, then what will happen? Stop the increment, when the increment happens, then what will go to me? You will come, Jhal Mirchi, what will go to me - ₹ 1 will go. If you Jhal Mirchi, what will go to me - ₹ 1 will go. If you Jhal Mirchi, what will go to me - ₹ 1 will go. If you cannot do it after this, then understand its mark here, which is the calculation of this time, we, I, college. Let me understand here that verification should come, so here help Laxman is just starting, if it is then entry will be done - entry will be done - entry will be done - what is the position of one plus one, to take one to three or to take literature of Tata for 3, my typing is done. That is, this tractor will print up to the third character, which has become the gift song, friends, if you have problem in lighting, click on Visalakshi in the description below, from there you like it, then understand it and driver the old logic by yourself. See if you can understand the program then friends, if you like my video then please subscribe the channel, like the video, comment, if you want any program help, read the description of the idiot killing his left hand by switching on the free mode. can | 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 |
224 | Decide for polling by banning Ajay, so today we are going to solve this question in a basic letter. In the question, we are making someone, yes, our own, we got a spray of expression and we have to tell from the same year how much of this entire Krishna Value will be created. Let's give an example. I will get you a SIM. Yes and inside it is written here that visit can sleep plus minus operator and can do castor. Okay that means two three four such a dildo. This plus one minor pass will get the full benefit. Can and this can and this balance will also be representative of expression here before applying this thing has to be called started its quality is more then do Bigg Boss in advance - love and then turn then do Bigg Boss in advance - love and then turn then do Bigg Boss in advance - love and then turn this whole thing on Two 238 Okay, so you have to tell me the answer that if this entire system is calibrated, cancer will be formed, so let's write some more examples, a simple example, there can be space here like it is written here, space on that printed saree. Maybe and then two minus plus two will get something like this tight so on that which the alarms which will start the gun and the result will come Kayan plus stop and per is full support tight and how to write Jhal I got you a string on that It is possible that plus text A plus minus month torch light This plus and minus are entry operators along with urinary operators also there are tight so it is possible that you may get the form of union operator you are representing this - dry ginger get the form of union operator you are representing this - dry ginger get the form of union operator you are representing this - dry ginger basically - voted to basically - voted to basically - voted to Right and this is the plus one, this is the banner operator, now what to do in anger is to add these two, this is full of energy, is this or cancer, here let's see in the 11th test match for some updates from which you will get this But what to do is that OnePlus and Plus five are plus two - 3 - 3 - 3 A plus B plus 8. Okay, so its complete Lanka. You can increase the speed by wearing this, it will be protein, if you get so angry then this is the yagya remaining of the plan OnePlus 11: 00 Aql - 3 OnePlus 11: 00 Aql - 3 OnePlus 11: 00 Aql - 3 A plus footy pipe this whole year has to be done accordingly add these two to help and fruitful call these two this note plus protein and it will be completed okay so you come that would be the answer for this time okay This is what you have to do, you have to evaluate the entire string toe and tell the answer, then their length can be this much, okay, so basically here it is off N or on9 N, this volume is required and here Delhi will give quarter. So let's modify this case a little in the same way, so the plus here, if I make it - plus here, if I make it - plus here, if I make it - Okay, this is the business - basically all of these are going to Okay, this is the business - basically all of these are going to Okay, this is the business - basically all of these are going to get height increase and will do and plus five nine plus 211 this will go one. Minus minus thriller 6 plus 8 that they are here and both are different turn impatience these two together in negative - will be coated impatience these two together in negative - will be coated impatience these two together in negative - will be coated plus one this - thirteen and plus one this - thirteen and plus one this - thirteen and that meet can be installed quickly on the solution I have some questions if you have any I get such an express and that I plus 4 - 21 A dream there is that I plus 4 - 21 A dream there is that I plus 4 - 21 A dream there is no rivalry there is no union operator so this is how you set it up see first of all what I saw is five and then its gone plus so what I have done to these two Saw 98105, kept it in all, equal to five, next was on Plus, so updated it to 980, saw I - updated it to 980, saw I - updated it to 980, saw I - toe have in this - made this seven, then toe have in this - made this seven, then toe have in this - made this seven, then further plus one, added it, edited it, absolutely won and less. You are done, the problem arises when I go to the University of British in this, if I rewrite this - two plus one, it is I rewrite this - two plus one, it is I rewrite this - two plus one, it is okay, if I find it, here it is negative, here it is positive with plus one, okay. So what do I have to do on this, first I saw the time, got so much, then I stopped the clock completely, I have to see so much of one spray, first I have to cut this passion, this is science, plus or minus, take fame, what are you going to make? Like we have shoulder is big plus makes plus minus plus milk is - make is and plus minus plus milk is - make is and plus minus plus milk is - make is and minus plus makes tight you are the same we will also use ji what have I seen here from plus and then from month both are different inside. So this is the complete details - Overwrite was kept ahead, it will be complete details - Overwrite was kept ahead, it will be complete details - Overwrite was kept ahead, it will be completed - 400 125 - Cigarettes came, that's completed - 400 125 - Cigarettes came, that's pure ghee, what did I see next, ignorance minus plus is kept, minus plus will make minus, so this complete is complete - and further If will make minus, so this complete is complete - and further If will make minus, so this complete is complete - and further If you have kept the value then here we will submit one minus two and it will become complete - one minus two and it will become complete - one minus two and it will become complete - 1st is the last. Again the question has arisen here - make one plus one and this will be the arisen here - make one plus one and this will be the arisen here - make one plus one and this will be the complete expression which will make its value zero. Now we are going to solve this medical question like this but in my spring I used to study that it can be done by taking out the unit and tweeting it all but the parents did not know how to do it, but so many will be required but what can happen here, it is three plus one. - - - How to plus one to Ajay that what would I have done if there was a string like this, first of all it was Jal Gautam, what he is saying is that keep in touch only, the result till this much is here plus one, then update and pre- result till this much is here plus one, then update and pre- result till this much is here plus one, then update and pre- set us. Taxes have gone to my head till now and there is no money here, when I have only plus and minus in the entire restaurant, what more will I do, what will be the result of all the brothers inside, that by nourishing their side. President can do this work that keep the information of this - somewhere that keep the information of this - somewhere that keep the information of this - somewhere like this - It came, you saw that the bed has come, okay, you got yourself into it, like this - It came, you saw that the bed has come, okay, you got yourself into it, like this - It came, you saw that the bed has come, okay, you got yourself into it, arrested yourself and kept it, when you saw that it is two, then you gave it a plus two. Instead of treating it like - two. Instead of treating it like - two. Instead of treating it like - tourist phone it will be completed two hey man plus one treat it like - hey man plus one treat it like - hey man plus one treat it like - it will go two and this youth and me here - it will go two and this youth and me here - it will go two and this youth and me here - two come so treat it like plus two it will go three layer Like this bracket came, you pot it, type if look a little more on this, after this, if there were some more expressions from exactly till the time, how we used to do Sril - Vwe Sril - Vwe Sril - Vwe Hai - Two Plus One and here again - Ri Hai - Two Plus One and here again - Ri Hai - Two Plus One and here again - Ri Plus Okay and press here Gemini, okay, if this was a profession then how would we do it with the current condom, it is made perfectly by turmeric, it is minus one but the result from here till here is done, when you saw it was a straight. Tracked because or one paper will work, we just saw - here - and then you are placed on the bracket, saw - here - and then you are placed on the bracket, saw - here - and then you are placed on the bracket, then you treat this trick like negative two sons, the phone is fine, you have done it, then it is complete Jio If the phone is plus one here, then you make it like this - is plus one here, then you make it like this - is plus one here, then you make it like this - Okay, so this is the whole time of hatred, that's it, but a positive means there is a negative side and then there is the racket, okay, so make it negative here also, so here that here. It is a medicine bill, it means that now you have to do the opposite, you were an Indian, okay, so put positive here inside here, plus three layer, treat it like earth, read the phone plus two key, phone, this will be completely completed, the sum of and Tight again, when you removed this project, you pause this one plus, this one which was negative, was just fitting so perfectly, fried, outside of this is the flag effect, okay, so here is the plus action or seen on this track of yours here. - It is placed here - here. - It is placed here - here. - It is placed here - Becomes a woman or completely. This was a solution, it was a way of doing it and it will also work, so this year will work in two favorable ways. We are not seeing it completely right now but in this Friends will roll it in a different way, let's check what that method will be. But we can't do it. Let's see with this if three plus one - 2 - pro and there will be a person outside also, - 2 - pro and there will be a person outside also, - 2 - pro and there will be a person outside also, what will this cream do to the body. So we know how to solve it when there are no adds, we made these right away, so he saw them first, made them three each, saw plus one, clicked on this and did it, now see, for now, this is going to set the results of all these. If you used to set it as a hate, if I send a message here, then this one is here, it will become soft, then what to do now, make the phone very simple, even the time and store it somewhere else on the data structure. Support it and keep it here - it on the data structure. Support it and keep it here - it on the data structure. Support it and keep it here - it is a symbol, keep the pimple here, it is okay and now we have left our labor behind, so this valid data, if it is gone, it will not make any difference, make this zero and start the sequence. Do it again, okay, here you have seen two, so it is 1 - and this - you have seen two, so it is 1 - and this - you have seen two, so it is 1 - and this - after doing this, it has become two. Okay, now look, now there is a negative here, which means the racket has stopped. You even know this. tha value - here also the person has cut it value - here also the person has cut it value - here also the person has cut it now what do I have to do itni kavya - to hai okay then what am I doing - to hai okay then what am I doing - to hai okay then what am I doing itni value veg - I have to click here itni value veg - I have to click here itni value veg - I have to click here tight if you see this now then in a mansion I have told you Then he also has to do - I mean, we told you Then he also has to do - I mean, we told you Then he also has to do - I mean, we only have to work out the value of this note first, right, how will this negative volume work, from here I took out this guy and I have given this guy a one minus one cement treatment, it must be two. I edited this entire result, okay, I got this much value, now only S+ is left got this much value, now only S+ is left got this much value, now only S+ is left and at this time I know, I kept it aside, took out Lal K and added it, this is not a problem, education, okay Look now, I used to keep the result from here till you for the sake of my sexual intercourse. First okay, then keep it from here till here. When both sides got late, now I have kept it tight from here till here. Looked ahead - after kept it tight from here till here. Looked ahead - after kept it tight from here till here. Looked ahead - after doing preliminary, this Completed free mesh, if we look at it one more time for some nested presses, okay, so let's see for this, first today we will create, so there are some shortcomings, three are now by default, which is these, so which is the first one. Looked inside, updated the location at 32, okay now New Delhi via Tite, so what do I have to do, if I have to outsource the work, then this is the data, the time till now is three and this is the line, let's install it. I have divided it here and kept the capacity so far, three more symbols - capacity so far, three more symbols - capacity so far, three more symbols - OK, now make it zero, now the work will start from here, you see, there is one, here I made it one, again here plus has come, problems. Came and this pred has started, so again we are going to do the same thing which we had stuffed earlier, we will store this one and plus, started one and plus and started this mantra, now the work inside. It started again, he folded it to plus five nokia plus 211, but as if it was completely over, what do I have to do, now I have to have a serious discussion with the first one, I have to have a serious discussion, one, I know the oath from here to here. What do I have to do with this, now I have to make it from here to here, okay, how will I reduce this, I have this entire part kept here there is fraud lying on the wrist, there is also a pimple lying, okay then again first. If the symbol Nikolai is positive then you will not add it will not remain that you have completed this work, now all that is left is to add it, take out this reason also and add it by giving plus one so that you can see here, we did insult special darshan. Was and taken out from special reservation Both of them have shoulder dates When it should be straight It works on 11 gram from the side Only mind One day on the gas track I am a lonely guy - Dear, if we minister it, I am a lonely guy - Dear, if we minister it, I am a lonely guy - Dear, if we minister it will become This is the question of right The job is telling that from here till here I have added Assam Twelfth here, now I have been pranked again, I know from here till here what is happening, what do I have to do, before that I have to extend it in this direction, so first negative. It should be multiplied by, accept and then send message to no, then add it is kept here itself, if you take plus 3 from here, then it will become 12th, this will go to - 6. Okay, so from here till here, complete plus and then If this one starts then subscribe 269 and this is another famous plus one, work will start again by doing zero, the inner camp will do education or 6, if the memory of voting is removed from this, then if the racket is closed, then first this is so much work, know the plug. Remove kaya and this is not protein coffee kaya and then the complete result of the previous one is - 6 complete result of the previous one is - 6 complete result of the previous one is - 6 sprites - but if it adds voting then it sprites - but if it adds voting then it sprites - but if it adds voting then it is - 6 or if added then it becomes a tunnel is - 6 or if added then it becomes a tunnel is - 6 or if added then it becomes a tunnel and that's it, the whole is good. Okay friend, there seems to be a lot of work in a court, so let's limit the implementation of the juice track, so we know what to do, once one happens, we see these signs, what to do when there are union operators. It happens that it is tied like a plus minus and after that it is minus plus five and it is asked how can it be handled, we will handle it already plus science lab - Aaya will fill this negative plus science lab - Aaya will fill this negative plus science lab - Aaya will fill this negative tight, this step will work by calling on the first step. If it happens, then how will we do it? First, it is accepted that it is okay to become positive in the line, we have seen three, then the next band is closed, if told, then the positive band is closed, the next guy will come - he will change this, it positive band is closed, the next guy will come - he will change this, it positive band is closed, the next guy will come - he will change this, it is okay with the negative band, the next guy is complete, either then I will get out of here. You will get to know, okay, you will get it from here, its size will be known from here - it is set that K size will be known from here - it is set that K size will be known from here - it is set that K - will start it will go - one firangin Here I - will start it will go - one firangin Here I - will start it will go - one firangin Here I saw it will have to be reset right we like the person tweeted, we will set it positive again Saw it being made - changed it to one positive again Saw it being made - changed it to one positive again Saw it being made - changed it to one plus, if it doesn't do the new default then it will remain negative then it will remain tight plus, if you do n't do it further saw the value is five then its lead is free size, that - should be its lead is free size, that - should be its lead is free size, that - should be on - pipe it is complete - 6 is done then it is ok. Let's on - pipe it is complete - 6 is done then it is ok. Let's on - pipe it is complete - 6 is done then it is ok. Let's play it and share it. Let's see it once in the whole city. Let's see what to do. In the last three tasks, we have the first one in the neighborhood. We have to work for a time to maintain them. By the way, if the brackets come, then those brackets. To handle the one, I increase on the extract. Okay, so we will work here also and lastly, when the plus minus here is such a unique operator, what do I have to do, I have to collect all these tight, so for that. Let's make a sign very, okay, plus one will represent positive and minus one will represent negative, the whole question, so this is plus one and the respect is okay, so you have to do the work of seeing, before that the festival negative is basically an opposite. Right, if you already have a negative, if another negative comes then it will become plus, it basically opposes the first one and when we have a plus, it does not affect the plus, it comes here from the first Dr to negative and the plus is negative. If it comes then it will be posted, it is tight, it is good in a way, so first of all, if the negative comes here, then post it, 2 - 150 140 negative comes here, then post it, 2 - 150 140 negative comes here, then post it, 2 - 150 140 via value, here you have to pay attention, there can be multiple digits also, 312 is fine and this is complete. You will have to take a string, so we will see how to do it, so there will be an operator inside each well, the operation will be, when I saw the value zero three, then changed it to free, then when the next Vrindavan came, first I multiplied three with tan and plus. Made one to one, went to 3152, Jatin added multiple items to two, it became 312, so some operation like this has to be done, or for now, they just don't focus on it completely, 312 came, so I got one digit complete. -I got the whole came, so I got one digit complete. -I got the whole came, so I got one digit complete. -I got the whole that one two and its line is on this side of the tables, I selected one and 2 - came to know the value of the plan from them - 312 21 a selected one and 2 - came to know the value of the plan from them - 312 21 a selected one and 2 - came to know the value of the plan from them - 312 21 a the - if you make it 312 then its the - if you make it 312 then its the - if you make it 312 then its value will also be the same - 312 two value will also be the same - 312 two value will also be the same - 312 two Next again, we have to reset it too, tight, we have a variable, a value, so you have given it a sign, now there should be science for further, it should test positive, okay, if it saw positive, it will not pack, if it saw negative, next. Close Jhala, he will make it rather - then got the value make it rather - then got the value make it rather - then got the value Madhavan and Vitamin A minus one after going to his prosperous - add this prosperous - add this prosperous - add this full of energy - 313 L - 3138, let's take full of energy - 313 L - 3138, let's take full of energy - 313 L - 3138, let's take that Parastri Yantri is fine, after work the next day. If it is completed then plus one has even said that if you show negative in the future then it is signed in - one is now bread, signed in - one is now bread, signed in - one is now bread, now this trick has to work, I am tight, so many doubts, till this time, and if you want to store this sign, then Evening is - 3138 and the then Evening is - 3138 and the then Evening is - 3138 and the line is - 110 that line is - 110 that line is - 110 that ignorance After doing this work you have to set the sum to zero and also reset the sign Next close Jhala - Will declare the Next close Jhala - Will declare the Next close Jhala - Will declare the war value of so this value by using it Will take - it will be tight, it will be completed - set up 3 through Will take - it will be tight, it will be completed - set up 3 through Will take - it will be tight, it will be completed - set up 3 through service, come on plus one that Iqbal also keeps writing to Gautam what he is doing, what guest of we have taken, the alarm I have here is white space, that is something on this. If we don't have to do this, then the goal will not change. If there is a value then ay, when there is a value, we sign it as value * ay, when there is a value, we sign it as value * ay, when there is a value, we sign it as value * and then we do plus equal to value and in the last sign we also change it to plus one. Okay, this entire work is done, I had asked for complete value, okay, so here I got plus one, I will add it here, so it will go to two and the last work is to reset the sign, so it is already like this. Also, there was no plus and no, okay ok, if I made a plus again, then this is closed Jhala vowels' Hamra Kata or closed Jhala vowels' Hamra Kata or closed Jhala vowels' Hamra Kata or what to do in my writing, the result of the first reviews which is found is not complete, how many results are there in the evening, this is tight, put this result first. Meaning, if you do that in the evening then it is here - Dua will come and then after asking for the sign, make it is here - Dua will come and then after asking for the sign, make it negative and then sign, reset the website option in coma and set the alarm, start this also and sign first. Since then he has become only positive. Okay, my friend, when the proposal came, it turned out to be a prank again. Now we will meet for the first time. First of all, the value came, after adding science, it will remain the same. At this time, he will add services, plus he will seat. So when will this tube go completely, okay, B and then set the time, it should still remain positive and give an alarm - then it will go - what has to be done in 100%, alarm - then it will go - what has to be done in 100%, alarm - then it will go - what has to be done in 100%, I am fine, Nighty Sanga writes. - If it comes then Nighty Sanga writes. - If it comes then Nighty Sanga writes. - If it comes then basically sign has to be called right then sign in multiple Icon to - one which change will come in multiple Icon to - one which change will come in multiple Icon to - one which change will come ok album then - hua tha to again one work will happen ok album then - hua tha to again one work will happen ok album then - hua tha to again one work will happen again I made it positive 1 came value I got one jhal the Science of positive yoga positive one, contact him, he will go to the job, set the sign also, now set this sign, I don't make any sense, there is no goal, okay, how much work has been completed, so in the end, one Plot cigarette has come, what do I have to do in the project, I will die in the evening, the result of this much, I have nine lying with me, first of all multiply this by outside MPs, pop it from here once, Sara writes here, what kind of work is this? If this close gets settled, then let's multiply our work. Track dot that you do. Okay, whatever will be bound and will be multiplexed. After the foot sign, when I pop plus is equal to two, that means wherever the even was, that is in the stock. Had kept * After adding even was, that is in the stock. Had kept * After adding even was, that is in the stock. Had kept * After adding all the props to it was nine - all the props to it was nine - all the props to it was nine - started this Sawant that from here to here the result of Sawan, we have come to know that it will be ours, okay, now let's see next Sunday - okay, now let's see next Sunday - okay, now let's see next Sunday - Time that Anna Sandesh Yatra tomorrow Will do swan become value come then the sign of one is - one and value come then the sign of one is - one and value come then the sign of one is - one and then it has to be added I set and this is a complete one of energy right if then able racket it has to be matched again we have to die that is the steps First meet me in the evening and spot it here - See, here - See, here - See, it's done - 6 You swear it's done - 6 You swear it's done - 6 You swear and after that add us Pop it here - For 313 I will add So - 309 here - For 313 I will add So - 309 here - For 313 I will add So - 309 This is the sum of close battery Have to reset the complete sign, now it is negative, good value, after the value, I did not reset this plus one, now you have slept half a step, got A plus made, no one will change - Maya A plus made, no one will change - Maya A plus made, no one will change - Maya from this - will do, if value came - to value from this - will do, if value came - to value from this - will do, if value came - to value and this Like this, we will go and add it here - Streel 130 210, complete here - Streel 130 210, complete here - Streel 130 210, complete 321 has come, then these four are in work, let's see how to do it, we have to do the individual according to the bracket and minus sign. If you want to do it, then here you are here ek banda woh kasam bus ek banda hoga sign mayyippan hai aur prajal jhal ki after all take out the character sequel does not spare time that if the press note here is to visit this that this edit is useful here. It will happen only if CHC is equal to its bed, there is a chance here, there will be work here in this project and if it is simple then there will be work here, so less has to be done, let's check the first work test, what to do when it is digital. First of all, you have to set the whole person and for example, if W is something like this, 3124 A is here, then you have to use it first here, then by increasing one here, increasing the fare to two to a or big to four and here. You have seen that we do not have digits, I am also an express, this is plus or minus, so our work stopped here, let's do this work, how to validate islab up to 0m and dont, length and character should be digits, jhal is a tax credit, so welcome to value. Multiply 10 and we will cut it by A quarter - 0 A quarter - 0 A quarter - 0 that I will definitely give its value basically and yours is fine that after this here we will have to do one more thing. Now what have we done here, the age in front of the digit. If we go to any symbol and put it on the right side of the horoscope, then either the value of that symbol will increase again, then this symbol will become a runner, so to stop it from doing this, we will have to delete it once again and move on, okay? Here you decrement it once so that they will move among themselves, okay you set the volume exactly to the two value multiply line and then to low so that one net is done and the cigarette is so much what to do, I am of my bed here and your Three goals - You guys are cowards here, it is - You guys are cowards here, it is - You guys are cowards here, it is tight and inside - if there is something like this, then tight and inside - if there is something like this, then tight and inside - if there is something like this, then first of all you have to put the information on the track, first put your oath, put the sign and then recharge in the evening, is it okay for inside? Who all first handle that tractor then put the time bead and workers 1205 so A positive they become a plate that people are stunned we have to go out and pepper him cases here there was some aspiration from here even You have got value on less and now close singh rakhra or hai follow back hour first then this sign hours have to work if you are tight then sum multiply equal to arrested got it easily on whatsapp and sum plus equal to a student pop The previous Samit took an oath and added it to you, so you understand that now Tight is keeping the complete information from here till here, the work here also got completed on the back foot everyday that so much less had to be done that - If it happens then sign. Give a that so much less had to be done that - If it happens then sign. Give a that so much less had to be done that - If it happens then sign. Give a call to Multiply Wealth Management that your complete song of this question will be present here. Okay, let's run it and see where Shri Radhe is in the line number 9211 and panty. We have given that 123 should come after checking. There was a mistake here, I did not reset the sign. Daily 121, after using it there, the sign had to be reset. Tight, for this case, you had plus minus verb, so you ever Sa ine - used my master - got free ine - used my master - got free ine - used my master - got free after this for the next value it should have started from positive tight here I made some mistake ok let's run it again these pieces are ready Well, okay, this is like a complete liver. Hello friends, thanks for watching, Ajay in the next video. | 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 |
133 | hey guys welcome back to this video now we're going to solve a coding interview problem clone a graph you are given a reference of a node in a connected undirected graph return a deep copy that means clone of the graph we are given starting index of graph is represented using adjacency list the graph is connected and all nodes can be visited starting from the given node and this is our problem statement if we are given this graph then we have to clone this graph in the cloned graph we can't reuse the original node that means we can't reference to the original node we have to create a new node to clone this graph we can't reference to the original node to the clone graph here we see this graph is not a cloned graph here we're referencing to the original node and here we are indicating that by using the same color okay so we can't return this graph because this is not a clone so we can't return this graph and here we see for this graph the nodes were cloned but the graph is messed up doesn't have same connections one connected to three and four but here you see one is connected to two and four so we can't return this graph this is not a clone graph and this graph is a clone graph why is that because this graph look like a clone and the nodes are new graph look likes the same and here we're using the node and they are new they are not referencing to the original node so we have to return this graph this is a column graph if we're given this 2d array and the index are one best not zero based and this represents this graph this it's for index one at index one this node has two neighbors two and four and here two and four is not a value two and four is a node okay two and four is neighbor nodes then we have one three and the index two and here we see one three and this node has two neighbors one and three then three one two three here we have two neighbors node two and four then four we have two neighbors one and three and this graph represented like this here one means the index one based index and two for this list mean this is adjacent to list and this list contains the neighbor nodes this two and four doesn't mean this is a value 2 and 4 it means that 2 is a neighbor node and 4 is a never node and this node 2 has a value and adjacency list2 and that's true for all the value for the second box i hope you have understood the graph representation now our goal is to clone this graph such that will not reference to the original node we will create new node to clone the graph and then we have to return the starting index uh let's see how we can solve this problem to solve this problem we're going to use q and hash map and we're going to use bfs source to clone the graph now let's see how we can solve this problem we're given this graph here we have hash map hashmap has two properties for each item key and value and this is our queue first we're going to create a new graph that has a value 1 and has no adjacency node and this represented like this we do not know the adjacency node for 1 we have just created this new graph by getting the value from the first index and this is the value first we're going to check does this first node exist in our hash map we see no if we see the current node does not exist in the hash map then we'll add to the queue so we added this node to q and let's add this node as key and as value without the adjacency list that means without the neighbor node now what we're going to do we're going to pull the first node from the queue okay we pull the first item from the queue now we have pull equals to this node one has two neighbors two and four okay for two what we're going to check does the node 2 exist in hash map no the node 2 does not exist in the hash map so let's add that to q and let's add ascii this node 2 and s value without the neighbor node so this node represented like this for node 1 and for node 2 we don't know the neighbor nodes don't worry keep watching this video we'll see how we can find neighbor node okay for 2 here we see the node 2 exists in our hash map now what we're going to do we're going to get the value in the hashmap for this node 1 and that is this node okay and there we're going to add the value whatever value we have in the hash map against the node 2 we have the value this node we're going to add to the neighbors of node 1 okay so we added here 2. now what do we see here and we see that this node one has a neighbor node two so let's connect to neighbor node two okay let's connect node one with node two right here as well because they are never now the next node we have here 4 does 4 exist in our hash map no 4 does not exist in the hash map so let's add 4 to the queue also let's add the node 4 to the hash map as value the node 4 without the neighbor node so this will represent it like this now for this node 4 we don't know the neighbor nodes okay we see that the node four is neighbor of one so let's get the value from hash table for node four and let's add that to the neighbor of one so let's add four right here so we have added node four right here now we see that the node one has two neighbor one is two and the other one is four now we're done with this node so now let's pull the first node from the queue because we're done with this node we pull out the first node from the queue first what we're going to do we're going to take this node 1 does this node 1 exist in our hash map yes node 1 exists in our hash map then let's get the value for the node 1 from the hash map and let's add that to the node 2 as neighbor so this one will add to this neighbor of this node 2 and we're just adding here 1 and we're adding as a node one has also neighbors two and four we don't have to worry about the neighbor we're just adding the node we're indicating the node by the value okay actually we're adding that node itself for sake of understanding we're just using the value and we're indicating the note by the value for sake of understanding so let's add one here we have added one then we have the next node three does three exist in our hash map no so let's add to the queue also let's add this node 3 to the hash map because 3 does not exist and as value the node without neighbor nodes okay now what we're going to do we're going to get the value for node 3 from hash map and then we're going to add that to the value of node 2 to the hash map as neighbor node so let's add this three right here again we're adding the node we're not adding the value three here for sake of understanding we're adding just the value and the value indicates the node this node three represented like this also here it's represented like this okay now let's add this 3 to this neighbor okay it represented like this all right now here what do we see we have two neighbors for node two one is three and the other one is one so let's connect to neighbor three so let's connect to the neighbor three now we're done with this node now let's pop out the first element from the queue okay now we have pull equals to this node four first we have one does one exist in our hashmap yes one exists in our hash map then let's get the value from hash map and that is one so let's add that value one to the node four as neighbor so one goes here then the next node we have three does three exist in the hashmap yes three exists in the hashmap so let's get the value and that is three so let's add three to the node four as neighbor then it will be represented like this and here we see for this node four we have two neighbors one is one and the other one is three so let's connect to three okay we connected to three now we're done with this node now let's pop out the first element from q okay we pop out the first element from the queue and our queue is empty here we have the first element 2 does 2 exist in our hashmap yes it is so let's add 2 to the neighbors of node 3 right here then we have 4 that's for exist in our hash map yes it is so let's add 4 to the neighbor of 3 so 4 goes here we're done now our q is empty when we see our queue is empty that means we're done and we have to return the new graph and this points to the first node one and this is how we can solve this problem hope you have understood this problem if you aren't understanding this video explanation don't worry revise this video then you will see how it actually works this solution will takes big of b plus e time complexity where v is the number of vertices and e is the number of edges we have in the given graph and the space complexity also big o of v plus e to construct the clone graph if you haven't subscribed to the channel please subscribe to the channel and stay tuned with cs ninja thanks for watching this video i will see you in the next video till then take care | Clone Graph | clone-graph | Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node. | null | Hash Table,Depth-First Search,Breadth-First Search,Graph | Medium | 138,1624,1634 |
1,610 | what is up guys we are back with another call problem so we're doing 16 10 maximum number of visible points you're given an array points an integer angle and your location with location in position x position y all the points also have an x y coordinate they both denote integral coordinates on the x y plane you're initially facing east you can't move from your position but you can start rotating in other words position x position y cannot be changed your field of view in degrees is represented by angle determining how wide you can see from any given view direction let d be the amount of degrees that you're going to say counter clockwise and your it using including the d minus angle developer two blah anyways uh the question is very simple don't want to read it but basically this is how it's going to work originally you're starting over here you're facing east and where you're giving an angle and your angle is basically your point of view your field of view that you can see and give it an angle that's your starting position x y over here is your angle okay and then you're also given that's your angle yes and you can also rotate you can roll it counterclockwise you can do the full 360 circle right you know full circle okay yes we know yep angle divided by two crappies ow that hurt where's the points okay anyways then you also have points in this entire xy plane you're also having points in this entire plane and you can see only a certain number of limited points at a time depending on your field of view right depending on your field of view and your location the points location you can only see a certain number of points at a time you want to find the maximum number of points you can see at a certain time and what is it dependent on is dependent on the points location is dependent on your location and it's dependent on the angle you are given right these are the dependencies we have for this question becomes very simple once you make uh one uh really big observation once you realize what kind of problem it is that you're looking for after that becomes very simple that's that before we get into that there's also some math involved uh i'm not going to really explain the math solution just uh i can't you could just review sokatoa and how angles work and i don't know i didn't even review it i just like oh okay yeah i remember i learned this a couple years ago some math stuff anyways so how is this answer going to work number one you're realizing that you have a certain field of view at every interval right it's dependent what on the points location on your starting location and the angle that you are given you could keep rotating right to see more points right you can keep rotating to see more points right different types of points at a certain angle at a certain rotation you can only see a certain number of points at a time notice that if my angle is like this i have a 90 degree angle and i'm rotating it right i'm rotating it let's say i'm looking this way and i have a certain number of dots right over here when i rotate this way what did i lose and what did i gain when i rotated like this much what did i lose i lost all the points that were between right over here and i gained all the view of a view of all these points once again i'm looking over here as soon as i move this way i lost view of all the points that were over here and i gained view of all the points that were right over here but i still can see this small angle right over here right this small angle right over here okay i see all this already i'm going to move this over here go back to my 90 degrees i see all these points now and i lost view of all these points now look you're seeing more points and you're losing a view of some other points what is that usually that's usually a sliding window problem that's what you need to know it's basically a sliding window problem in a sliding window problem you have uh you have your array here you're starting a raid usually there's like some kind of starting array right and you have a sub array or your small little window and you're either increasing your window from the right or you're decreasing from the left and you're kind of keeping the sliding window and you're going through that entire array viewing all the possible subarrays viewing all the possible windows that match so that's how you want to think of this problem now where is the math involved the math is involved like i said all come together and end i know i'm jumping all over the place but it's going to come at an end so we have these points and we kind of need to convert these into some kind of sliding window approach what we have our angle we have our points we just have points we need to convert each of these points to our angle we need to convert each of these points to the angle and that's where the math is involved in some kind this is an equation using a tangent inverse tangent so katoa opposite over adjacent blah don't worry about that too much and i mean worry about it but i'm not going to explain it and also in the question uh you can just create an uh like a real interview problem you can just create a helpful function called get angle and you can tell the interviewer oh i'm going to fill this up at the end i don't want to worry about it and use that in your main part of the code now we're going to take each of these points we're going to convert them to an angle and then we're going to sort them how are we going to store them we're going to sort them in the relative order that we can view them so for example i'm facing east i can first see this point then i can see this point in this example over here um there's only two what is a bad example but let's say i have this field over here and i have a bunch of points all across my plane first i can see the points over here then i can see these and i can see there's any answers right so i'm going this way i'm going to counterclockwise so the points will be sorted in order how are they going to be sorted by their angle relative to the starting point which is you're facing ease and relative to the location okay so that's how this problem is going to work so for example now we're going to take all our points which is like x y we have all these points blah we're going to take each of these points of recovery term to their angles so now we get all these angles and i'm going to explain how you convert some angles in the solution so we have all these angles we're going to convert different angles and then we're giving it a starting angle meaning our field of view that we can see and that will be let's just say 40. okay actually let's say um 30 okay now how many points can i see at one time well over here let's see i can see 20 that's my starting i can see 20. can i see 30 yes because 30 minus 20 is 10 it is still within my uh angle with my constraint which is an angle of 30. so 30 minus 20 is 10 so i can also see uh that point can i see 40 yes i can see 40 why can't i see 40 because 40 minus 20 is still less than 30 so i can still see 40. i can see 45 46 47 48 49 and i can also still see 50. why can't i still see 50 minus 20 is what 30 so i can see all these points within a 30 degree angle my starting point will be over here probably at this point the end of that will be at 50 and that is my little angle then i'm gonna keep sliding i'm going to try to add 70 into the equation 17 my sub array but now i can no longer see all these points at one time why because my angle that i was given was just 30 degrees and to see 70 and 20 at the same time now is impossible because the point at the 70 degree angle and the point 20 degree angle have a 50 degree angle difference they have what a 50 degree angle difference so i can't see both of them at the same time either i have to remove this one or this one well remember we're having a sliding window post already calculated this and we kept track of the max we can keep track of the maximum so i see 70 now so it's too much it's above 30 so i'll drop my first and i'll get 30. so 70 minus 30 is 40. that is still too big so i'll drop the 30 again i'll get 70 and now again once i have a possible window in which i can see all these points so you're gonna keep working through it like that you're gonna have seven they're gonna add 80 minus 40 that's too much i'm gonna drop this much 45 still too much i'm gonna have to drop all of these actually no yeah i'll have to drop all these points i'm gonna keep dropping 45 and 46.7 i'm gonna keep dropping 45 and 46.7 i'm gonna keep dropping 45 and 46.7 uh end of eight minus 450 is 30. i'm gonna keep going like that okay i'm gonna go all the way around so i'll show you the answer in one second actually i won't even cut the video to go to this guy he had a really nice solution we'll just walk through that fang 2018 thank you for your solution it's a java sliding window problem yes so what we're going to do first is we're going to create this array list of angles or count to zero okay and then we're going to go through um all the points we're gonna get the difference in x we get the difference in y if there if the x is the difference of x is zero and the difference is y zero meaning it's the same exact point we'll just increment the count meaning we can always see this point at every time and then we just continue to go to the next one but if they're not which is usually the case we'll add to our angles and this is the equation to get the angle okay the inverse tan d i don't think this is this will give you theta whatever but this is the basically the equation you can google this figure so i don't want to explain this right now and honestly i don't even think i remember this fully myself but anyways this equation to get the angle in the um coding if you don't remember this is fine just do angles.add get do angles.add get do angles.add get angle helper function and just put in your equations you should know what it's dependent on and it's always going to be dependent on the difference between y and x or is it dependent on the your location and the uh the point the location of the point right depending on the points location these p and depending on your location so basically this for loop will get you all the angles and then you need to sort the angles right as we mentioned you need to sort the angles in the view that you're going to see them and then this is basically just a regular old sliding window problem google sliding window watch some videos on that if you don't understand them fully i highly recommend that anyways we can do this temporary array we're converting all these angles into over here and we go through each of the angles and we're going to add d plus 360. why are we going to do this well sometimes we may have an edge case where we have the full angle is 360 or maybe 300. right let's say the angle is 300. eventually you're going to come you're going to go around and your angle is going to go all the way around and it's going to need to shift back up to the uh beginning again okay so we're going to have to calculate and add 360 to each of those points and add them to that then we have the and i don't think the angle is ever going to be larger than 360 so you don't need to worry about that because that would be whatever would be a different problem all together response is going to initially be set to count why is your initiation initially going to be set to count well because the count is what the count is the number of points we see at our location and if the point is at our current location within well then we can always see it so we'll start with count okay and then we'll go through the um array all the angles and this is basically the shifting uh sliding window approach we're gonna go through all the points and while right while remember the what i explained while the right most angle or the angle at this over here at this point minus the angle at this point right is less than the angle the field of view that we're given you can think of angle as the field of view we're given right wild is great while it's too much we're gonna keep bringing this back so we're gonna slide this upwards when it gets too much greater than our field of view we're gonna slide this back so we're gonna keep going like this okay once again bring this up and once we go over our field of view i'll bring this back shifting over bring back over and over like that okay that's what this is do okay while this point minus this point is greater than the field of view we're given we're going to keep j plus we'll shift this over we're going to keep shifting this over okay and then we'll end up with a response right count plus i minus j plus 1 i minus j is the number of points in there capital i minus j plus one will give you the final number of points and we'll keep q we'll continuously keep track of the max and number of points we can see at this interval and uh at the end of that we'll return it that is the solution uh please subscribe if you haven't already please comment improvements suggestions on how i can improve these videos comment any questions and leave a like if you enjoyed um yeah thank you very much i'll see you guys the next one | Maximum Number of Visible Points | xor-operation-in-an-array | You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane.
Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In other words, `posx` and `posy` cannot be changed. Your field of view in **degrees** is represented by `angle`, determining how wide you can see from any given view direction. Let `d` be the amount in degrees that you rotate counterclockwise. Then, your field of view is the **inclusive** range of angles `[d - angle/2, d + angle/2]`.
Your browser does not support the video tag or this video format.
You can **see** some set of points if, for each point, the **angle** formed by the point, your position, and the immediate east direction from your position is **in your field of view**.
There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.
Return _the maximum number of points you can see_.
**Example 1:**
**Input:** points = \[\[2,1\],\[2,2\],\[3,3\]\], angle = 90, location = \[1,1\]
**Output:** 3
**Explanation:** The shaded region represents your field of view. All points can be made visible in your field of view, including \[3,3\] even though \[2,2\] is in front and in the same line of sight.
**Example 2:**
**Input:** points = \[\[2,1\],\[2,2\],\[3,4\],\[1,1\]\], angle = 90, location = \[1,1\]
**Output:** 4
**Explanation:** All points can be made visible in your field of view, including the one at your location.
**Example 3:**
**Input:** points = \[\[1,0\],\[2,1\]\], angle = 13, location = \[1,1\]
**Output:** 1
**Explanation:** You can only see one of the two points, as shown above.
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `location.length == 2`
* `0 <= angle < 360`
* `0 <= posx, posy, xi, yi <= 100` | Simulate the process, create an array nums and return the Bitwise XOR of all elements of it. | Math,Bit Manipulation | Easy | null |
338 | hey guys persistent programmer here and welcome back to my channel so in this channel we solve a lot of algorithms and go over legal questions so if you haven't subscribed already go ahead and hit the subscribe button smash that like button because that helps me create this content for you guys so without further ado let's go ahead and look at today's problem counting bits and what we're given here is a number n and what we need to do is return how many ones are found in each number up to this number so that's what this number means i know the question can look confusing so what i've done here is i have drawn out each of the representations of this number so it goes from 0 to a and what we need to return here is the number of ones that are represented in each of these numbers up to eight so if i were to solve this manually um first we would put a zero in the first position because there is no one here and then in the next position we have one and then we have another one in the next position and then in three's case we have two ones so this is one we need to put a two um and then for four we have one and then for five we have two ones and then for six we have two ones again and then for seven we have three ones and for eight we have one so i hope you understand the question and what we need to return okay now there's an observation that we need to make and don't worry if you didn't really notice this because you wouldn't know this unless you did this type of problem before but what happens is each time there's an even number if you divide it by half so let's say we have a 4 and then 4 divided by 2 is equal to 2 so when you look at the position of the two there is only um one so this value and this value is actually equal so the number and it's half so in this case the number was 4 and its half is 2 here will have the equal number of ones when it is represented in binary and then the second case is when the number is odd so you notice here that with all the odd numbers this last bit is always 1 and that's because 2 to the power 0 is 1. so every odd number will always have this extra one so if we derive that okay for the even numbers the number of ones in the binary representation is exactly half all we need to do for the odd numbers is just add a one to that so these are the two cases so if it's even we take the number over the half and we put whatever number of ones is in that position so that is our answer and then if it is odd then what we do is we do the same thing we do n over 2 but then we add this one because you can see that for all the odd numbers this last bit is always equal to one so that is the idea to solve this problem and what we're going to do is create a empty list filled with zeros and we're just going to populate the numbers in as we go through them um so i'm back in the code and what i'm going to do first is create a answer list where we're going to return the answer and this is going to be the number of positions we have plus one because we are starting at one and what we're going to do now is iterate through this list so for i in range and we're going to go from um one to n because we um already know that for zero we have put the answer as zero so we do not need to iterate this okay and what we're going to do is get the position so for each of the elements we're going to use the index as the position so for example if we are at 2 we want to get half of this so 2 divided by 2 is 1 and we are going to get the value of one so and then similarly if you look at this case one the first thing it will do is um lo try to half it and we're going to take the ceiling of that so one or we're going to take the floor value of that so 1 divided by 2 is 0.5 so it's going to 1 divided by 2 is 0.5 so it's going to 1 divided by 2 is 0.5 so it's going to give us a 0 if we take the floor function and then odd is n divided by 2 plus 1 so we're going to add a 1 to that and that's how we're getting this one so i have i hope that is clear how we're getting this position so we'll do math dot floor here and pass on um the index we're at and divide by two so this is how we're getting each of the positions after we have um our position we want to check if um the index we're on is odd or even so we'll say if i mod 2 is equal to 1 that means this is odd so if i mod 2 equals to 1 then what we need to do is in our answer list so at that index what we're going to do is get um that position that is before at the half position of it so this is what we were talking about so if we're at four we want to get the position of um so let's say we're at five and what we want to do is we want to get the position um two here right because uh five divided by two is two point five so we just want the 2 and then we want to add a plus 1 to that so we're going to take this value here 1 and then we are going to add 1 to it to get this to so this is what we're doing in the odd case so here okay so let me go back here so we will say so at that index we want to put the answer of that previous position maybe i should call this half position so it's a little bit more clear so we can call it half position yeah okay so we're going to take that and put that half position value here and then plus one okay else that else means it's even and here all we need to do is just say the answer at that index is going to be equal to the answer at that half position because we notice that um the even numbers have the same number of ones um when they're halved and the last thing that's left to do is return answer okay so let me run this why did we get a wrong answer um yes i realized the last number was not set and i forgot to add a one here so if i run this should work okay yeah awesome so now it's returning correctly and then submit yay success | Counting Bits | counting-bits | Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)? | You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s? | Dynamic Programming,Bit Manipulation | Easy | 191 |
465 | hey everybody this is Larry this is me doing week one of the league of July weekly challenge premium challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this poem 465 optimal account balancing so you come in transactions from to an ml return the minimum number of transactions to be quiet so the debt huh okay well so um some of this is just knowing literature and I happen to know that this one is kind of very tricky to do but the problem the thing is that um you know there's only eight transactions so that makes it slightly easier um because then now what is this stuff anyway because then now we can do some sort of uh basically crazy proof for us and hmm thank you let me think about this for a second no I mean it's going to be uh proof for us but I feel like this is the one that uh this is the problem that won me a contest uh on lead code um basically more but less about this one but I think but like that day and where I was probably way oh and today I'm struggling to think well remember how I did it um though that one I did know how to do uh but I think it's just a bit mask thing um in that okay and that you ask every um subset of transactions and then ask if you can settle that in one transaction and if you can then yeah then you can just minimize it over order submask and given that transaction is eight I think we should be good I think that's the idea of a man not gonna lie like I feel like I should notice immediately and I do recognize this as the problem in which I won the contest on um though not exactly the same way but it's still a little bit busty today maybe okay so yeah so let's just say and is he to the length of transactions right and then now we return um maybe say get mint of zero right um and this one we're gonna use bitmask uh I already kind of did a very brief overview of the mask on the July 1st daily problem I guess it's the same idea so I don't want to repeat things literally on the same day so definitely check out that problem and let me know if you have any questions still in bed mask but the idea is that a big mask is in a way of seeing a way of um Boolean values so yeah and then now we have to do the again Min function and then we have the current mask um yeah mask is equal to then we return zero because that means that we're done right otherwise uh yeah so then now we do 4M the current one is you go to do away if and you could do this with the three to the end algorithm instead but I'm I don't want to go over it so we'll do the four to the end one instead uh but yeah if um but do look it up if you're curious about it if m is not used then and uh maybe something like I mean we can do something like good of M but we should pre-process this because M but we should pre-process this because M but we should pre-process this because oops because we know that uh so yeah let's do that instead right uh but let's just leave this for now but we should pre-process all of these so we should pre-process all of these so we should pre-process all of these so that we don't go from one to the end of them but yeah um so best as you go to Infinity for now the base case and then if this is good then we do best is Men Of best uh one plus get min of M use this and then we return best and that's pretty much the entire idea really um we have to make some optimizations we have to uh do a caching thing but that's pretty much it so basically now we have to calculate whether what's the good point right so the good thing is that we can figure out something in one move right so yeah so maybe we have a mask right like a good function uh can one transaction function something like that I don't know that's a terrible name but of a mask and basically the idea is that we use that transaction so now um yeah so let's say we have a lookup table is a good collections.counter right is a good collections.counter right is a good collections.counter right I'm trying to think where there is a I think there is a way maybe I'm a little bit off on this one because there's a way in which this can be done in zero transactions right because like if they all net out to zero then the answer should just be zero right all right well let's just write this function for now and yeah that's a terrible name but yeah so then now flying range up and if uh look up of transaction transactions of Pi of from zero uh we added to all right let's just say a b and c is you go to transactions sub I and now we have paper and that should be good right and then basically the I the idea at the end is just that if um yeah 4K um so basically we want to just return the number of keys left and ideally so if okay yeah uh non-zero is equal to okay yeah uh non-zero is equal to okay yeah uh non-zero is equal to um look up that values length of this uh for x and of V until uh if V is not zero right and then basically now we return this number maybe and then here maybe we put in two classes right so for m in range of 1 to the N we want to say it um of M way so let's just say this is equal to that if V is equal to zero that means that you can do zero transactions so maybe we have a two things with zero is equal to and then one since you go to so then zero is that a pen m and then yeah and then if V is equal to 2 meaning if one person pays the other we do it here I don't know that this is quite good this feels weird to me to be honest but I guess technically this is once but we want to do another one for zeros right uh let's run it real quick does this time out it does oh um it's because this can be zero for some reason um that's unfortunate let's make sure that is it zeros I never remember this one okay so zeros oh this is true that this can be nothing and then one why is this so one and a two right so oh this is this minus one what a typo okay right and that's pretty much it uh we just have to remember to catch the mask so of course Mass can go from zero to two to the N minus one so let's catch that right uh so yeah has cash is you go to force times two and then cash is you go to none of this length and yeah if you've seen me done uh what am I doing I was gonna say it looks the same actually the same but I yeah a lot of liquor Farms today so maybe I just need oh no hmm yeah like I said today I'm not the same so I put three but you can do this in two maybe my assumption is wrong man hmm because it's taking all individually but actually zero can pay two and three and just skip one as a middleman right wow I am like really weird about this one hmm I thought there's someone like this but yeah thank you maybe it wasn't the same problem maybe I try to keep making the same month but yeah maybe I can just do like payers is you go to the link where it is greater than zero right so the payer should is it always to case if there's one pair and two receiver you can always resolved that way but if the two pairs and two receivers it's not necessarily true that wow I really have no idea to do this one maybe I'm not gonna lie I uh hmm wow I mean huh yeah I don't know how to do this one well I mean I know I stopped the idea but let me have to reset a little bit sorry uh sorry that I raised a timer 14 minutes or whatever um how do we set it a little bit what is so there is a case which apparently is this one for example that you may reduce tweeze the two oh here's some Blue Force but not like this hmm made pressure I mean don't tell me it's Max flow is it Maxwell Max full uh what would it be on it's not bipolar matching I mean it kind of is but I don't know that you can minimize the number transaction from the max flow foreign Hungarian algorithm that seems very high powered though sorry friends I've I thought I knew this one but I clearly do not I think maybe there's some confusion on my part um trying to figure it out a little bit it is some kind of proof not before it's been exponential okay but I think clearly I'm um missing some for part of it right oh foreign the 12 people they say maybe I could take advantage of that basically for each user that owes money and then just pay some subset amount to pay off but then you have to keep track of state and stuff that's kind of hard right this is kind of right but it's not in a general sense I need another thing to kind of I thought that you can so the reason why I thought this way was that I thought you could build these components up from one transactions like you can merge them into one transaction it seems like uh you should be able to merge them into uh more transactions maybe I could take a friendship to factors as eight but man am I struggling today hmm foreign the number of things there's one pair and two receiver so that would be take two transactions two maybe I don't know this is quite right um also because if this is right then we don't need all this thing we just kind of do this math with it right so this cannot be right with transactions of one component if I'm missing something missing an observation I guess now I guess this should be right in a sense that if this is not and this could be bigger than that I guess I don't know thank you sorry now I'm in playing around mode so uh what does it see and if that one night out and it's just really zero but I don't think that's the case though this is the pen that's why but why oh three people no I mean it should oh but am I confident about it to be honest not at all give us a minute okay so basically this is the same thing but the four instead of three so that's gonna go all the way man oh so four people are in five people involved but the answer is three and it requires all of them uh because two is playing three years I'm right now okay not gonna lie I don't know that I know how to solve this one anymore I think I need it like I said I think I need to reset but I'm not really doing that well the last 10 minutes uh man I have no idea missing something like Rudy silly right we said okay I mean there's gonna be some proof Force given that it's just 12. I think there's some like I mean 12 times 12 is 144 of it the brute force of that is going to be too much right the eight transactions is it true that most is only six pairs and six receivers that's still like I don't know about the 100 that means anything I do yeah I'm really struggling this one uh foreign friends this is like the I think there's a bigger struggle I've had in a long time because you the problem is that you can partially pay off someone So It's Tricky I'm trying to visualize everything in my head so the worst case is going to be just the number of transactions what is this one maybe I have to examine this one a little more actually it looks a little bit funky I don't even know how to put Foresters that's what I mean I think this is a proof for us solution to be honest maybe or someone calls in another so how do you do it in three oh I see then zero to three you give four bucks instead and then now two can give four also four bucks and then the additional one is just who receives an extra Buck four so one to four of one right something like this hmm how do you even propose this there was five people we only need three transactions foreign similar one which is just this one uh with just ring two and that could be just two transactions because zero three four one four oh yeah one four right I think I messed this up actually I don't think that's quite but I think I thought this was a zero actually like that so this isn't quite right but still that is another case that I would fail so I don't understand if I not I have to understand it if I were to solve it and this one two so four receives five bucks so 1 to 43 has to stay right probably I should have no idea what the solution is to do this and do it four receives five bucks do we receive four bucks how do you even do this in three oops I don't even know how to do this manually the number of force to give the money to two I mean you can but that does nothing right one get the money to two that's still four transactions and uh okay I'm so confused about this one actually so zero is minus two one is minus three two is plus four and four is plus five how can you do this in three transactions did I miss copy any of this could I do this and maybe unlocking this is the key oh and two is minus four whoops I forgot that point how do you do this in three transactions I see wow that is a tough thing okay I see it's two seven to three four bucks zero to one and two and oh sorry CO2 four and two zero uh one two four in two way right something like this foreign how do you get that from here and that's the thing right is it enough to do these maybe that's the part that I just kind of got confused about but that's not in one transaction right that's one bunch and that's what I was trying to do kind of live with these things like that's one transaction sure how many transactions is these foreign maybe that's it maybe I'm just kind of what's that's two transaction right so how do you do that math and that's what I was trying to do here I guess right uh okay that's it oops let's say pair is equal to this the receiver is equal to this right and maybe we want uh Max of payout receiver or if pair is equal to one and return receiver a receiver is equal to one we turn pair otherwise what happens if you have two right let me just maybe return Infinity I don't know if that's true to be honest that should I just work for that one though I don't know why it doesn't because basically yeah actually I don't know why this doesn't work for this one oh because it's a subset of transactions and given off for this will return Infinity so instead just two individuals then it's just one and one um this is the so we want to match to zero one and four but there's no individual transaction that does that it's just all ledger right I guess it's just is it you can mask him that way how can it be maybe it does I don't know let me try it on please set your mind so now mask is going to be uh the number IDs so okay let's just say we have something like this all right let's say we have a general lookup yeah I am struggling on this one and then we just do foreign look up that keys if but you can even do the match up one at a time I don't think there could be something like uh like a case could be something like I don't know three two four and it sums up to nine right so like you want like a uh three and six maybe no two and seven no five and four I mean this is a bad example so you have something like this and then you have a five and four and none of these subsets match up with the other one right so you have to like look at it all together and then it takes maybe this point was right but still wow I don't know this is the longest I've done one for a while okay thank you foreign thank you I guess it's just the same idea but then there's like two to the fourth twenty four how do I like photo you have to do instantly I think I got it okay I have to do instead of people right thank you I don't think that's right though I don't even know how to be first to be honest okay fine we said please let me set what would the recursion look like before first then we just go calculated Maybe we have the current index and then yeah okay and then basically for the current index we keep on finding money to give it to it so okay so if look up okay basically what I'm doing now is just doing basic backtracking and then seeing whether interesting whether I can get something from that then uh okay so then now if lookup of index is zero and we continue foreign because we'll just assume someone gives me the money otherwise we have to find people to give the money to so we do a recursion try to give this money as this person as much money as possible uh okay so now this is the name this is a Min of this and not cover of index look up index money so too so that's just backtracking put none would I get none from where we're turning none oh I forgot to return um so we're going from lookup index to I as much as we can okay so you give money to one for five no I just couldn't look up real quick oh it's not n it should be just 12. yeah I mean we can do something with the ID but I think for now I'm just trying to show that is why oh geez all right so now we got it right but is it fast enough huh thank you I might have some print statements all right it should time out but it doesn't it takes a long time but it doesn't time up that took a long time for me to figure out a bit I don't know that I believe that this is the intention though I mean this is just backtracking I thought it was going to be some big mask thing maybe I over complicated things but I am I got a slow one though so I feel like this isn't quite don't intend the solution I'm not quite sure to be honest with the intended solution is yeah so if you skipped ahead from the beginning uh well you should have because this took a while um but yeah I mean I just kind of did a backtracking and kind of worked I feel like there's still a better solution but basically what I do is that for each payer I basically keep on paying someone in a very Brute Force kind of way as much as we can until their debts are paid and stuff um the thing to note is that because there are only 12 items um that's mostly the cheap putt oh sorry 12 people um it's almost like a weird Brute Force Hungarian matching thing except for the order that um does matter in which you kind of process them so I don't know I'm not comfortable about this one sorry it sounded a month week but uh I need to take a break so that's all I have with this one let me know what you think let me know how you did it let me know if there's a better solution um I'll see you soon so stay good stay healthy to get mental health goodbye and take care to do | Optimal Account Balancing | optimal-account-balancing | You are given an array of transactions `transactions` where `transactions[i] = [fromi, toi, amounti]` indicates that the person with `ID = fromi` gave `amounti $` to the person with `ID = toi`.
Return _the minimum number of transactions required to settle the debt_.
**Example 1:**
**Input:** transactions = \[\[0,1,10\],\[2,0,5\]\]
**Output:** 2
**Explanation:**
Person #0 gave person #1 $10.
Person #2 gave person #0 $5.
Two transactions are needed. One way to settle the debt is person #1 pays person #0 and #2 $5 each.
**Example 2:**
**Input:** transactions = \[\[0,1,10\],\[1,0,1\],\[1,2,5\],\[2,0,5\]\]
**Output:** 1
**Explanation:**
Person #0 gave person #1 $10.
Person #1 gave person #0 $1.
Person #1 gave person #2 $5.
Person #2 gave person #0 $5.
Therefore, person #1 only need to give person #0 $4, and all debt is settled.
**Constraints:**
* `1 <= transactions.length <= 8`
* `transactions[i].length == 3`
* `0 <= fromi, toi < 12`
* `fromi != toi`
* `1 <= amounti <= 100` | null | Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask | Hard | null |
689 | hey guys how's everything going this is Jay sir who is not good at algorithms in this video I'm going to take a look at 6 8 9 maximum sum of two three non-overlapping separation we were given non-overlapping separation we were given non-overlapping separation we were given a ray of numbers of positive integers find three non-overlapping sub-arrays find three non-overlapping sub-arrays find three non-overlapping sub-arrays with maximum sum each sub array will be size K and we want to maximum maximize the sum of all three K entries return the result as a list of the indices represent the starting position of each interval if there are multiple answers return the lexicographically some other one so input of one is like this the K equals two so we return 1 2 6 7 3 so this sums up to the largest one the number will be one not be empty as I will be between 1 and this you are between 1 on the floor so for this example I think we better analyze the example for the simplest format with a K equals 1 so if K equals 1 it means that actually we need to find 3 numbers with some three numbers sums up to the largest one right after three numbers maybe we will we find it may be hard let's just rush it down to one number crush it down to one number for one number Wow we're just linear time right just a loop through all the numbers and find a maximum so it's no big deal if two number if you got in to search for true number what happened well for two numbers how many pairs are two numbers well it's gonna be in two times n minus 1 right and we can't summon them up so it will be two and they get the maximum so this is linear Square could improve it well let's analyze the process first one we pick a number here and search all the maximum right so actually rather than we compare each pair some of them up actually for the starting position and here we need we only need to get the maximum of all these numbers right now if you pick a two but still you get two just to pick the maximum from this disarray right so now here's the tricky part you see we're checking starting at one and starting to but we're getting the maximum of this array and this array sub array and these two sub R is almost is the same right it's only except the first one so actually for that if we go down to the last one like 1 2 + 2 5 down to the last one like 1 2 + 2 5 down to the last one like 1 2 + 2 5 there's only one number left so this one itself so it's the problem becomes for each position we need to get the maximum of the rest sub array and that sub array could actually be one linear time to get it from right left so if we cache the max suburb max out of sub array from right left we could actually if it gets the maximum like maximum from right for easy for this index to the one and then we could loop from left to right and get the result right like we're getting one but we know the maximum of the right and then get to the max another right so this will result could be improved to a linear time actually - but it's linear right now actually - but it's linear right now actually - but it's linear right now here's the problem if we get it to three numbers could we reuse our idea here well if we focus on the first one it will be the same right same as it will be the same problem here with two numbers but with one left right and then we could this linear time and then for different if we choose to but the two could be actually in the middle right if already done so actually if we do it like this it would be linear time for starting next to be linear right knee no time for the starting eggs and the for the rest it will be linear so actually it will be o to the square but what do you but what if we choose the middle one the three numbers right if we choose through to as the middle one then you see the left max and the right max right and now if we choose one and we get left max and right max all right so now the left part of the right part actually is symmetric so actually we could use one inner time to get the maximum from left to right and the user one linear time from left right left and then and use the last linear time to collect all the result right to the final results so actually we could improve the result into linear time right cool let's start so what we need actually is to summarize is max array oh there's a problem so this is index at index I know this is actually the Phenom K equals 1 right if K is not one is to actually you see that if we take a look at the starting next the sound actually could be reduced into what a one-element right be reduced into what a one-element right be reduced into what a one-element right into our case here so first week splits our implementation to how to say for step the first one is get crush it into K equals one array and then collect max array from left max array from right and then get the result by fixing needle element okay the first one we the index array right so we could choose the how to say this is a because this is numbers its sums for let I 0 isomer then I should be stopping and the carpark a if this one is 1 if the scathed minus K right so yeah a plus so and we are getting the sum of 1 2 and 2 1 and 1/2 so we could use a sliding window and 1/2 so we could use a sliding window and 1/2 so we could use a sliding window to avoid calculating in multiple times sly window okay so let's sum equals zero okay for the zero we some of them up sometimes I and after we summon them up like one okay three okay we need to push this element in right so if no wait a minute if I is a for K equals two when we sum up to three and the third one we need to subtract the first one so if a is bigger than is equal then K some actually was substract the nums I minus 1 and the minus women this 2 so this is 2 we need to subtract this so this is I minus 2 right 4:01 tool because cake was too so this 4:01 tool because cake was too so this 4:01 tool because cake was too so this one is minus K minus r1 minus 1 this is minus 2 yeah okay this is the right some so some push some so what we add a new one if it is mm-hmm no I use not one if it is mm-hmm no I use not one if it is mm-hmm no I use not started here I should be to the end and we sub some that I equals zero some the current one and then we'll in K mu order of K we subtract it's obstructed but when we already push it of course I in speaker then K minus 1 worse I to push it right we push the first sum 3 to it and it goes next one we get three push it and then get three push it cool so this is the Sam's array now the max array from left well in this should be inclusive okay so let max equals infinity max from left 4 equals zero loop through all the sounds if some eye is bigger than max the previous max could be used as the current max right so actually we could max equals math max sums I this is a new Max and Max from left with push max right max from left okay we all do the same from the right rather than we are rather than on shift I think we could just initial I because this land hasn't change we could initialize it and because our shift is very slow array some stuff in a few zero and this is from right and so okay so here becomes this minus one it will be bigger than 0 minus 1 minus this for max sums I max from right equals max mm-hmm let's try to lock being that max mm-hmm let's try to lock being that max mm-hmm let's try to lock being that lock max from left max from right we got some right 3 8 yeah this should be right yeah things I think we got it right and the last step you fix the middle element and try to get the result which is from actually from the sums right so we will just laughed it could start from the yeah it's just three elements right love this what actually be one okay we'll be okay so this will be vetted okay so let okay max at last we said to infinity again for that I course what it was of course one I smaller and some stun n minus one and Maxima should be minus two right okay now I plus one so the problem the max equals mathematics max okay so the left part would be some max from left I'm Anna Swan plus sums I plus max from right I plus one finally return max is not valid for input ah return the index right oh my god okay oh I know we got the problem so it's a rather than the max I think this should be max index max from left you should push to the index okay findex if that if the index I think okay I'll just update the index likes index oops so if I kuzey rule then it should be itself right let's just do the same as this equals zero or we could just say zero-zero we start or we could just say zero-zero we start or we could just say zero-zero we start with one and say if sums hi is bigger than sons math from six PI minus one if a speaker than it then I equals hi if not we will set it again to the previous one right this your work and yeah here is the same if that's the case you should be minus two and we said some length that's one equals some sense minus one we set the same here if Sam's eye is bigger than sums max from right I plus one if he's bigger than it then I was high the other case it should be depleted II the previous one okay yeah and now we get this here we need to keep your max maximum and the result that result goes low okay so some equals this right sums plus some light plus this should be max index from left max index yeah if saw me speaking IMAX Mexico some result equals of course this right hi cool so at last will return the result hmm Rana sir what like this week output a 3 5 3 4 5 ok we log the sums max index from right okay the sum is oh we have a run answer of the Sun is not good Sam is not ready Oh Sammy's right three yeah twelve but six this is right and now the biggest it says the maximum from left okay we useful originally initialize them to 0 the first one should be zero and I start from one this is Sam's if it's bigger than the maximum zero no so it should be this previous one hmm why for weight becomes Oh found left okay zero three and four this is right and now for from right is six five four yeah this is right so now which is the middle start from one to this one okay Sam's me it because the maximal index from left yeah so here in x is 0 plus sums I yet some time equals Sam's I equals three customs max knees from right I plus one so we get this I we forgot to update them and updated mmm ready if some smack hey update blacks or update max for one some 0s here so it should be three 3:19 right this 12 got to 33 it is this is 33 Lock them up you got 33 so the index should be index is 3 4 or 5 wait a minute some e33 max index from light left by Ike was 4 or 0 1 2 3 4 ah haha what's wrong here okay so the Sun three eight there is no problem for at one maximum is 19 so zero one four and then update zero one two three we got eight plus not here zero three four this is a 24 now we get 13 8 Oh No overnight overlapping right non-overlapping so we're going to do the non-overlapping so we're going to do the non-overlapping so we're going to do the sums is the Ray ah we need to go to the non-overlapping my bad non-overlapping my bad non-overlapping my bad so if we got one too this is a sum right but it's overlapping so when we are going to choose to we need to choose - not one but - if it is need to choose - not one but - if it is need to choose - not one but - if it is one then it's one if two - one - two one then it's one if two - one - two one then it's one if two - one - two so actually - k overlapping is something these sums is actually start with K right so it's okay but each number the sons array each actually contains K numbers so if you want to avoid overlapping this is right this is not right actually I should not start from one exactly it should be started from where is it if you if Kate was one then is from one if it's two if you're from - from one if it's two if you're from - from one if it's two if you're from - yeah it's okay start from I should start from K - K uh-huh yeah from K - K uh-huh yeah from K - K uh-huh yeah I see aah overlapping he's the problem sad we got the wrong answer as always let's laugh it's login yeah see what your what we are doing so the Sun would be 4 to 3 or B won't sick 9 there will be eight threes right okay and then the maximum you actually to the left and oh I see what happened when we kept when we are checking the right index from right we are told to return the lexically go up smaller ones so from left we must check strict larger but here actually could be equal yeah Wow very tricky not that it still we lock it down hmm not a number what won the soccer reason isn't right okay some zero eyes bigger than one why I - - you should be - okay I am so I - - you should be - okay I am so I - - you should be - okay I am so stupid very tricky cool finally were accepted but actually I've failed four fell for like three times the first time is about the sums I forgot to handle the K very well I rise some dummy one or two and this next one is over a nappy I forgot overlapping thing and leads to mistakes here the last one if there are multiple answers return the lexicographic smaller one so we need to choose those smaller index for from left to right it's so strict bigger but from right left if it's equal we could update the index so that's some tricky parts and let's try to analyze the time and space complexity as we already add that assist you should be linear time a space yeah we use this sums array index array so it's a still linear cool so that's all for this problem hope it helps for this kind of array problem what I learned from previous problems is that sometimes for maximum array something consider sliding window of worried to calculate and one by one like if you want to come if you want to calculate the sum of three and adjacent elements we just create a sliding window of three elements and move it right to left to right so it won't be you know time and a calculate the sum array which we're doing like this the second one is always considering cashing a son not only about this problem but something like gets the sum of sub-array we could actually do sub-array we could actually do sub-array we could actually do subtraction by subtracting the sum that I and the sums SJ right and from left from right cash the sum and there might be some leadings there another thing is about like the three elements threesome fix the middle one and it will lead us to the symmetric left problem of the left part and problem on the right part so it's symmetric and it will be just right just be a big good enough to be the solution of caching a sum will be just perfect for these kind of cases anyway hope it helps see you next time bye-bye | Maximum Sum of 3 Non-Overlapping Subarrays | maximum-sum-of-3-non-overlapping-subarrays | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
**Example 1:**
**Input:** nums = \[1,2,1,2,6,7,5,1\], k = 2
**Output:** \[0,3,5\]
**Explanation:** Subarrays \[1, 2\], \[2, 6\], \[7, 5\] correspond to the starting indices \[0, 3, 5\].
We could have also taken \[2, 1\], but an answer of \[1, 3, 5\] would be lexicographically larger.
**Example 2:**
**Input:** nums = \[1,2,1,2,1,2,1,2,1\], k = 2
**Output:** \[0,2,4\]
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] < 216`
* `1 <= k <= floor(nums.length / 3)` | null | Array,Dynamic Programming | Hard | 123 |
496 | in this video we're going to look at a legal problem called nest greater element one so we're given two integer array and both have unique elements numbers one is a subset of nums too so we want to try to find all the uh less greater l uh elements for nums one's elements in the corresponding places of numbers two so let's say we have an example of four the next greater element or the next greater number and numbs 2 is going to be in this case we cannot find it right so in this case 4 you can see the next greater ones greater element that are greater than this element right here is not going to doesn't exist so if it doesn't exist we're just going to return negative 1 for this number so in this case for this element we cannot find the next greater element in nums 2 so we just put negative 1 as does not exist right so for 1 in this case we have a greater element which is three so in this case we're going to put three as the next greater element for element one and for element two in this case it's right here right so it's at the border so it doesn't there's no elements that are on the right so in this case it doesn't exist then we just put negative one as the next as there are no greater number right so we can see there's also another example where we have two four so this is a subset of this array and basically uh two the next greater element in this case is gonna be three right so we have a 3 here and the and 4 the next greater element in this case doesn't exist so we just put negative 1. okay so how can we solve this problem so one way we can do this is we can uh scan right for each element that we have in nums two right in this case for each and every single element we're going to scan to the right to see if there's a to two to find an equator once or to find the next greater element in this case for uh four we find that element in nums two and we scan on the right side to see to find the next greater element in this case it doesn't we cannot find it then we're going to return negative 1. and then we find then we're going to look for 1 in nums 2. in this case 1 is here so in this case we scan on the right to see if we have an s greater one a greater element that's greater than 1 in this case we have three so we put three there but this will give us a time complexity of big o of n sorry big o of n squared um so how can we solve this problem in a linear time complexity so to solve this problem we're going to use a stacked structure so stack data structure is a lasting first out so if i have a stack and i have an element here um the first element that we inserted is so the last element that we inserted in this case let's say five this is the element that we're going to first remove right so what we're going to do is we can have a stacked structure to keep track of all the elements that uh that we cannot find the nest getter elements and we just insert onto our stack and once we find an element that's greater than the top element that we have on our stack then that will be the next greater element for all the elements that we have in our stack let me show you an example so if i have a stack empty stack initially right we have an empty stack if the stack is empty then we first add the first element that we have an array onto the stack so in this case it can be two so then what we can do is we check to see if three in this case element three is bigger than the total element that we have it is and we just remove that we're gonna set two next greater elements gonna be the current element which is three okay and then we're gonna add three onto our stack then once we get to 5 we check to see if 5 is bigger than the top element that we have in our stack in this case it is so we just add we just set 5 as the next greater element for three okay and then we add five onto our stack and then once we get one we know that one is not bigger than five so we're going to add one up to our stack then zero then seven is greater than zero that means that's seven so what we're going to do is we're going to set all those elements the next greater element is going to be seven right oh sorry this that should be seven okay and then we get insert seven onto our stack and then we continue we saw three so three is not bigger than seven so we're going to add three onto it so what we notice at the end after we traverse after we iterate the entire array is that we know that all the elements that have on this greater elements will be at will be stored on our table but all the elements that we don't have a that does not have a greater element cannot find the greater element will be in the stack which is true seven does not cannot find an escalator element three you cannot find it in this greater element so what we're gonna do is we're gonna pop each and every single element off the stack and set three set each of those elements to negative one because we cannot find the uh in this case we cannot find the net equator element right so at the end if i have if this is num two right and i have a num one which is two three five right so let's say this is num nums one this is number two uh what we're going to do is we're going to iterate each and every single element that we have in the numbers one and then what we're going to do is we're going to get that elements uh key sorry get that elements value in a table right this is our table so in this case two has a value of three so we have array first element's three for three has a value five so for the second element it's going to be five has a value seven so we store seven there so to do this in code first we're gonna have a stack which has a type integer and then we're also going to have a hash table or a map which stores less greater element for each and every single element that we have in numbers two right because numbers one is a subset of numbers two so what we're going to do first is we're going to iterate every single element that we have in gnomes2 so once we enter for each iteration we're going to uh check to see if our current stack is empty if it's empty we can just add it on to our stack add the current element to our stack if it's not empty then we're going to see if the top element that we have on our stack is actually uh bigger than the uh sorry is less than its current element right if it is then we're just going to um get each and every single element that we have in our on our stack and set the current uh set the every single element that we have on our stack and the next greater element to be the current outlet right so let me show you an example well let me demonstrate that in code actually so i is equal to zero i is equal uh less than uh nums to that line and for each iteration we say while the stack dot is empty right is false so it's not empty and we know that the top element that we have right so in this case is going to be nums 2 at i is actually bigger than the top element that we have on our stack so dot peak if it's bigger than then what we're going to do is we're going to get the top element off the stack so the top is equal to stack dot pop okay so once we pop the top element off the stack we're going to say map.put for this current item right and the current item is going to be nums to i sorry uh the current item is top right so the top item the next greater element is going to be nums to i right so we set that as the next greater element and then what we're going to do is we're just going to get each and every single elements that we have on our stack onto the table right once we've done that we're going to insert the current item onto the stack because we haven't find an escalator element for this element yet so stack.push nums so stack.push nums so stack.push nums to i so once we've done that we're just going to iterate the entire num stew array to find their nest greater element and save it onto the map so once we've done that just like i said earlier there could be a situation where we still have elements that we have left in our stack so we're going to say if while stack dot is empty is equal to false right so it is not empty yet what we're going to do is we're going to get the top element that we have so top is equal to stack dot pop so we can top element off the stack and then what we're going to do is we're going to say map output for this top element we cannot find the next greater element so we're going to set negative 1 for that and then once we complete this part we're going to create an array that we're going to return at the end and this array has a size of nums one dot length and then we're just going to iterate all the elements that we have in nums one and then get their nest greater element added on to our result array okay so nouns one dot length so result at i is going to equal to uh hashmap.getnums1 uh hashmap.getnums1 uh hashmap.getnums1 at i right so for each iteration we're is going to save their nest grid element onto the result array and then at the end we're going to return results okay now let's try to run the code and let's try with a few more test case and then let's try to submit and you can see we have our success so this is basically how we solve this next greater element one in a linear time complexity or where n is number of elements that we have in nums 1 and nums 2. so there you have it and thank you for watching | Next Greater Element I | next-greater-element-i | The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array.
You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.
For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.
Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._
**Example 1:**
**Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\]
**Output:** \[-1,3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3.
- 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
**Example 2:**
**Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\]
**Output:** \[3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3.
- 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1.
**Constraints:**
* `1 <= nums1.length <= nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 104`
* All integers in `nums1` and `nums2` are **unique**.
* All the integers of `nums1` also appear in `nums2`.
**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution? | null | Array,Hash Table,Stack,Monotonic Stack | Easy | 503,556,739,2227 |
890 | hello everyone welcome to quartus camp we are at the 21st day of may lead code challenge and in this video we are going to cover find and replace pattern so the input given here is a list of words or the string array and string pattern and we have to return again the list of words which matches the pattern given in the input so let's understand this problem with an example so here is a given input strings and we have to match any words given in this list matching the pattern and we have to return it so if a word match the pattern given is said to be having the same set of permutations of character but the characters are different for example if a b is a pattern in this case our the matched pattern word should have same permutation repeated so for example let's say instead of a there is an x and instead of b there is a c so wherever a appears x should appear wherever b appears c should appear so if the word is x c d and this is not matching the pattern same way if the word is x c it is not matching the pattern because a maps to x and b maps to c so if x c is given then it is matching the pattern because it is repeating or having the same permutation as the dot the pattern string so now getting back to our example given let's start from having abc is not matching because abc having three characters and all three characters are different same way the second string also having three characters and all three characters are different moving on to our third word which is m e so let's map a with m so in that case instead of a m is there so next character is b and with b we are mapping e so now in the word the next character is also b then we should have one more e to match our b so this is the actual string given so it matches our pattern so we are adding that to our list same way the next string is also having one character and the other two characters are different so this is also going to add to our result list and other two strings are different from the pattern given so we are not adding them to our list and this is going to be our output so how are we going to approach this so if we are trying to map a character with another character and see whether it is repeating in the positions take the string a q and a b in this case both a and a are c so if you try to map a with a that will bring another confusion so if you are trying to count the number of characters so in that case a b a and a b will also have the same kind of characters so how do we actually approach this problem so we are going to convert all the given words to a number pattern or an integer array and match all the converted patterns to the given actual pattern so if any of the array matches with the pattern array then in that case we are going to add that to our result so how are we going to convert the given words to a number pattern so we are going to take the first occurrence of the character and fill in the rest of the array with those characters to convert the given strings to integer array we are going to get the help of a helper method where we pass each string in the input to that method to get it converted into an integer array so let us start by having our patent string a b here in this string the first character is a and the occurrence of a in this string is this position which is zero and second character is b and occurrence of b for the first time in this string is this position so we are going to fill in one which is nothing but b occurred at the first index for the first time so moving on to a third character which is b again but actually b has occurred already in our string which is at the index one so we are going to fill one again so this is something some pattern we follow you can follow any pattern to convert the given string to an integer array so this is one of those patterns and i am simply going to fill the numbers with the first occurrence of that character in that string so now the pattern has the integer array which is 0 1 so let's start iterating the given words in the words array so the first word given here is abc and abc each character is different so they all occur for the first time in the same position itself so that array is gonna become one zero one two as a occurred at the zeroth index b occurred at the first index and c occurred at the second index so moving on to our second word in the list which is deq which is again follow the same pattern asset of abc because all three characters are different and they're gonna have its own position as the starting position so its value is also going to be 0 1 2. so the next word in the list is going to be m e so here the first word is m and its index is zero and second character is e and its index is one and again e brings one to the third character as well so it is going to follow zero one which actually match the actual pattern string which is given in the input so this is going to be one of the strings which is going to be added to our result list so let's move to the next word which is a q and a q also follows the same pattern as it of the pattern and the mee string which is also going to be one of our output so as we are going to compare each array with this array it matches so we are going to add this as well to our input string sorry result list so yes the next word is dkd and the first character is gonna hold zero second character is gonna hold one and the third character which is t which is a repetition of the first character and its first occurrence in this word is zero and we are going to fill zero here the last so it is gonna have zero one zero which is not matching our pattern so let's leave this word and moving on to ccc so here all the characters are same so first occurred in this word c at index 0 and all the characters are c so the complete array is going to have all 0s which is also not matching our pattern so overall these are the two arrays that actually match the pattern array of given input so that is going to be our output so hope you are understanding this approach so first we are going to iterate each word given in the list that is going to take n time and plus one which is the pattern string and each word is gonna be each character in this words are going to be iterated and assigned a integer value so let's consider l is the average length of any given word in the list so it is going to take big o of n cross l time complexity and we are going to use a hash map to store the first occurrence of this characters and whenever needed we are going to get the value of the first occurrence index and put that into our result list so overall we are going to use big o of n space complex so let's go to code now so first let us write our helper method before getting back to our main method so yes here i have declared a hash map which is gonna store the index of first occurrence of the character and this is nothing but the length of the string and we have declared a new result array which is going to hold the integer pattern values and finally we are going to return this from this method so now we are going to iterate each character given in the past string so here in our hash map i am going to put the value only if it is not present if it is already present we are simply going to ignore so for the first time when the character is encountered in a word we are going to put the character and map its pattern so this is nothing but the size of the map at that particular point so if suppose the character is a comma b a b then when first a is added the size of the array would be zero and when first b is added the size of the hash map would be one so b is gonna hold one for all the time if suppose again a b is encountered it is not going to update that value in our hashmap so once the values are updated in our hashmap we are just updating a result array and return the result so here in our main method we are going to iterate and pass all the words given in the string array as well as our pattern to our helper method to get our result integer array and if any of the integer array matches with the patents in teacher array then we are going to add that to our list and return the result so yes let's run and try so yes let's submit so yes the solution is accepted so thanks for watching the video and the solution runs in three milliseconds so if you like the video hit like subscribe and let me know in comments thank you | Find and Replace Pattern | lemonade-change | Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**.
A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word.
Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.
**Example 1:**
**Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb "
**Output:** \[ "mee ", "aqq "\]
**Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}.
"ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.
**Example 2:**
**Input:** words = \[ "a ", "b ", "c "\], pattern = "a "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `1 <= pattern.length <= 20`
* `1 <= words.length <= 50`
* `words[i].length == pattern.length`
* `pattern` and `words[i]` are lowercase English letters. | null | Array,Greedy | Easy | null |
1,802 | Welcome to this Stylish Co. This is a medium level question. Inside this question we will have three positive integers N index and Max sum and we have to construct a like whose indexing will start from zero and the condition which is given below should be satisfied. Okay, so what will be the condition that the length of the Eric created by us should be n, that is fine and the value inside the area should be a positive integer value, where is the power, where is zero. From zero to lake N, there should be power in it. Okay, no. Sorry, between zero and lake n, it should have positive voltage. Okay, in the third condition, he is saying that he has the namas i - nas i + 1. that he has the namas i - nas i + 1. If you look at this number, then the difference that can be there between the numbers that we have, can only be one, cannot be more than one, so what would be the meaning of eating like that if If you have one A here on the index, it is okay, then it can have one A, or you can have one, or it can be zero, okay, or these three possible numbers will be sent that these numbers will come near it. One number increases or one number decreases or the same number remains the same. Okay, the third point is done. Now in the fourth point it is said that whatever is the sum, we have the maximum sum of the whole area. This max should not be more than the minimum, okay, and what should be the value of the index number which we have given here, it should be the highest, it should have the maximum value, what should be its mains, the life arrow that we will have. Whatever we need inside, we will first put all the numbers in it. We will give whatever is the sum of its area, it should not be more than this maximum sum and whatever number is there on the value of this index, its maximum value should be. And these above points are also fine to follow it, so that's it, our question is done, let's talk about its example, so here we have the first example of life, inside this we have what is going to happen in life N = 4 have what is going to happen in life N = 4 have what is going to happen in life N = 4 mains which I have here to become a payer, what should be the size of the area, it should be 4 size, it should be okay, what can be the maximum number of suns in it can be six, okay, so what did I do, I should have maximum number in the second index. So what did I do by going to this maximum index and keeping it at 6, it is fine and I have other values, how many zeros and zeros have become on the remaining values, then look inside this, I have a maximum of 6, but what is my required condition? That required condition is being satisfied. That required condition is not being satisfied here. What should be the condition that if I delay the difference of these two numbers zero and six then what should it be? One should come, okay, it should be absolute one, okay if that No, okay, so this is not what happened, now what I do is, inside this, I flowered like one and one, okay, now what is the maximum total sum, I calculated its four sum, so do I have my now? I have to take care of the area which is not timed, maximum index should be true, so what do I add next number, I add one on this one, like on this one, I made it you, I made it ahead of all the others, I kept it, so my It is satisfying the required condition but my S of this ray is still 5, I want six, so where can I add in respect of this, I can add on this one. I can add it on one, okay, so if I add it on this one, it will become A, okay, if I add it on the back, then I will be getting something like this, okay, so the answer I have is The concept is that there should be maximum value on you, then what is the maximum value I have on you and you will be my answer. Okay, if we look at the second example of this, what kind of life do we have? In the second example, I am with us. Here, if there is a life of six, then I will multiply it, how can I do it one by one, okay now, how much is the maximum sum I have, after doing six, I have taken out the even, okay, if I have to put you in it, then how much will be the even, the index will be 7. Sari value of sari of pay like, it is going to remain in my future, if I have to keep it three here, then how can I keep it here, if I have one here, it will not satisfy my condition, then I will have to make it how many, but I will keep it one. I can keep the next one after this, okay, so one, so what is the total sum I have, here it becomes 10, okay, what is the value on my maximum index, 3 is the maximum value, yes and three is mine, what is our example? So let's talk about its solution approach, what power do we have, so like we did right now, initially we flowered it one by one, we checked whose maximum sum is happening, how much is the six, we took out the index of it. We need value for 2 days. We checked the condition. If the condition is not being satisfied, then we will get it done. Then how much is the sum? Even after 7, it is less, so we kept three. It is okay if after going to three, we got the possible answer 10. If we don't get the answer here, then we keep checking it like how far we can possibly check it, we can check it till 10 because we have kept 10 here on this index, so the answer we are going to get is A. Maximum sum will be ok then like the possible probability that we can have, from where to where, that is our answer. From here, it is between one to 10. Ok, so this is our answer. If we check it one by one, it will take a lot of time. If we look at the constant here, then the power of the tenth is nine, but checking it like this will take a lot of time, so we cannot do it with this approach, so can we try it a little. And see in the logical way, I have come to know this range, okay can I keep the value inside it according to this range, from where to where, between one to 10, so I do binary search inside it. Okay, between 1 and 10, find out the middle of it, how much will I get? After going to 5, I should check whether the value that is going to be inside it, do I have that value, if I have to keep it inside 5, then what will be the sum of time and area. It comes if it is equal to mine, if it is greater than the maximum sum, if it is equal to you, then it is ok, otherwise if it satisfies this condition, then I check the value above it is ok and no. If it does, I will check the value below it, 6, you will check 10. If it does, I will check four, you will check it. Okay, by doing this, I will like it, I will check it for four, then how will I get that like, what will I get? If I check 521, then three will come. If I do six, I will get almost 7 something. By doing this, medium will come. You can check your value on the needle. Okay, this is a matter of binary, how we can index. Will keep the value. Now let's talk about the like that I have within it, which has to be taken to the maximum sum also, keeping this index in mind, how will we handle the value of the like? If we look at this example of this example, Inside we have sequence, what type of ban power is there, so I can have one is ok, it can be you, it can be three, it can be four, if you want then you can go to four or even to Dr session. 1 and 1 is fine, so look inside it, I have like, what is this part, what is the constant taken out part, what is this part, it is happening in increasing order, meaning inside it is increasing by plus one and from here, this part goes on. What is happening near me, mines one is happening, okay and this part again, what happened to me, okay, from these three ways, I have seen it, okay, now like if I have to do what inside this question. I have to identify this four is fine, this four is mine, what is the maximum, now who do I want to check, then how am I checking, then the first thing is if my friend is good, what happens in the math that I have this What is it in increasing order, following each difference, making it in arithmetic progression, so what can we do within this, we can find the sum of these terms, so its formula is that we keep the first term, okay its own. With whom we do plus with the last term and inside it we multiply. Whose N/2 means the number of terms. Okay, so at N/2 means the number of terms. Okay, so at N/2 means the number of terms. Okay, so at this time see what is the first equation that I have, which means the first value. What is that going on? Okay, so the first which is here with me has been made by four. Okay, so what is this four with me? This is the maximum value, meaning you can use it as the first value, Shakti, for this one here. And the second should be the power and value for this. Okay, now what we need is to identify which is going to be its first term, which is its starting position, what is going to be the value inside it, so like if we index it, then I have it. Which index would this be on? Zero on one, two on three, four on five, okay, so on five, we have this value, okay if I calculate the value that I have, what is the value? Right now I have four, out of four, I have mined 5, so at this time, the difference that comes to me is how much is mined from one, so can I do this, not within this, which is being made in this sequence. There is a repeating one inside it because if it was running one then it would have been four. If it was running in > fashion four. If it was running in > fashion four. If it was running in > fashion then like if we count from here one three six 10 then here it would have been formed by doing 10 in greater than m. It's going on but 5 is coming so it means there are going to be repeating characters inside it so if I want to see its starting point then what do I do? How much difference do I have - 1 If I had the index of like these How much difference do I have - 1 If I had the index of like these How much difference do I have - 1 If I had the index of like these four, then how would I find it? How many three numbers do I have, that is, this value would have been on the third index. Okay, so the starting Joe. It may be even. What is its value? Three but in this example, how much will we consider as a0? Let us consider it as zero. Okay, so if we put it in this formula, then what will be the starting value of 'a' at one time zero? starting value of 'a' at one time zero? starting value of 'a' at one time zero? What will be the value of a0? Starting zero, this is zero, how much is the value of n? We have 4 when we add them, how much is it? We take out 4 and we get 4. Okay, now we need to identify the number of n², so min, if we look at this one and this one. When we look at ourselves, we come to know that what we are going to have is zero, but in reality we do not know what we are going to have, so what we do inside it is like the maximum value that we have found for our. If the like is starting from this position, then what will be its starting point in minutes, it started from zero, it is ok, from zero to where it will go to our value, so the value is ours, how many likes are there in it? 4 Yes, ok then. We will find out the sum of these two sides and what will we do with the sum, we will calculate what is the total sum and give it and compare it with ours. What is the maximum sum? Now we were looking at it that if we were looking at its left and middle, then our answer will be in this range. If this condition is not satisfied then our answer will be between meet plus one and the one which is on the right side. Okay, so let's do. If we have this in the code then first let's make our variable anti loft = 0 and right equal variable anti loft = 0 and right equal variable anti loft = 0 and right equal tu this will be equal to our max sum in between which our answer is going to be okay then like if we saw the example then first We had started our mains by placing one on all positions, we were thinking that our answer was going from one to there, so what do we do in this, we are going to get the maximum sum from it and make our mains from it. Let's give n so min, we have initially changed the value to one by one, ok, now after this, give us like which is our binary condition on the left, it should be like on the right, it is ok, we get it right, ok. And we will enter our one in it. Okay, now we have to keep the middle value and check whether the like which is maximum sum is equal to the number which is Erica's life which is maximum sum or not, then create a function here for your like. Whom we will keep as private return type, Bhole is ok, he is helping, so we call on help, ok, then the identity value will be our made ID and the total number of elements is ours, then after that we will get what ID we need. We will need the maximum in this, it is okay and then we will end up with the index. Now in this we find the like which is going to happen on the left side of us. What is going to happen on the right side is okay. Let's call it our left is equal to max. Whose like will we take? The index that we got, the like value inside it, we subtracted the like from the value that we saw, the middle value of ours, which is the current index, it would have been greater if it had If there is caste in value mines then we will keep it zero otherwise we will keep whatever value it is. Okay, this is done and from this we will also find the right for it Math dot Max. Okay, so in this we will be opening value minus or what? Whose will you be doing mines in this? We have N - 1, okay. Total number of elements N - 1, okay. Total number of elements N - 1, okay. Total number of elements from this, we will do our mines. Okay, and give our index. After this, compare it, if it is zero, then zero is okay, now it is done. We have come to know about left hand right. Now what we have to do is that we have to make our sequence equal. Okay, so let's keep it in our long. Let's call it left even equal. Okay, here we have our first. Type casted, give it long, what will we do after that, we are going to have value plus what we took out on the left, that's it, our submission is done, like open, multiply it by the total number, which is going to be N, then value. - If we click, N, then value. - If we click, N, then value. - If we click, then like is taking indexation here, then we will have to do plus one here. Okay, so select control C here and the long thing here, let's name it first. What will happen is this is our right sum. Equal you and this here, whatever value is changed, this will be our right, which came from above, okay, we will get our mines done here, it is okay with the right and after doing plus one, we will divide, now in the last, what do we have to do, if we like our If we look at both of them, we are making our values equal twice, but our maximum sum should be making our values equal twice, but our maximum sum should be making our values equal twice, but our maximum sum should be equal to the value once. Okay, so what will be our total sum, what will be left sum plus right sum plus both sum. Mains is done, the value is repeating in it, so you minize the value once, it is okay, if this total is even, if you take this equal, what happens to me which is smaller in max, then what do you return from here? Will give true and vice versa return, if our water is fine then it is late, then what was done here yesterday to our helper is fine, inside the helper we will send it to our own people, what do we need in the first value, what do we need in the value, this is our meat in the second, n total number of Elements are ok. Max sum maximum is the life we have. They will maximum is the life we have. They will maximum is the life we have. They will make their own mines from it. Which N is ok. Now after this we need index. The index which is life we have is the same index which is life we have is the same index which is life we have is the same index which is ok if it makes this condition true. So how will our left point become what will it become? Meet is fine and in the else condition it is fine. In the else condition what will happen to us? This point on the right will become Mid - 1 This point on the right will become Mid - 1 This point on the right will become Mid - 1 is fine and in the last one our this. After the loop, we will be returning here that if our left point is ok, then the return will be done from here. Our left plus one is ok, there is no syntax error, let us submit it, then our code should be successfully submitted. Now let's talk about its time and space complexity. So what will be the time and space complexity of our support? So what have we done here? We have done it here. Is binary search ok? What is the time complexity of binary search? It is done by locking, okay, people can say that people have time complexity and what are we doing inside it, we are finding the maximum sum inside it, what is the range of this maximum sum and one more thing from zero. If we were going till max sum, then IT min which is going to be our answer, which is going to be time complexity, will be in people's term, max sum which will come to us, this will be ours, if we talk about space complexity, If we had done the story about additional space, if we had not told about it then our space complexity would have been happening. Oh one. Okay, so gas, this was our today's solution. Hope you liked our video. See you again with another video. Till then 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 |
171 | hello guys my name is Ursula and welcome back to my channel and today we are going to solve a new liquid question that is Excel sheet column number we will be solving discussion with the help of python so let's start solving this question just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and book maruti playlist so that you can get the updates from the channel so let's read out the question given a string column number that represents the number a column title as appears in Excel sheet written its corresponding column number for example a is 1B is 2 C is three Z is 26 a is 27 and a b is 28 so on so we have to return corresponding value of this given string for example if the given string is a we have to return 1 if it is a given string is a b we will be returning 28 so let's start solving these questions first of all uh I have to explain you the logic of this whole thing so if a value is 1 uh it is one d it would be 28 and C it would be um 26 into 28 plus 3. so how come this is happening let me explain it to you how this is all happening so it is happening because if you multiply 0 into 26 plus one so we will be getting a and 0 is the sum and B is uh sum so this all will be here into multiply by 26th plus 2 so this value will keep on adding now C is equals to 28 because this whole value is 28 so we'll be taking 28 into 26 Plus 3. so how we are getting these values 1 2 3 how do we get this so I have taken ACI values let's go for search and found find out what acir ASCII so if you see a table here you can check that for Capital a is C capital a capital b capital c um Excel let's check um yeah this looks more relevant um yeah so see this is 65b 66 C is 77 and so on so we only need three values here for to make the example clear to you because we are only X I am only explaining you the uh ABC value so that you can understand it in a better way so this is 64 this is 66 so this is 67 so here this is starting from 0 so we will say that instead of this we can write 65 minus 64. because a is equals to 65 so 65 minus 64 this could be um 66 because B 66 minus 64 again the base which we considered as a zero and 67 minus 64. so this is which will give us three so this tree seems more logical now so I hope you have got the point what we are actually seeing so after we have understand what we are actually gonna do let's convert this whole thing into a code starting from some is equals to zero okay and then I will say a loop here for I in range the length of um column title then I will go with sum is equals to sum into 26 Plus Rd column title I and minus 64. so put a bracket here again and then I will be just return the sum so what we have to actually do it did here is I've created a loop here starting from a variable sum which I have already defined outside the loop and I've said that sum is equals to 26 so because this is sum only because if you check for this whole value we are getting one so one will be here into 26 then hold it this variable was 28 and 28 into this plus this so This you convert this whole thing or B or C anything into this form you will get an answer here so let's do that and I've already did that and I have taken ORD which will give us the as ACI value of all the ith integer ith values in the string for example if for a it will give one for a b it will give 28 ultimately so A8 will give us so this whole will give us 65 and this will give us 0 for a and this is 65 or 64 and this is 65 for E if we talk about example number one and if we return it we'll get 1 so let's run the code and check for an answer so we have got our answer here so this was all in the question guys hope you have understood this question and if you have any doubt ask in the comment section so thank you guys for watching the video see you next time | 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 |
221 | Hello hello guys welcome back to take division in this video you will see the maximum square problem visit from list co de 2730 discarding challenge so let's look at the problem statement the problem yes-yes york this look at the problem statement the problem yes-yes york this look at the problem statement the problem yes-yes york this is gold subscribe channel very simple problem in the Video then subscribe to subscribe the Video then subscribe to the Page Subscribe Bhi Same Day Will Be True Even From This Direction So In This As A Tool Ka Moto G3 Soln To Problem International Will Be Same In Superintendent How Can We Solve This Problem When Approached The way can find the longest road in action and action in this water subscribe to subscribe the Channel Please subscribe and subscribe the do Bluetooth of the matrix which you have formed and 1000 will return and soon you will return back to the caller for this is not The Way To Solve This Problem But Did A Lot Of Time And You Will Not Be Able To Take Away All They Know About The subscribe and subscribe the Video then subscribe to The Amazing Dhruva Video DJ Video Se To The Current Quar Metro Ke Swift Condition Safai Student will appreciate this column is having all 102 this length and support for observing all lineage will report to solve this true when they can extend discover tree broke this current subscribe to the Page if you liked The Video then subscribe to the A square matrix can be possible by 10 wave settings vire values and this column 10 wave settings vire values and this column 10 wave settings vire values and this column values but were not working for all the values but were not working for all the values but were not working for all the values in this is the calculated at least to determine the vire values in this is the calculated at least to determine the vire values in this is the calculated at least to determine the vire values Problem Can Do Problem Solving Problems Cancel Problem Video subscribe And subscribe The Amazing And You Will Be Able To Understand Your Content Inside Fifth Three Different Container Nowhere To Read Only About This Container Three Left His Job Well Wishers Having Volume Of Meter Cube Know Your Goal Is To find the volume to know the subscribe Video subscribe to subscribe our 200 wherever you for matters when you will have to keep track of the largest matrix which forms for research and different metric systems at different points And the point in the war between the thing to solve this problem to remember Subscribe now to the largest lakes of dynamic programming can only be Subscribe Solution will be used for calculating the time will be making Subscribe 00 Moving from left to right from do Solution Like This Robin Like Country Business Just Voice OK So What Your Values Will Be Available For Values Will Be Available For Values Will Be Available For Rs 31.80 Majlu Sahi Will Be Available To Be Rs 31.80 Majlu Sahi Will Be Available To Be Rs 31.80 Majlu Sahi Will Be Available To Be Available subscribe Video Print Only And Mother Will Be Available At Least One Item For Which You Can Help Yourself To Remember only if you liked The Video then subscribe to the Page Mitthu's Private Dash Just Once Upon the Biggest and Matrix and Note from Solitaire Where Given a Square Matrix Seven Level Three and Waste Processing From This Point Value Ho Ki Don't Have Knowledge About Inter metric Ton More Will Have No Value Stop Acid Attacks Which Will Give One 09 2012 Subscribe Note Seervi This Point To Take Medicine For Events And Your Week Element Solar System Matrix Witch Country For This One subscribe to subscribe our Channel and Share subscribe and subscribe the Channel subscribe to subscribe our Channel subscribe and subscribe the Channel subscribe this element that Swadesh will be counted by value because this will form a matrix and size 212 hand over your understanding that no letter this point to make sure Radhe Shyam Current Worst condition is unit 25138 subscribe this Video not this element subscribe position in this channel subscribe now to the meaning of this is the meaning of the sun and [ __ ] shot on given you can extend the size and [ __ ] shot on given you can extend the size and [ __ ] shot on given you can extend the size of square matrix wedding 125 values in all directions to the Volume Two values in all directions to the Volume Two values in all directions to the Volume Two You Cannot Be Extended To Answer Will Be Id Elements Of Obscuritism 512 Indicators That You Can Read This Element Will Take 2.5 Inch From Deputy Superintendent Tutu David 2.5 Inch From Deputy Superintendent Tutu David 2.5 Inch From Deputy Superintendent Tutu David Subscribe Must Subscribe Like This Element Subscribe And This Points Will Use This Point To Table Today That Nav Deep table will always be for the size plus one in terms of roads and plus one in terms of columns in their pure first form will be defeated by you since 5200 only been taken to take care of the height of mount cases show will start processing from From this point limit officer have seen this post element top seal recent cases end take the minimum and other elements end see if e can extend subscribe minimum 1008 peer will indicate 200 300 you are not able to extend subscribe nov 09 2013 volume minimum end 128 From indicating that this is not extend the square matrix in this reduction so you have done next one day you will also be given this will also give one similar 98100 [ similar 98100 [ similar 98100 Video Channel Subscribe 900180 Matrix in which is no development no You Will See A Volume Minimum One You Will Hurt 128 9 10 Vikram 210 Indicate Left By Using This Element You Can Extend The Size Of The Square Matrix In These Reductions Which Have Already Mentioned Since Solving This Using This Reduction Suet This One Day You can extend and from this largest Government Institute of Science 2ND Year for face value to and away if you want to update the largest Subscribe now to the element This is the meaning of this is the deduction from0 members also 1.3 Elements In the deduction from0 members also 1.3 Elements In the deduction from0 members also 1.3 Elements In the left side note affected actually this is when we live with you can see the now 200 do n't know you are in the and it is just minimum one which will give way to a minimum of election 2013 date this element you can extend the subscribe The Channel subscribe to that has returned career 9.the largest is returned career 9.the largest is returned career 9.the largest is model in the current one 16 just will again be updated to three love simply will process rest of the elements as well as will give visa zero-valued 2000 will be completed visa zero-valued 2000 will be completed visa zero-valued 2000 will be completed more than 100 one And last well wishes in the largest is the length of the return of the area of the written taste will be able to area of the written taste will be able to area of the written taste will be able to understand you all subscribe quarter of mintu subscribe now you can even subscribe you can see you need only available in order to keep track Of the largest size square meters which was formed and when you are currently like Amazon you need to see only three worlds Top 10 Top Losers 10 Previous Row And subscribe The Amazing You will be able to solve the center solution in just subscribe to the Page if you liked The Video then they quote 10 largest railways and finally is the largest will be content with side length of the largest format research will be multiplying Thursday Solution and Different Languages and Benefit from Comment Section Languages and Benefit from Comment Section Languages and Benefit from Comment Section Like Share and Subscribe Channel Subscribe Video Like | Maximal Square | maximal-square | Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_.
**Example 1:**
**Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\]
**Output:** 4
**Example 2:**
**Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\]
**Output:** 1
**Example 3:**
**Input:** matrix = \[\[ "0 "\]\]
**Output:** 0
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 300`
* `matrix[i][j]` is `'0'` or `'1'`. | null | Array,Dynamic Programming,Matrix | Medium | 85,769,1312,2200 |
1,004 | hello welcome to my channel i'm here to do my 100 lego challenge today we have the code 1004 max consecutive 1 3 so given an array a of zeros and ones we may change up to k values from zero to one and we turn the link of the longest contiguous sub array that contained only once after changing right so the example in here we have uh we can only change to zero to one and in this case we can change this to this become one and then we have a whole entire subarray six number become all ones like this example here so the length of the sub array is six so that's the longest up array and in here it's kind of complicated in here you can see here the two hole you feel this so we only have one more bullet shoot it right here and then we have this whole entire sub array connected so the total sling of that one is 10. so in today we can use a sliding window solution for this uh questions it's really classic and it's always good to know um we will have a left pointer and right pointer pointing to the beginning of this array and then we keep moving if this is one and then right we move to next one and that will keep it right there then move it's still one right now we have three in here the right pointer will keep moving now we see it's zero and then if it's zero and we will deduct k by one so k is one right now and now we move so k is zero detected by one so now k is zero lab is still here right is here then we keep moving to here so now that's a different case so y k is no longer available and then we will check if this one i mean we move lab pointer we move pointed forward and check if this is zero and we can gain one k back if this is one no so now in here and what it means is k currently becomes negative one so we will need 1k to fulfill this lane what it means in here because we started from left here to right here that's the currently the maximum right now since we found five we won't go lower than five so we can move this one to here for checking the next five if it's are valid or not or if they're valid and in have much more lane then we can configure consider that one so now in this case this five now the moving five for every windows and for this five we need one no it's no good and then if you get one of this and it will move forward if this is one and it's nothing i mean so the k is still less than one less than zero then we need to move this uh move the left pointer forward right but k is still negative one and just keep moving until we see this one and that's one of the uh solution for that one that's the idea and we'll code that first go to l first and i will give you another example so we have left equal to that pointer also have right pointers equal to zero they it right there and we need to check why loop things right uh less than a dot lane right okay so now if you check a y um is equal to zero then k will be k minus one so k will deduct it by one so now it check k is less than one i mean less than zero or not so if k less than zero we have to move the lab by moving left one i mean a left we need to check if a left is equal to zero that mean uh case plus if we move that pointer to forward uh to take out one zero then k should be equal to k plus 1 because you gain 1k back and left will move one step forward after that right will move one step forward too to keep track of that windows and moving forward at the end we'll just return the gap which is the window the maximum window for this solution yeah this is a solution but we won't end it right here i will try to run through one of the example zero now we see we have this array and the k equal to zero so we don't have any chance to change zero to one let's see how is the gap how's the maximum cons consecutive ones here so we have oh let's draw this we have left right here and right is right here pointing to here now left is one i mean right is one right now and then we move forward um right is not zero k is not zero i mean less than zero then we don't do anything but only this one the right equal to right plus one move one step and then keep moving until here so now right is equal to zero k become -1 right now lab is still here now left still in the beginning so what that does after k minus right and then k will be less than zero then we check we need to move this one because this is only three window of three we need to move that one if left is one then um left is not equal to zero so k won't be incremented by one if that's the case we move the window right here and k is still negative one and then we move one step for the right is still zero and we keep minus one so it's minus two for k and left will move one step we keep track of the frame for three and then because of that we won't add any k and just keep moving forward right will move one step left we move one step because uh now k is negative three so we won't we keep minus three right here because we keep losing our chance because we don't have any one we keep moving the frame to the end of the array then they will keep track of that bracket which is the window at the end we output the maximum consecutive one so that's it for this question hopefully it's clear enough if you still have question please comment below and i hope you get something from this video otherwise i will see you in the next video bye | Max Consecutive Ones III | least-operators-to-express-number | Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length` | null | Math,Dynamic Programming | Hard | null |
41 | code 41 First missing positive how to solve hard leak code problems creatively with JavaScript I didn't look at any of the other submissions or any of the discussion I dove right in and got good performance after making a few tweaks and changing the submission a couple times I got pretty good performance out of this and here's what I did I'll start with a problem given an unsorted array of integers nums return the smallest missing positive integer you must Implement an algorithm that runs an O of n time and uses constant extra space definitely runs an O event time it uses extra space I don't know if constant extra space is correct uh anyway this is that like 2N space I'm not sure what they mean by that so given the examples input nums one two zero output is three okay so if the numbers in the range of one to two are all in the array right so zero is eliminated because it's not a positive integer um one is a positive integer two is a positive integer and then this Edge case we have to return what would be missing would be the last thing after the array that's an edge case there's another Edge case example two nums equals three four negative one and one the output expected is two we eliminate one we have one three and four so two is missing now example three seven eight nine eleven and twelve output expected is one so we don't start at seven and look for sevens there eights there Nine's there ten is missing which is what I initially assumed they wanted that was wrong they want the smallest missing positive integer smallest possible one is the POS possible smallest integer is one it's the smallest integer you can have and it's missing here so that's the output now onto my solution my creative JavaScript solution uh I basically filtered the array and sorted the array and then looped through it starting from the beginning of the array to the end and look for the smallest possible integer of all the possible integers in that array starting from one so I forgot one and that's there then okay we're okay until we get to something that's missing and if we don't find something that's missing we return the last element of the array and add one to it right so if we got one two three then we're going to return four is missing and that's what they want the way I did it is to implement a filter function positive unique filter this nums array positive unique by filtering all numbers that are positive and unique because we don't want doubled numbers when we get down here to this Loop so if we have 1 2 3 we're going to look for expected is going to be equal to I zero plus one we're expecting one okay we got that's fine we get to 2 expected would be two plus one that would be expected be I'm sorry one plus one would be two because I would be one okay so we're okay there and then we get two again expected will be equal to I would be then 2 plus 1 is 3 and then we would have two expected would be two but the actual element would be three and then we'll be returning to oh it would say uh two was missing no uh or three was missing but it's not missing it's just it's the next one because I have a double two so we have to return um the smallest missing one and three is not missing it's just we have an extra two in there that makes it look like it's missing and could make our Loop not work so that problem right there makes us think us we need a unique array and we need to filter out everything that is less than one so let's filter out positive unique numbers okay so then we filter this nums array with positive unique numbers and then we sort it uh and the way we sorted is using an unsigned 32 in 32 array and the reason for that is this sort function is faster and the un32 is necessary to match the requirements of the constraints is that num's I could be 2 to the power of 32 minus 1. so we need these big numbers in there so we're gonna have some big numbers in this array we're going to have a lot of numbers in there 10 to the power of 5 lots of numbers in there okay so let's uh let's use the new un32 array and the way this filter function works is rather interesting as well we use uh what I'm going to call a poor man's set so what I first did and you'll see in the submissions I made a few attempts is I sorted I filtered everything so that we have all positive integers and then I pass that to a set very straightforward and it works but it uses a little extra memory so how can we use less memory what I did is I created a map and that uses less memory here so unique e is e and unique and let's step through this I like to step through the problems when we have these filter functions it's good mental exercise so we start with this one if we have an array let's say we were given an array of this and that's what nums is let's say nums is equal to this array and we pass I'll start with the filter function we go with one unique one we're gonna first we're gonna say uh e is greater than zero one is greater than zero yes uh unique our object here one is equal to one and unique well one is not in unique so that's going to be false one and unique is false the result of this expression unique E equals false okay so does that mean it's not there no it is there and it has the value false we negate that value so now we say unique e is going to be true ah okay so we e is greater than zero and that's true and this is true so the result of this um this binary operator this uh and expression here is true right so that gets added so one gets added the next one we have is two is greater than zero unique two is equal to two and unique that two in unique is false so now unique two is equal to false not false is true that gets filtered the positive that's in so that's in it's not filtered out it's filtered in the next one we get is two so now we say 2 is greater than zero true and unique two equals two and unique is true the value of unique two is false currently but it is in unique and then we assign that to Unique two is now true and then we say not true oh not true is false so that's not going to get added so this 2 would not get added to the array and the same thing would happen with three that happened to the first two and the first element that we got one and so that's how we filter out the array to have positive unique numbers without having to use an extra set we do have to use a map but it is much better uh with memory then the set so there you have it guys there is my creative approach for solving a leak code hard problem with a creative use of JavaScript and I did this without looking at any of the submissions uh without or without looking any of the solutions without looking at any of the discussion I just went straight to it and you can see that I had a bunch of attempts where I optimized for my performance and eventually I Came Upon one where I hit it off lucky with this particular one where this was really what did it I tried back and forth and changing this around this was really the most performant way to do it and I did actually get pretty good performance I'm still not up there uh as far as memory usage goes that could be improved uh so it's not the best solution for memory but it's pretty damn good considering the constraints of this array where we have a lot of data a lot of nums and big numbers as well thanks for watching | First Missing Positive | first-missing-positive | Given an unsorted integer array `nums`, return the smallest missing positive integer.
You must implement an algorithm that runs in `O(n)` time and uses constant extra space.
**Example 1:**
**Input:** nums = \[1,2,0\]
**Output:** 3
**Explanation:** The numbers in the range \[1,2\] are all in the array.
**Example 2:**
**Input:** nums = \[3,4,-1,1\]
**Output:** 2
**Explanation:** 1 is in the array but 2 is missing.
**Example 3:**
**Input:** nums = \[7,8,9,11,12\]
**Output:** 1
**Explanation:** The smallest positive integer 1 is missing.
**Constraints:**
* `1 <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1` | Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n) | Array,Hash Table | Hard | 268,287,448,770 |
724 | hi everyone this is Colleen Dev Tech and today we are going to solve 724 of Le code this is find pivot index and so we are given a nums array and what we want to do is find our pivot index and so for this nums array we have these three elements that equal to 11 and then these two last elements that equal to 11 and so what we want to do is find the pivot and so six is going to be our pivot but we don't want the actual value of six uh of this pivot we actually want the index so it's going to be Z 1 2 3 4 five so we actually want the three so here we have our input nums array and we want our output to be three okay so how do we solve this problem like what is the first thing we tackle so first we need a uh to sum up our elements and all of these elements equal to 28 okay and then we also want to have a counter to track our left and also to compare it to our right side we want to iterate through our array we want to check if uh if our left is equal to our right if it is we want to return our index if it isn't we want to move along to next element and add that to our left count okay and in the case that there's no valid index we want to return1 okay that's what it says here so how do we start to code this so and we'll walk through everything we'll have a variable uh s equals our sum of nums array so this will equal to 28 we'll have our left counter we'll set that as zero because we haven't counted anything yet okay and then so what we want to do is we want to Loop just going to bring this up here what we want to do okay that's fine is we want to Loop through this array okay how do we do that we do 4 i v in numerate nums so for every index these are the indexes for every index in and value V is for Value in enumerate nums enumerate means getting the index in the value okay in the nums array we want to do something and what we want to do here is we want to um check if our left is equal to our right side and so how do we do that so um we want to say if left is equal to sum minus our left side minus our value of that index okay and if it is we want to return the index of that uh of that element okay um and okay so let's just um step back a little bit and just see how this looks okay so right now our left is zero because right now our count is at zero okay let me just that out uh and our sum is 28 our left is zero see okay and then our value is going to be one cuz we're starting at one or at zero index okay so 28 - 0 - one or at zero index okay so 28 - 0 - one or at zero index okay so 28 - 0 - 1 is going to be 27 is 0 27 is our left equal to our right no it's not at this time so what we want to do is say um if our left is not our right equal to our right we want to um move push this uh our value to our left counter and then move along um and the array so the way that we do that is we want to say left plus equals or V okay so for our left counter we want to push the value into our left counter so what does this look like so our left will now be one okay so left is going to be one okay and then now we change our left to one our left is going to be one and then our V our value is going to be the next so this is going to be our x value 7 okay so let's look at this 28 - 1 is 27 - 7 is 20 is 1 = to 20 no it's - 1 is 27 - 7 is 20 is 1 = to 20 no it's - 1 is 27 - 7 is 20 is 1 = to 20 no it's not so we are going to push this value into our left counter so it's going to be 1 + be 1 + be 1 + 7 okay so this is going to be eight so left is going to be 8 we're changing this to eight and then our value is going to be three so now we do the math again 28 - 8 three so now we do the math again 28 - 8 three so now we do the math again 28 - 8 is 20 - 3 is 20 - 3 is 20 - 3 is 17 is 8 equal to 17 no it's not so we're going to push this value three into our left counter okay so now this equals to 11 that is 11 and then now our value is going to be six 28 - six 28 - six 28 - 11 is 17 - 6 11 is 17 - 6 11 is 17 - 6 is 11 does our left side equal to our right side now does 11 equal to 11 it does right so it's going to return our index and our index is three so it's going to return our index of three okay so our output should be three but if in the case there was no output then we want to return 1 okay and put this back to zero so let's see how this looks okay let's run it okay and it is accepted okay so let's go through this again so here we have our sum equal to the sum of the nums array okay we have a left counter we iterate through the nums array we check if left is equal to right if it is then we return our index and if it isn't then we push the value to our left counter and move and loop through the rest of the ARR and if otherwise if the index is not there or invalid we return negative 1 okay I hope um you enjoyed this and I hope um you learned a little thing or two and if you have any questions um please leave it in the comments and until next time thank you | 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 |
1,837 | At this moment I have the result number of three percent real estate1 in tu adia price that plant testing version tubeless k 6585 the best with this will find out key 130 office number 66 value will divide this treatment at every step number 3 k basics and committee Plus Five Physical Document Simran Ne Effect System 150 Divide Bittu 10 Result Number That I Will Benefit Format Rate Suhag Define Fifties Include Sea And Digit Deliver Na Dhi 10 Latest He Divide And Rule A Great Wall Of Thanks Til 1000 Software Ka Insan 300 Plus And Getting Justice Cars Back After 12th Increase Angle A Print Out Of Cutting From Creative Put On The Selection Committee On Now Accept One So If You Like This App You Tube Please Like Subscribe And Channel Thank You | Sum of Digits in Base K | daily-leads-and-partners | Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`.
After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`.
**Example 1:**
**Input:** n = 34, k = 6
**Output:** 9
**Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9.
**Example 2:**
**Input:** n = 10, k = 10
**Output:** 1
**Explanation:** n is already in base 10. 1 + 0 = 1.
**Constraints:**
* `1 <= n <= 100`
* `2 <= k <= 10` | null | Database | Easy | null |
40 | in this video we'll be going over combination sum two so given a collection of candidate numbers candidates and target number target find all unique combinations and candidates where the candidate number sum to target each number and candidates may only be used once in a combination the solution set must not contain duplicate combinations so in our first example we have 10 1 2 7 6 1 5 and we have the following combinations where the sum of each of the combinations is equal to our target which is go to 8. now let's go to the dot process we will be implementing a recursive backtracking approach now for each of the starting index i we want to scan forward for each of the starting index i we will want to scan forward from i to the end of the array end of the limp array which we denote as j which is known as index j to find the element x to be included into our combination we should know that we are only allowed to include the element x if x is less than or equal to target because if x is greater than target the sum will overflow we can only add values of x where x is less than or equal to target then after adding x to our combination we will continue our search for elements from j plus one because we do not want to use the same elements more than once because and say here each element may be used only once we will continue our search from index j plus one because the current the element x is the index j so after accounting for the current elements will continue our search for j plus one we're continuing our search for index one for the com for the combination of target minus x because we have added the current because we'll add x to a combination where this is where the decrements are target and after accounting for x we will backtrack our steps by removing the last elements from our current combination this will allow us to give space for the next elements to create our next combination so we will backtrack our steps by removing x from our combination this will give space to the next elements and also allow us to find the next combination a side case will also have the handle is the solution set must not contain duplicate combinations now how can we avoid duplicate combinations so we can say if we are currently looking for the elements we are currently looking for eight elements for index k in our combination after accounting so if we found the element x if we found an elements x and we add x to our combination we will want to skip all futures down after accounting for x we want to skip all future occurrences of x for the index k because we do not want x to be placed inside index k in our combination ever again because if x is ever came back to our index k it will create a duplicate combination this means we will need to sort the input array in ascending order this will allow us to group all the duplicate elements together and will allow us to quickly determine if the current element is equal to the previous elements this will group duplicate elements together and allow us to quickly determine if the current element is equal to the previous elements that means if the current elements go to the previous elements then we can skip the current element because we know we have already accounted for it already now let's go over the pseudocode now we're going to create a list result to keep track of all combination then we're going to sort input array in ascending order this will allow us to group all of the duplicate elements together then we can implement our recursive backtracking approach then what parameters do we need the current starting index and then our candidates is the temporary and our target is our current target and then our com is our current combination and then our result list of all combination then what's the base case if i is outbound then well then we have no more elements then we can just return from the recursive call if target is equal to zero actually we don't even need this we can just iterate through we don't really need this case target is equal to zero then we have found a valid combination so i'm going to add a copy of com to result we don't need the previous case it'll be more apparent in the code in the pseudocode after we type this out so in each of the recursive call we're going to iterate through from i to the end of the ray because if i is out of bound then this iteration will not even be invoked denoted as j index j so if the current elements if the current element is greater than target we want to skip the current elements or i is or j is not a good i and the current element is equal to the previous elements we want to skip the current index this case will allow us to prevent duplicate combinations and this one will prevent our sum from overflowing so we can just say continue the next iteration now we can add the current elements to the combination then we'll recursively find the rest of the combination our current starting index turns to j plus 1 because we are not allowed to use the same elements more than once and then our target gets decreased by the current elements at canvas j then we'll backtrack our steps by removing the last elements from our list backtrack our steps by removing last elements from cone come from the combination and then we can return the list of all combinations now let's go over the code so we first create our resulting list for all combinations then we are sort temporary in ascending order then we perform a recursive back tracking approach starting index zero and then our input array and our target and the current combination and our result of all combinations and then we're going to return results after our recursive call finishes so if target is go to zero we have found a valid combination so we're going to result that add a copy of the current combination we had to create a new list because if we just add combinations to our result this is by reference because we do not want it by reference we actually need a new list into our result so we're going to turn from the recursive call and i'm going to iterate due from i to the end of the ray if the current element is greater than target we want to skip it or i is not going to j and current elements is equal to the previous elements then we then want to skip it to prevent duplicate combinations so i'm going to say continue now we want to add the current element to our combination and then recursively find the rest of the combination starting from j plus 1 because each element is only allowed once target gets decreased by the current elements that we added to our combination and results then we're going to backtrack our steps by removing the last elements from combination size minus one let me know if you have any questions in the comment section below like can subscribe for more content that will help you pass a technical interview i upload videos every day if there are any topics you want me to cover let me know in the comment section below | Combination Sum II | combination-sum-ii | Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`.
Each number in `candidates` may only be used **once** in the combination.
**Note:** The solution set must not contain duplicate combinations.
**Example 1:**
**Input:** candidates = \[10,1,2,7,6,1,5\], target = 8
**Output:**
\[
\[1,1,6\],
\[1,2,5\],
\[1,7\],
\[2,6\]
\]
**Example 2:**
**Input:** candidates = \[2,5,2,1,2\], target = 5
**Output:**
\[
\[1,2,2\],
\[5\]
\]
**Constraints:**
* `1 <= candidates.length <= 100`
* `1 <= candidates[i] <= 50`
* `1 <= target <= 30` | null | Array,Backtracking | Medium | 39 |
219 | okay so as an example we are trying to solve the contains duplicate 2 problem now this is a very popular late core problem that has been asked in some of the popular companies like Amazon Facebook Adobe Microsoft Uber Google Bloomberg Airbnb and plenty so these are all Tech Giant companies who love asking this question so that is why I consider it this month let's try to see the problem statement is actually quite simple and this is a lead code easy problem and also a very well like problem on lead code basically we are given an integer array called nums or we are going to denote it as n that contains array values we are also given a value K and K can be anything like 1 2 3 for any single integer value so suppose K is equal to 3. now we need to return true if there are two possibilities uh the first possibility is there exist any two values I and J that are uh exactly same so if they're con there exists two duplicate values in the array and the second portion is that the difference between I and J so I and J refers to the index positions of every single value inside the given array so the index position should be actually less than the value of K let's try to understand this with few examples so suppose our given input n is equal to 1 2 3 1 5. if this is the input we are given and we are given the K value to be 4. if this is the case uh thus it satisfies these two properties so first let's see okay so we need to check that between the window 4 there needs to be two duplicate values currently we can see that there exists a duplicate value 1 and 1 over here let's see the index position 0 and 3. so if we do the different 0 minus 3 so basically we need to do the absolute difference so the answer is going to be three is actually less than the value of 4 which means this one currently contains the duplicate value that is not far away from four elements from each other so in this case we are going to return true let's try to understand it with one more examples of suppose our given n is equal to 1 2 3 1 0 something like this and our given K value is equal to 2. if this is the case again same scenario we have the values located at index position 0 and index position 3 that contains the same value but current K value is equal to 2 and if we do the difference between these two values the current difference between indices is 3 meanwhile our given K is equal to 2 which means in this case we need to return false because that does not exist any two duplicated values that are two steps away from each other or between two elements of each other so this is the whole ask now let's see that what is going to be the simplest approach we can take okay so suppose this is the input we are given now we let's see The Brute Force way to solve this problem that we pick any element then we take then we check the next K elements so in this case currently we are allowed to check up until this point so between these portions we check that whether 0 is present in any other value or not if 0 is not present we can Define that 0 would not be any would not be a duplicated entry in any of the window because we are strictly told that we can only check next three elements so in this case we can get rid of 0 because 0 is not present same way we are going to check for Value number five So currently value number five is located at index number one which means we have the ability to compare between these portions so again for Value number five we are going to check this value and this value in Bingo we find Value number five so we can return true in this case because element number five exists and the difference is less than 3. but this is like a very inefficient approach by inefficient approach say for an example this entry does not contain any duplicated values and all the values are unique and at the same time we so what would what we would do is for every single element we would compare it with the next three elements and we would keep on repeating the same process until we reach to the end of our Loop and that would be an inefficient approach because the time complexity would be bigger of uh n so n is the total number of elements multiplied by K and this is not what we want something more efficient so let's see uh and more efficient and better approach a better approach is that we know that for any single value we need to check in the remaining portion whether that value is present or Not So currently we can break it down in Us in this sequence So currently we can create a window of Windows like the zero and then five to seven currently we are at this position number zero now we need to check that whether 0 exists in the remaining three entries or not first approaches is to do binary search so for binary search what we would need to do is we would need to sort this given input and if we sort this input array the sorted result is going to look like the 0 2 5 and 7 and then all we need to do is check any two consecutive values if we identify that there exists like a back to back entries that contains the same value then we can return true if it does not contain then we can move on to the next window and again in the same way we would repeat the same process for this next window that is concurrently comprised of the values 5 to 7 and 3 and again okay so let me fix this one so this one should be 5 not 7 and 5253 so again if we sort this window in this case the answer we are going to get is two three five and we found two back-to-back values and we found two back-to-back values and we found two back-to-back values that contains the same uh value so in this case we can return true but the thing is even this approach is also not very efficient because if we see time complexity in this case the time complexity is going to be bigger of n then log of K by log of K because for any given input we will actually have to sort this and sorting it cost us lot of time and energy and this is also this is better than the Brute Force approach but still there can be improvements made so what is one Improvement we can make and again remember we are using sliding window because we know that we need to do this in any subsequent values and we need to find the answer so definitely you understand by seeing the problem that why we need to use the sliding window but let's see that what would be the Improvement we can make first thing we need to check is that in the binary search approach what we had to do is we need to check that whether in the remaining portion does the same element exist or not and also at the same time we were considering that every single time we need to create a new window we would have to do the entire sorting calculation again so we need a data structure that can very quickly like get rid of elements and add new elements at the same time very quickly search that whether the existing element exists or not and the wonderful answer for this but this type of scenario is a hash map so we can create like a hash map or a hash set inside our input and hashmap and hash set are wonderful at doing two things like doing the search and remove and input operations in big go of one time so hashing is really good in that also at the same time it does not allow duplicate entries so no duplicate duplication is allowed which means we can identify duplicate entries very quickly very efficiently in any sort of hashing input so we are going to use this property combined with sliding window approach to solve this problem in the most efficient manner let me quickly show so first we are given the value of K which means we are going to create our window so currently we let's just create a window of size K okay so starting from value number 0 to Value number five and then we will have all the values 0 5 2 and okay let me just put down some different value over here and let me put 5 over here okay and then this is going to be four okay so this is the these are the current values at the moment we are going to initialize the hash map now inside this hash map we are going to store two items we are going to store the value as the key and we are going to store the indices uh based on its value inside the hash map so first we are going to check okay this one is value number zero and currently the index values are 0 1 2 3 so 0 is not present in the hash map We'll add entry 0 over here and its index value 0 as well again 5 is also not present so we will add entry 5 over here and its index value 1 over here 2 is also not present so 2 and again 4 is not present so 4 and the index value is 3. so we add these four entries in our hashmap at the same time we would we can check that currently since the value of K is equal to 3 we already added four elements and still we were not able to find a duplicate entries which means we will have to update our window so in order to update our window rather than getting rid of all the items what we can do is we can just get rid of the first element and then we can just shift our window to include one more entry inside our input and that is going to be value number five for the index value position number four so again we add 5 over here at the same time since we got rid of the first index value we are going to also get rid of that inside our hashmap so we are going to get rid of the first entry and currently we have three entries again we will try to check that whether 5 exists or not so we will try to input 5 inside our hash map but we would be able to immediately find that 5 is already present as a value inside our hashmap and immediately we can return true saying that this contains duplicate inside a k window and see what we did is that initially our window was consisting of this value number zero we got rid of the only zeroth value we kept the remaining values inside of our window and we simply added a new value inside our hashmap and then we were able to immediately identify that whether this is the correct response or not and say for example if somehow this value is not value number five this is value number 11 or something else this does not contain any duplicate entries what would happen is that every single time we would get rid of the last element from our hashmap and we would keep on adding new values to our window and eventually we would reach to the end of our input and if we don't find any answer we can simply return false in this case so if we see time complexity in this scenario the time complexity is actually going to be big go of n only and since for this case we used to we had to use a hash map of size K we the space complexity is going to be Big O of K but this is a very wonderful and beautiful approach to solve this problem so that is why the sliding window technique is really powerful because you are already building your solution upon we already calculated computed values you are not doing everything from scratch and that is very powerful in making your inputs more efficient okay so for this problem I'm not going to write the entire code I'm just going to give you the explanation so first we are going to initialize our hash set and I mentioned that we can use hashmap or hashtag anything in this case we are using hash set now we are going to iterate over the given input array using a for Loop first thing we are going to do is to check that whether our set contains the current value current ith position of value we are at if that is the case we can return true immediately if that is not the case we would add that entry to our hash set at the same time we would check that if the current size of hash set if that is greater than our given input K if that is the case then we need to remove the earliest entry inside our hash map and we can calculate that using the number of ith index that we are currently at minus the value K and then if we remove that value from the hash set our hash set is only going to contain only the K elements and then we can keep on repeating the same process until the very end if we haven't returned True by then we can return false in the end and this is going to be the whole solution let's try to run this code seems like our solution is working as expected let's submit this code and our code runs decently efficiently compared to a lot of other solution and I would be posting this in the comments so you can check it out from there thank you | Contains Duplicate II | contains-duplicate-ii | Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`.
**Example 1:**
**Input:** nums = \[1,2,3,1\], k = 3
**Output:** true
**Example 2:**
**Input:** nums = \[1,0,1,1\], k = 1
**Output:** true
**Example 3:**
**Input:** nums = \[1,2,3,1,2,3\], k = 2
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `0 <= k <= 105` | null | Array,Hash Table,Sliding Window | Easy | 217,220 |
1,402 | Hello Friends Today I Will Discuss Your Problems From Its Core Problem Name Reduce Indexes Voice Mail Play List Only A Good Heart Problems Because She Thought My Subscribers World Heart From Some Great Quotes And Shayris For Start Posting Laut Problems All Should Know Specific Playlist Research And My channel I will have to date sex videos in the prayers they can send a lot and videos of coming soon research of pimple not but still heart problems from Madhes Edison Electronic yes this problem solve different subscribe The Channel and subscribe and yet in you ok to This section Love and Friendship Day in School A normal life time is a peace and offered as defined as the time taken to good places including pictures multiplied by section Lalit dat this time came in to-do section on Lalit dat this time came in to-do section on Lalit dat this time came in to-do section on words in this liquid as updation of starting from The Ide Supporters and Architects Twist First Features - 15 Architects Twist First Features - 15 Architects Twist First Features - 15 Second Test Cases Five Lines Lifestyle Co Patient Is This Summation Of All Is Well Developed Co Printer For Star It Will Take One Time Pure Don't Be Afraid It's Best Dressed In A Second Chance For The * * 0 World It's a A Second Chance For The * * 0 World It's a A Second Chance For The * * 0 World It's a Little 531 Total Lifting So What Doesn't Mean That You Take Off But Some Distance from the Satisfaction Level and on Instagram Kingdom in One Officer The First Second Third in the Light and Cooperation in the Question of the Length and Timings and Total Is Written question person have to take whatsapp order of some specific from destruction article and left right to make use of this facility to maximize the election commission vacancy in this point today we in 10 half clear voltage this to and after 30 seconds you get this little suketi 340 Deficient Person Plus Maximize 800 This FTU Multiplies Quickly With Lord This Time Only To The Largest Value Attended And Smallest Latest Of Baroda Withdrawal Registered With The Last Time You Will Get Away A Large Number Of Snow And Quite Understand This World Who Lost All Three Lootera Liquid From Subscribe to Channel to To-Do List Channel Short End Subscribe What I Can Do It To-Do List Channel Short End Subscribe What I Can Do It To-Do List Channel Short End Subscribe What I Can Do It Back Already Subscribe Quintal Italian with Example Let's Do I've Formed as Witnesses - 5 - 5 - 5 A Minus One and Five Hai Na Wah Aayega Soft Destroyed Evidence E Can Just vote and switch to support mode How to make the last salute not seconds for decades Treat not a little adjust and notifications make juice good enough to unfold your hidden days and record dress the water in the same way holidays start only did was the first end Second Largest For Skin Thought What Is Caught Unconscious And Only You Contra Voucher Valued For Small Number For This Is Not Beneficial To Make How To Find A Good Match When Not Forget To Values For This Acid 5.5 Notification Diversification Addition 5.5 Notification Diversification Addition 5.5 Notification Diversification Addition Total 10 & 121 Miles - 49 Total 10 & 121 Miles - 49 Total 10 & 121 Miles - 49 That a plant status - 5 out of That a plant status - 5 out of That a plant status - 5 out of 10 - Two that and 10 - Two that and 10 - Two that and sister 3 that Shivaji can see destroyed proper small that Sudarshan News should quit what is not always beneficial to take at all stations which causes prevention from giving last one the largest Rajput is Note Porn Just Like And Definition Of How We Can Find Yourself In Which Is The Largest Building's Pizza Understand By This Is Why This Is Giving Of Moral Value And Reasoning Classes PornSharing The Water In This Pot Is All The Qualities Of Festivities 2314 Involves Beneficial Note IPL AUCTION IN DIRECTIONS DEFINITELY BASED NATIONAL FLAG IN NO 1820 Still posted by take medicine account witch episode 19 number to take off this is the number subscribe effect give ab isko number denge number subscribe this Video then subscribe to the Page if you liked The Video then subscribe to subscribe ho can you art and Samadrishti's Start-up Indore District Hospital This Start-up Indore District Hospital This Start-up Indore District Hospital This Point Mention on the Best Is Steel and Power in Active and Issues Give the Number All Values Destroy Polk Hotspot Variable Values Destroy Polk Hotspot Variable Values Destroy Polk Hotspot Variable in this Situation Gift Veer Vacancy in this Case Then You Will Get Along Well and Senior Assistant Driver Two Three Cases For Watching This Question Ok If You Want To Do The Real Reason Quite Well In This Problem Withdrawal And Two Three Arrested Already Told In Just Few Places In Indian States In To-Do List Mention More Subscribe The Starting Point Right To Left End Find out the forest index tell where the total submission is post correction do you for last to the first and key point total submission for reference from right to left till date 800 to 1000 than this thrust want to take deposit reference can see his point from Right to Left and Keep Adding 5 - 116 Possible But - Phims and Madam Adding 5 - 116 Possible But - Phims and Madam Adding 5 - 116 Possible But - Phims and Madam So I Don't Want to Take Decide If You Start from the Site and Sudesh Left Deposit Deal from This Point Stated in the Temple IS NOT LESS THAN BIG BOSS 10 START WILL Tell you what is a starting point because I'm already go one step back to final mid point of 2012 start and greater interests at which till this indicates posted in just updated on that and what will do take care record one and this cross time with Steve Waugh and Tuteja Total Submission of Light and Confident Just From This and Start Today and Just 10 Minutes Total is specific so different that its picture is similar to development to three and want to decentralize significant for Licensee Sukhi * Section for Licensee Sukhi * Section for Licensee Sukhi * Section for the 1st year of Total Obscuritism Total Indiscriminate Pot Shift Channel Post Videos Next 9 Newsroom Report | Reducing Dishes | count-square-submatrices-with-all-ones | A chef has collected data on the `satisfaction` level of his `n` dishes. Chef can cook any dish in 1 unit of time.
**Like-time coefficient** of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. `time[i] * satisfaction[i]`.
Return _the maximum sum of **like-time coefficient** that the chef can obtain after dishes preparation_.
Dishes can be prepared in **any** order and the chef can discard some dishes to get this maximum value.
**Example 1:**
**Input:** satisfaction = \[-1,-8,0,5,-9\]
**Output:** 14
**Explanation:** After Removing the second and last dish, the maximum total **like-time coefficient** will be equal to (-1\*1 + 0\*2 + 5\*3 = 14).
Each dish is prepared in one unit of time.
**Example 2:**
**Input:** satisfaction = \[4,3,2\]
**Output:** 20
**Explanation:** Dishes can be prepared in any order, (2\*1 + 3\*2 + 4\*3 = 20)
**Example 3:**
**Input:** satisfaction = \[-1,-4,-5\]
**Output:** 0
**Explanation:** People do not like the dishes. No dish is prepared.
**Constraints:**
* `n == satisfaction.length`
* `1 <= n <= 500`
* `-1000 <= satisfaction[i] <= 1000` | Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0). Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer. | Array,Dynamic Programming,Matrix | Medium | 2192,2193 |
458 | hi guys welcome to tech geek so today we are back with the daily eat good challenge problem and that's four pigs this time the problem is a hard one that's leapfrog heart 4 58 so before beginning i'd like to request you all please like share and subscribe to my channel let me know if you have any queries regarding any interview experience or anything then do let me know many people approach me on linkedin asking me for referrals and uh about my interview experience in ticket as well as google so that's what i found out so we'll be sharing that very soon and have actually referred many people for the same position and if you guys require the same then do connect with me on linkedin as well i have shared my links and if you want please connect on the telegram channel too because they have helping you guys with some you can say job profiles and whatever that comes up to me that's beneficial to you people i actually share it up so it's good if you get connected because getting connected will help each and every one okay now let's get back to the question and see what the question says we have buckets okay so there's a input that says bucket so these buckets are the buckets of liquid where exactly one of the bucket is poisonous so out of n buckets you will get one poisonous bucket now to figure out which one is the poisonous you need some number of poor pigs okay to test the liquid and see whether they die or not now unfortunately what you have a time limit of minutes to test and you have to determine within this time limit which of the particular bucket is poisonous now there are few things that have been given uh the procedure you will follow the procedure says choose some life picks okay so you cannot take a pig that's all there is something a self-understanding for each something a self-understanding for each something a self-understanding for each pig choose which bucket to feed now out of n buckets you have to choose so from 0 to n minus 1 you need to decide which one to choose the pig will consume all the chosen buckets and simultaneously sorry simultaneously and will take no time so that means let's say for first pick it took some m time to test that's observation time and still the time to test the overall time to test is left so the pig can move up to other ones now wait for the time to die minutes and you will not feed the other pig during this time okay now after the minutes to die what is the condition that happens like if anything has been fed a poisonous bucket will die otherwise what you do then test the other one repeat this process until you run out of time that means you have to consume the whole thing now given buckets meant to test and means to die and manage to test return the minimum number of pigs needed to figure out which bucket is poisonous within the plotted so that's what we need to so we have gone through the same sorry gone through the question now comes few things what we must keep in mind before beginning our approach okay so there are few things that were told to us that a pig is allowed to drink simultaneously as many buckets as the person would like but keeping the thing that we have been told is that feeding will take no time so that means zero time then one a pig once a pig has been fed okay they need some time that means the minutes to die time is required so that somewhere you can see kind of a cooling period we have so this is the time after feeding the uh the pig needs to be left free okay then the third thing they said if there is any bucket okay that can be sampled an infinite number of times so that means uh a single bucket can be fed by any number of pigs it's not specified okay this is what's it now see we have minutes to test i'm just writing minutes to test and minutes to that these are things that tell us so to specify how much time can or how many times a pig can eat or feed so for that actual condition would be you can say test or result anything that would be minutes to test upon minutes to die so this is what we are getting so for any round you will have this condition now keeping in mind we said a person or a pig could die so for that particular situation what could happen the person or the pig won't wait for this whole time so the actual testing will be greater than one because as said there's exactly one fake report so please make sure about this situation what i said is for testing it's minute to test upon minutes to die plus one why one because of that exactly one poisonous buckets now there can be many cases coming up to the fact so to generalize this we know that the number of tests that could happen is this now what could be the condition that comes up let's say if t or this test was one okay if this test was one then number of rounds would be one that means you have five buckets or four buckets both will work for the same 15 minutes to die 15 minutes to test for this case so if you have four buckets then obviously what you could do is and you have 15 minutes to test so a first person could come here could go here and then the third one could come here similarly this goes on so obviously this is a format that would be required so this is the same thing so you know that the testing provision would require this now for the same condition if you could see for the four that has a two part x right so that's what the power is who is required for our situation that's what a log base situation comes after so to find the answer what we'll be doing is we'll find math dot c okay of log it's actually math.log of buckets by log of this test this is what is required so for our situation if we find log of 4 upon log of 1 or this was actually if you take out 2 so these situations come out so log of 2 is 2 log 2 this gives up 2 is your path so the same way this is purely a mathematical based question you don't have to apply any data structure here if you know how to approach the problem if you have read it properly and if you know how to work this is actually a hard question because it requires a lot of brainstorming okay now see this is test this took minutes to test some minutes to die we place the counter here now you can either write all of this okay or you can simply write one thing that's return in math dot c sorry bracket math dot this would also give you the same answer and this would also give you the same answer here what we are doing the same thing instead of finding out the seal and log we are avoiding that log and directly finding it out that for the total for how much time that we are taking we are running this loop over and the total time is required and the total time will check whether it's total buckets will check if it's less than the total buckets and the count will give you the count of the peaks now talking about the time complexity as you know we're doing nothing just a simple math so time complexity is order of one as well as the actually free space is also order of fun as you are not requiring any specific extra space so this is one of the best things you must have seen a very optimized solution there's nothing that has to be done okay i guess this is clear if in case there's anything that's missing out then do let me know i'll be there to help you thank you | 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 |
1,189 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximum number of balloons we're given an input string text and we want to use the characters from that string to form as many instances of the word balloon as possible of course from that input string we can use each character at most once so it's basically like we're given you know suppose this example right we're given a bunch of characters we don't have to use all of them right but for each character we can only use it once so like this individual o we can use it once we've used it can't use it again but there is a second o we can use this one as well right but that one i can't reuse that one as well and no matter what input string that we're actually given our target is always going to be to create the word balloon which is spelled like this so to create the word balloon we need one a b character one a character uh two l characters so actually let's start you know creating a map almost over here l will need two characters o will also need two characters and we'll need one character now there's a lot of ways to solve this problem the way i'm kind of doing this is making it obvious to see that okay if we had a single b character like in our input string whatever it happened to be if we only had one b character it doesn't really matter how many characters we have of the rest we could have 10 a's 10 l's you know 10 of everything but if we only have one b we're limited by that's like our bottleneck if we had two b's we know that we could have we could create the word balloon at most two times but maybe uh not even two times right depending on how many we have of the remaining characters similarly if we had uh for l's suppose we had four l's that means we can create the word balloon at most two times but maybe not even two times how did i get that though basically we're taking the number of actual occurrences of you know whatever character in the input string and then dividing it by the required number of characters so what we should do is take the input string and construct a similar hash map for basically each of these characters you know if we had a z or something we don't really care how many z's we have but if we have a b we want to know the count of that suppose we had one b one a two and one well in this case you can see obviously we have just enough to create this word a single time now if we had two ends we still have just enough to create the word a single time because we're limited by the other characters but if we had twice as many as we needed for each of these if we had two four two then we could create the word two times what's a good algorithm to actually figure out the most number of times we can create the word basically what i was talking about before we're going to take the real number of characters divide it by the required number to create the word so then we'll have a new calculation so in this case this is going to be 2. we're basically getting the ratio of characters that we have versus how many we need so and then from this we're going to take the minimum of those right because the minimum of these is going to tell us our bottleneck for example if i changed the number of n's or actually let's say the number of b's instead of having 2 we actually had 1b then our ratio here would also be 1. so from these values we want to take the minimum because we want to find our bottleneck because in this case we can only create the word balloon one time because we're limited by the number of b's now what's the time complexity to do this well we're just going to really have to iterate through the entire input string so whatever the size of that happens to be is big o of n you know using after iterating through it we can create these maps and these calculations are pretty simple to do you know this is basically a hash map and we're going to create a hash map for the input string as well you know to get these values so the memory complexity is also going to be big o of n where n is the size of the input string so with that said we can jump into the code now okay so let's code it up the first thing i'm going to do is actually let's not initialize our result just yet so the first thing we really want to do is create a hashmap for the input string so let's call that count text we're going to count the occurrences of each character now i'm going to assume you know how to you know initialize a hashmap using a for loop but just to save time i'm going to use a counter because this is like a built-in data because this is like a built-in data because this is like a built-in data structure in python which will take some string and then count the occurrences of it if our interviewer really wanted us to write out the code to do this of course we could do that but maybe to save time it's always nice to ask your interviewer if they're fine with you using some built-in function so this is using some built-in function so this is using some built-in function so this is just a so account text is just a hash map counting each character let's do the same for balloon and i'm just going to call it balloon and you know it's feeding into this uh function we're just going to pass in the string balloon itself again we could hard code a hash map or we could write a for loop to go through each character but this is just a little faster before we go through both of these you know hash maps and getting those ratios we want to know what's the minimum ratio like i was showing in the drawing right that's going to be our result so what would be a good default value to set this to well we could set it to a float of infinity just to have it to be a really big number because we want to know what the minimum is so by saying it to this it would be a good default value you could do that but if you don't have like an infinite function or you don't even remember what it is we could also actually just set the result initially equal to the length of the input string text because we know it's not possible to create the word balloon more times than there are characters in the input string so this is also a good default value to set it to once we have that set up let's actually go through each unique character in the word balloon right by doing this we're going through our hashmap and what we want to know is that ratio i was talking about so we're going to take the count text so the number of occurrences of this character c and then divide it by the number of occurrences of that character in the balloon string so we know b occurs once l occurs twice right that's some potential values this could be whatever this ratio is we want to find the minimum of all the characters so let's set the result equal to the minimum of itself and this particular ratio by the way in python you need to do integer division you need to use double slashes that's why i'm doing that and once this is done all we have to do is return the result which will be the minimum ratio which will be the maximum number of times we can create the balloons right it'll basically tell us what our bottleneck was okay so let's run the code to make sure that it works and as you can see yes it does and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching | Maximum Number of Balloons | encode-number | Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible.
You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed.
**Example 1:**
**Input:** text = "nlaebolko "
**Output:** 1
**Example 2:**
**Input:** text = "loonbalxballpoon "
**Output:** 2
**Example 3:**
**Input:** text = "leetcode "
**Output:** 0
**Constraints:**
* `1 <= text.length <= 104`
* `text` consists of lower case English letters only. | Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits. | Math,String,Bit Manipulation | Medium | 1070 |
332 | Candy Crush Channel on my phone In today's video, if we are going to Candy Crush Channel on my phone In today's video, if we are going to Candy Crush Channel on my phone In today's video, if we are going to call Reconstructed Reena Question, then we will weave this in reverse, do you have some tickets given to us brother, how can the apps become like this, how can ticket suggestions be made, how can we go to ATM and like this for You can bring a day, you can go to Jaipur from ATM, you can do puja from ATM, right, now you have all these tickets, initially Jeff Yoga Spider, if I represent all these tickets in the customer's form, then the ad will ask if a scam had entered then you What has to be done, only then you have to use the Israeli one tickets, you have to use all these tickets, for this you have to visit all the united and tell everyone to visit Ajay, I told you through which cities you will travel, it is true. Diet jitni ticket city all are used exactly once that this point is done so did nothing but union partner tractor graph of Eulerian path if its video is not seen in the graph then see it this urine pass back talk about Mintu and Falls Pimple President Will it happen or not, then the next video will be in Turin to find out the same thing, how will you calculate it? When asked to take out urine pass, then how is it calculated? Now I will tell you that it was first slid in the market, so what is it like, so how much is it in Janpath. Also body honey one of them tax exemption degree can be more than these degree 101 force tax that can be more than individual degree with the help of which will continue to be more second can think and this reaction happens apart from this any number of words it All of them sleep that these degrees and degrees are at all the same, only then the villain is the circuit president and has given it here, then keep in mind whether she is pregnant or not. Is it written in BJP list Bengali return including Shruti validity is confirmed meaning. There will be some nugget and some how do I install it, then the fixed deposit will be an increase in this, it will be like this by going to [ __ ] Delhi and everyone else will have as much ignorance as these are necessary and for the going to [ __ ] Delhi and everyone else will have as much ignorance as these are necessary and for the details of this, I will suggest you Urine Baat and Union Circuit Interactive End I will check it out once in a dark well, but it is only milk and fruits, so how can we make it a year here, so what I am saying is that what happened was that if you were asked to tell the text, then simply dates continuously. Simply put an edifice and add things in the same wards where you will travel. I told the light, will I just put a face, then what is the problem, what is the cucumber, friend, if you have problem with this less joint, how do I go, ATM defo has two options. You have been asked to choose the lexicographical Ismail from the two options. First, when you can go to two places, then put it in this and choose the audio. Friends, you will do this with me. If it is time to go, then Mixture Paytm will work. Now because I follow you. Apply cadets, then you will forgive the development of ATM, then you have two options from Airtel and you cannot release such core data capture because it is respect, then you will forget it, now there is an option to reach like this, but if it is a positive step, then how? If you go, then in this option you will go to the stop, right here, I have not opened it for traveling in the world, tell me what I have said wrong, but I am saying brother, if you will travel to all the apps, then if all the apps If you want to inquire then I can travel the tips multiple times, now I am busy here but I am making it, there is a mistake, visit of but, it means but with little of apps, any gap near the news, call once, World Tractor So, if I am not convinced myself, then I will make one, no, it will go to an ATM like this, then I can go from ATM to Z, I can worship like this, then first this Kiran has as many options as Mumbai, if you paper these matters geographically first, then go like this. While the rest went to such a decision, the money is only airtel, went to ATM again, now start making answers from here, how can't go anywhere, can go here, you will only do extra, first add this city, cook add it. WhatsApp, phone masonry, the last ticket I used was Rs 70 because of this, I became like this, then I could debit the ATM, then you will say that I have factored it, so Airtel's network has been done in the name of this ticket, then you will do such elements like this. You are doing the work in the name of ticket, keep doing it, then you will remember the job, then when you talk, you will do my tab, then when you will cook the back, you will remember from A to Z and back track, then this is your slipper, the thing which will help you all in this. Akhand, you can try once, now this is absolutely CM, now in this I know mostly what happened when I thought of this for the first time, what would I have thought, now I backtracked and created a short answer, so come on, I can do this. The correct way is I have sent but will I add it while leaving, will something go wrong? If I rice in the hotel in which I am setting up the defense, why am I doing this in the situation of getting the apps set up now while coming back demanding UK? While leaving, I am adding that yes, this is still a possibility for love, all of you are frying it, you all are the ones who make AR Rahman's village brighter, I will be the first to get up and play the music of the table, then I will go to Airtel, why like this for Airtel? I will give preference to the lexicographical smaller. Sir, you are saying, 'Pair Sir, you are saying, 'Pair Sir, you are saying, 'Pair Airtel, then you will go to Jeth from Airtel. First of all, how is it that you are a pimp, you will ask like this, you will go to your husband's ATM. You will speak like this to your husband's ATM, and still I will add that all the apps visited have died. So you will get this answer type, it seems that yes friend, there is only one thing, keep doing rice, go to the middle and delete it and do rice twice again, moving away from the beginning, the difference is the film, the difference is the arts, MP3, alarm set. If you kill the name of this film then you will either understand the choreography, why it is absolutely necessary to add pass, it is doing its rice in the state, but will go to the back part only in the same audio, how can it not be done in this Mustard Bhai Jaan Salaam Nibhayega. Turn on this simple setting that if you do not use the Kingdom in English language then it will be in such quality that I will go to Airtel first in the retail pack. In this episode, you cannot go anywhere from Tips Indian, so I will dive into the end which I had put in the beginning earlier. And then I will do the lighter and then take it back and take it and then send a message in one of the options, how about the prostate, then check again, add it, phone teachers and cannot go anywhere else, after a meeting, then add it, go to the phone, cut off the office jet. Do this by giving felt tip by the state, start setting many pictures, you are the first one to come, how is the work of STF width, you go from ATM to bank and ATM, then this is how you got rid of it, then such a process is strange, a rally in Not seeing the pass, gel facial and then the certificate from the ATM, how will this be understood, I will tell you a tight square, when you make a graph and urine passes are piled up in it, then it can happen that your destination comes first, in this, your final The destination was that all the entries had been entered at the end and had been taken before that. In this case, both the things should work i.e. you do In this case, both the things should work i.e. you do In this case, both the things should work i.e. you do riverside and set the starting point, but the scenario where you will visit the travel agent while celebrating your visit, in that your The destination should come first before turning everything on. If you are adding as you go, you will add the oil to the same tree and then rice to the rest. Your destination has become a homemade month. What if I was setting the life? When I'm doing Riverside, I blitz my definition first a friend till I add him at the end now actor now this will not be subscribe now this part will be travel and in this part because all the vertices that these degrees and degrees If it is the same, now you will start memorizing everything here after travelling, then what if your definition comes first and you have added it from the beginning, then if you have added it while writing, then it will come to meet you, Patera is set backward. If you are doing it, then some respiration will come, you will do white lokayukta backstreet and now the difference in anyone's in degree and right degree has been taken, it is the property of the district and district, will two become closer, one will be more, one will be less in degree. It might have been one or two degrees more but the one that came out to be the previous one, if you have traveled, it could be that of a person, if you have done rice, then now it is a matter of you because there is a bag of beans in it, everyone in that range will do rice and only then. If you want to add here, if you talk, scold Shyam Sakha Shyam, then first of all, the characters who understand must comment, make a French twist and what I am talking about today in the channel, you could have done the top with an increase in the sweater. At this time or while coming back, when the tree breaks, add that you will get trapped in this case, in this the update comes first, I come, so what did I say, what am I coming to meet, if he had typed tiffin, then it would have been a matter of tightening you up. What do you have to do now that a point friend, what is the work visit you want to say, what is the meaning of its withdrawal, how will I make it, I will show you Amazon quit for vortices, I will show you how the graph will be made in this, how will this question aircraft be made. Graph will be special map will be kept Introduction that at the chief of Windows 8, string and gold medal get priority Q Sachin pilot is you, in this, professionals make ancient because if found someone has to give preference to graphically smaller one like two nibbles in the pocket Why did you go to the ATM first because Electrolyte is small meaning that the one who is the smallest among them is Bigg Boss, he needs to call first, you birds will come in the priority queue, seeing him you can just say a grand salute to him. Specific two number to 19th such for how many number of airtel two exact scan specific for this such focus is only one ATM so what will be the benefit from it before this young what lexicographical smallest we will be able to extract tele I like judge get started from Now I am going to call, what will I call her nipple, the property that is submitted to me is ok but remove it or call me otherwise my knowledge is absolutely correct, now we will also take the work of visit like JSK payment know that I That's not it, rather I will see, I will just kill the applicant, then automatically the lexicographical smallest will come out, then when the ATM will come out, then I will call through Airtel and I will make the middle disappear from the criminals, I will call Vikas and now the ATM will be in the priority queue. Not only this, it does not mean that I have gone to the point of forgiving the visitor or you have removed it, use it once and have removed the dead skin, now it can never be used again. Do it is equal to retail price. This is your crush. There will be no return, like you will spoil the customers of the teams, you will remove the apps, the daughter 's answer will come, otherwise how will I do, I have to 's answer will come, otherwise how will I do, I have to 's answer will come, otherwise how will I do, I have to keep Friday, I will remove the purse, I have to travel once, oh love, sometimes you can't, now see tomorrow. You will cry if someone says no brother, do n't spoil the graph, if someone says something like this, don't spoil the customer, then you will have to achieve again like you will have to achieve that from where you are going to where you are going, there is a subject of source and destination. Put some desks in the middle and ATM, so it is becoming a little present in H to check your team. Will you ever again go to call against James Cassie that you will check in Britain, put it in the visit address and check or ATM of juice is already ready due to fear of gas, what is the role, again meaning, you can add one and now want to clean it, ask it in a good way to remove the radicals, whether it is tight, then friends Ashraf Ali, for the smallest. Why should you remove it from the name, then it is like smoking cigarettes, now quote it quickly, the code is 332 clicks, if you fold it quickly, it will be fun, Jhal, did not listen to one plate, first of all, for those who do social media, I will make you a graph, then a face. Map of range versus experiment British youth complains about all this, I do not answer as per a qualified competent, link because I have to type it is compulsory, I am making it in full English because it is said in English, its add is first oven, so I have made the link from string. Install strainer to jhal solan place of children for whatsapp chanchak space and not even equal toe will mix him times strike is now graphical to new hai snap slide then definitely answer is equal to new a little s a that now body start tell and all bake subscribe By doing this, we have given the list office, so list officer training list of train ticket, where will I get the ticket from, will I take out the ticket, comment from the monkey, Kanodia of clans will be constructed, we will cook this too, so how will you get angry, so repeat the previous song again. Set that 101 what should I do, why am I a party and have a friend, take it out of this, I should talk right, think good, I should get all the most difficult, the show is creating a political map for kids, should change the default language of the ticket. Dot 202 for which he is starting, what is the quality of chicken, Dot 10 and Difficult, Zero and New Price, that is the new purity, I am rich, etc., you are I am rich, etc., you are I am rich, etc., you are becoming times like this, if I got it from a gas shell, I will make me laugh. Why is there a corresponding priority? If you have a practice then gift it to someone else, if not then look at the new one, see this, I have spoiled it, now we have got it done, I will add the new dependent to it, how will I do the mountain on the song, and I will do it time. Dot MP Dot Airtel Limited Which Monkey Ticket Do Not Gate What happened, I gave this investigation to everyone, then Difficult Pandey Nagar Pvt. Cut it off from here, why not the property, then this lighting also a little more, did I add it which is not his? But which is the subject of the ticket in it and then you have to shift it in the graph, Power of What Should Thakur, from where you took it out, in the remaining tank, I fitted it on the back side and that's it. Added to the graph, now in a soldier in which your brother-in-law will be going, in a soldier in which your brother-in-law will be going, in a soldier in which your brother-in-law will be going, thinking about whose power, he will be doing first and will have to spend the day and on the side, I have to give the industry, taking all this skin, fitting the play list in Tigers like Share Thank you, if I come then how do I need to dance here? First you can write something that I will add from the video while adding in want fame answer. I will apply sauce and sunscreen lotion for the fixed thought. The alarm I set for this. Set this of I will be the first one to come out of his network soft whole this train near the tube that unfaithful equal to customer top gadgets should be arrested typist accused profits now that till Punjab till its nibbles till now till its budget spiderman equal to Z there is no one in it The guy is entertainment, the size of my friend's residence is 30, I am Anil, I have the powers to do something, only residence, till when I have the purse, of course, we will keep working, yes, till we are successful, friends, keep working, today we will talk about this, my extreme will come out as a pimp. If you are not able to find a lexicographical small place, then it will come to you, if you remove it from the butt, then the main private has been made that if you do that, then the matter will be resolved, now if you do school for this, then remote quora pistol. If you can work, then you can work like this, but when all the purse processes are done, you are going to do the banking from here, if you are going to hold the meeting from the place of permanent residence, then what will you do easily in Add First Year First Someone? I will add what you have thought that it is like this, now call me like I have taken out the property of neighbors who sacrifice animals while its size has to be seen, depending on the place, I will start the equal to neighbors start remote for which I postponed and for that Call and see, brother, make it a smooth journey. Teams have different systems. Called for the cross. After all, I think how successful the center has been. Tips three A jhal hua tha, Ajay ko that your channel function has come jhal. Why did it not happen? Pointer exception is not coming, I did not bring in the bus for money, does this, do not take duty at all, once a person has unknown Pune bus medical panel, what if ever in front of Bigg Boss, any issue should be done to him Can't be kept to fry all the people, you have them, they must have been made in the priority queue, then sometimes there can be a tap in front of any thought, then for that, terminal leon is needed, it is making the last puff of the internet, we meet and then were in the mix video. that if you mesh | 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 |
478 | hey everybody this is larry this is day 17 of the march decode daily challenge hit the like button hit the subscribe button join me in discord it's almost the end uh welcome uh let me know what you think about jay's farm generate random points in a circle i usually do these live it's a little bit slow let me know or fast forward because you have to your master of time uh okay so actually i did i've done this problem either recently or something like that or i remember doing this one um because i think the so the naive thing to do or my first incarnation is to have two variables right uh r and theta where r is the radius and fader is the angle right um and then just you know do random r and then random fader and then go but the problem is that it actually does not it's not uniformly distributed in the circle um let me see let me pull up paintbrush actually give me a second technology um yeah but the problem is that and pretend this is a perfect circle um is that if you have two things right you have r which is the radius and then you have theta which is the angle so r would be you know for example uh let's just say let's pretend that's the middle so r would be the length and in theory i mean you could draw also obviously draw this from any point um theta would be that angle that's in between right um and the problem with this is that actually it um it's not uniform is that it's that um i don't know how to prove this to be honest uh and it's just that and i was wrong about it the last time i was doing this but it's just that if um given that r is uh if you choose r to be uniform it actually uh has bias uh against the more remote points right so i mean and i don't really have a great way of proving this um at least without like a long mathematical formula you can find google on the internet but the intuition is that um you know let's say you have the same fader right i mean let me change the color a little bit uh let's say you have you know here the same you know you have two fade you have the same fader uh let's say they're the same length right and then you have the same uh you have a shorter er but the same uh fader um in this case you can see that this if this is uniform this actually more spaces in between right on the top one so you have to kind of adjust for it because um but there's not uniform because on the top there's more spaces right um because of these extra spaces it means that it's not gonna be uniform because that means that dots are more likely to be biased toward the center of the circle um i think that and i actually know the answer to this because i looked it up um like the last time i solved this but i don't really understand the proof to be honest or at least like um you know so i'm just gonna just say it um and the answer is actually you end up taking um taking the square root of a random variable of r um which is the way to do it but to kind of get or maybe even how do you want to yeah so basically instead of doing that you get a random of uh theta you get a random of uh wherever then wait is a square with a square i actually don't remember maybe i need to look that up to be honest it's been a long time um yeah but i think it's square root okay so but however what i'm going to do is not this which is why i which is fine otherwise we could look it up together and maybe we still cannot get up together so what i'm going to do is instead i'm going to draw a square box and then i'm going to put point a random um changing the color again we're going to make random points uh and then we turn the first point that's inside the circle um so this is a randomized algorithm anyway so yeah so then your question may be well but couldn't this go into an infinite loop well the answer is that well the circle is clearly um the circle is clearly more than half of the square and you can easily do math on you know pi r square over or square which is wait is it no that's oh pi squared over 2r square which is you know pi you know what i'm trying to say we could do the math but the point is that you can see very quickly though that the circle is bigger than half of the square in area and because of that you know that you can actually do this in an amortized or probabilistic constant amount of time uh to get a dot inside the circle because of that convergent series that means you know like one half plus one fourth plus one a plus dot and that's equal to all that's equal to one right because that converges to one so or two depending on how you start with one operation on an output uh but because of that if you just do a random dot and see if it's inside the circle and then we turn the first one that is inside the circle that should be good enough um it does have a worse uh oops it does have a worse worst case um you know bad scenario but i think that's uh for me that's already um that's the way that i would do maybe on an interview even if it's not the perfect solution um that's it you know we'll go we'll see if we could go with the other one uh the other solution later uh together because i know the answer but i don't know i mean i don't understand the proof very well i think i didn't do did that for last time but yeah um okay let's see uh yeah oops so let's set the radius and then we just get a random point we get a random point between uh of you know uh which between zero and uh with two times radius so basically we're just doing a square box from z we just resent to the zero and then two times radius and 2 times radius on x and the y and check if it's inside the circle and then keep doing it and as we said because we know that this is a convergent series we know that it's gonna run in reasonable time and as long as we uh you know as long as we don't do anything weird um in other languages you may have to actually make sure that you see your pseudo randomness so that it doesn't um no you don't do something like predictable or something like that but uh but yeah uh okay so actually remember how to i actually don't remember how to do python randomness it's been a while all these off my head so i'm going to google that real quick is it just random that random okay so random god don't know uh so random.random gets a number uh so random.random gets a number uh so random.random gets a number between zero to one so we just times it by uh well okay what does that mean right so we have two of them one for x is one for y and then basically we want to check whether this is um this is inside the radius of the middle so actually yeah maybe i set this a little bit weird maybe i don't even need that but this is between zero to one so we just have to translate our um our thing so that okay so then we want to actually convert this to um random.random um random.random um random.random uh gets a number between zero and one let's convert it to 0.5 let's convert it to 0.5 let's convert it to 0.5 and 0.5 uh so let's actually ignore this uh and then now we check um if it's inside the unit circle right so the unit circle of course is if the distance is uh less than one away from the middle i think that's good right or is it one or half oh yeah no because now it's a half boxer so we have to check that this is um yeah so r in this case is so it's not the unit circle so i just circle with a radius on five okay uh okay so then we have let's just say rubber route true if um x plus y to the 2 uh is less than so you would probably multiply it out so i guess that's just 25 right uh then this is inside and return um well now we have to you know um so then we want to times this by the x plus sub dot x uh oh what do you want this is a list so then yeah and i think that's maybe it let's give it a quick go i mean obviously then it's not going to be the same but does it look okay uh yeah i mean maybe yeah let's copy the second example just to see i wish they told you already this is successful because i guess it's hard to tell from just one case um yeah let's give it a submit halfway doesn't oh why are you sent us so close well that's a little bit awkward do i have any buyers on this one i don't think i have any bias on this one hmm maybe i'm wrong as well first quick that's weird i mean i don't know how so litko does have um a thing that checks the distribution i think um do i have a bias here hmm i mean i it's hard to donate to tell but it probably looks close enough but does this have a bias maybe we'll have to find out together i thought this would be good to be honest because it should have all the dots in the pen like i'm thinking about the dots and all the positionings um and this is just saying that my distribution is not good huh and there's no way for me to kind of see whether this is good enough to run again or am i just a little bit unlucky on the distribution um hmm let me think about what i want to do i mean i know the other answer but i can't really prove it either um this one it feels more intuitive but maybe it's wrong oops sorry for kind of misleading you if that's the case um i mean we did pass all the minimum ones right so let me double check that we at least check out all the negatives and positives uh yeah i mean it looks like we at least have you know negative numbers on the x and the y so it's not like i did anything weird all right let's give it one more submit and if it's wrong then we'll just cheat and go to the other one together okay huh okay i mean let's um all right let's do it the other way and then i thought this would work hmm and i have to look at the proof for this but uh okay yeah i mean i do actually happen to know the other way as we mentioned before so we can just do something like um for the square root and then fader is you go to random.random um times pi or something but i have to do the math in a second but basically yeah we just convert this to um you know this is the polar coordinates and we have to convert this to um uh we have to convert this to uh what do we call it to quotation coordinates sorry i'm a little bit stuck on the other one as well but uh okay so yeah so x in this case is you go two um i made to get them confused actually so but it doesn't matter due to symmetry but i may get them confused so uh definitely you know uh apologies if that's the case but that is just um x is equal to r times uh cosine of theta right okay this is it map.pi in python okay this is it map.pi in python okay this is it map.pi in python let's wrap that pi and then we'll look it up something like that and then we turn um oh right now i have two this is look roughly okay it looks kind of the same so i don't know so let's give this a minute it might be wrong i don't remember this is square boot but uh huh decided that i just have a fundamental misunderstanding of this vlog that'll be funny all right let's give it again if not then i'm just going to have to look it up because i think um oh man wow hmm i feel like i've done this problem too so that's a little bit sad that i did not learn from last time um it's loading i don't know where did i done i definitely have done this farm but maybe it was on or maybe it was on or maybe it was on or something uh okay so let's look together oh did i mess up that did i have to do two i didn't do the math i was a little bit lazy maybe that's why uh because it's two pi fader yeah okay it's really sloppy today that's my fault everybody um i got phoned off by this because i wasn't hmm i mean this is so much like item math or trivia it depends how you want to call it uh and again i don't know how to prove this so you might have to kind of read it with me and we'll see it together i mean this is just um oh but this is a good actually picture of um of why that's the case as i was saying because there's more spaces on the outer side um so it's not distributed and you need and i do remember that you need to square uh root of it uh from learning last time as i was saying but hmm actually i had this solution did i mess that up maybe i just messed this up i had this exactly right that's weird well at least i would say that my first idea was correct but or like in concept maybe there was some implementation thing um let me play around with this actually that's weird because i mean you know y'all saw i did this the other way um how did i get back what was i doing well okay so i mean i think the takeaway is that okay i mean i was confident about it but there was a lot of math that i wasn't sure about but this is my thing which is the same idea um why how did i do this well or incorrectly this is a number between point zero point negative point five and point five huh because this is basically this right that's weird i don't know why my solution is a little bit well well yeah why is this wrong then huh i'm going to try to debug this offline but uh but it seems like this has the right idea um yeah uh i'll be right back uh hey i'm back um actually i so i looked at my old solution this is my own solution um i figure out why um so the short answer is that um uh i would say position error um so this is a little bit of a rounding error or position error mathematically this is correct and this is why i had issues with it with um you know with trying to figure out why this is the case but the answer is that um and this is actually a pretty good lesson for me though i mean i knew about it but i or like i know of it but it wasn't in my mind so maybe it's a good lesson for you at home as well but the reason is that um you know and you know uh what was my example that i got wrong so i hang on so basically that's actually a kind of hard uh i mean it's not a hard thing it's just a nuance thing that you know you might not or i did not uh do as well uh let's see right all right let's look at what um all right let's just look at the first input right oh man okay well whatever uh the idea is that okay so basically um the input that we were given and this is actually comes into play a lot with uh votes and stuff like that and i was just being very careless because i haven't had to deal with it in a while with respect to uh lead code or competitive programming but in real life this actually happens a lot so you should be careful about it but the idea is that okay the radius the sub.r the radius the sub.r the radius the sub.r the radius constraint that we're given is 0.1 where our is 0.1 where our is 0.1 where our xy is equal to some big number right let's just say a billion um then the problem is that well maybe the other way around um though in this case is this but the problem is that given random that random we actually do not um because we do this thing where we find a number between zero and 1 and then we multiply it the problem is that when you multiply you actually lose significant digits relatively so it actually was not precise enough as a result and what i mean by that is that when you have something that's small actually the xy doesn't really matter um it's just that uh or well maybe it does but it's just that by comparison when you multiply it um you can think about it as uh maybe the other way is a little bit easier to visualize let's say you have a radius that's really big um if you have a random number that's really small um between zero and one it might look like this and it may not i mean i know that has more zeros but just an illustration um that means that instead of getting all the possible um you know because we time times random variable times radius here um it actually may make it so that each step is now one instead of the smartest possible right um and as a result that's how we get the wrong answer so it's just not precise enough um and i know that this math is very rough but that's the idea is that because we multiply it um the error the step error if you want to call that of random that's between zero and one we now multiply that by another possibly big number um so and from that it magnified the steps versus instead of um uh getting the position right so the way to solve this is actually just by um yeah just by doing the you uh calculating the um you know in math.random there's a uniform in math.random there's a uniform in math.random there's a uniform function that uh lets you get the range of stuff so then we can just do uh from negative sub.r to self.r uh negative sub.r to self.r uh negative sub.r to self.r uh same thing here and oops and once we've done that um you know this is the distance is now subtract r squared we can actually cache that of course uh if you want to be performant and yeah and then now we don't have to multiply by x here and that should be good enough well let's give it so basically the short answer was that we were just not precise enough uh even though i had the right idea and this was oh i set that in that with a typo oh whoops no i mean i do have a typos dancer oops oh i wasn't even it's all even a variable how did uh no it was subtle okay because everyone was returning the same answer so of course as well uh okay so this looks good and also one thing to note is that they actually tell you whether it is accepted in this real versus and the daily problem view so um does that so that's a little bit awkward because that was one of my trick to thinking was that i couldn't able to test it but yeah um so now once we send a submit uh it looks better so yeah so the idea is just precision errors and i like the solution a lot more because i don't have to memorize or prove any uh really hard problem i like that in this one um you know you just basically have a circle and you just put dot you put dots that are random you know that drawing dots in um in a square uh it's going to be uniformly distributed it's just about whether it is inside a circle or not and actually coincidentally that's how you do numeric uh integrations as well so it's good enough for integration is good enough for us uh because it's gonna be uh uniformly distributed um cool and as i said because we know that um we know that this is uh this is let's put it here actually we know that this is true greater than half the time then the running time is going to be um probabilistically uh constant because it's just going to be one half plus one half of the time it ends at you know times one plus 1 4 times another operation times 1 8 for another operation dot and this is of course equal to 2 right so this is going to take up two loops on average um give what i mean less than two loops because we know that this is greater than one half right but yeah um in terms of space obviously we don't really use damage space as constant space uh cool that's all i have for this problem it's a little bit messy and i kind of jumped around and i'm not gonna go with the other solution you can google it and look it up um because uh i don't know i don't find that useful i mean if you want to do if you want to learn math if you want to play around with all that stuff you know feel free to up salvage yourself but for me i don't know well i would also say i definitely need to get better at that the math to the trig trigonometry but um but that's not today so uh we'll talk about it later uh cool that's all i have for this one let me know what you think um even though i had a simple and correct answer i definitely had some issue with the implementation that i learned so it was good for me okay that's all i have a good day take care of yourself i'll see y'all later bye | Generate Random Point in a Circle | generate-random-point-in-a-circle | Given the radius and the position of the center of a circle, implement the function `randPoint` which generates a uniform random point inside the circle.
Implement the `Solution` class:
* `Solution(double radius, double x_center, double y_center)` initializes the object with the radius of the circle `radius` and the position of the center `(x_center, y_center)`.
* `randPoint()` returns a random point inside the circle. A point on the circumference of the circle is considered to be in the circle. The answer is returned as an array `[x, y]`.
**Example 1:**
**Input**
\[ "Solution ", "randPoint ", "randPoint ", "randPoint "\]
\[\[1.0, 0.0, 0.0\], \[\], \[\], \[\]\]
**Output**
\[null, \[-0.02493, -0.38077\], \[0.82314, 0.38945\], \[0.36572, 0.17248\]\]
**Explanation**
Solution solution = new Solution(1.0, 0.0, 0.0);
solution.randPoint(); // return \[-0.02493, -0.38077\]
solution.randPoint(); // return \[0.82314, 0.38945\]
solution.randPoint(); // return \[0.36572, 0.17248\]
**Constraints:**
* `0 < radius <= 108`
* `-107 <= x_center, y_center <= 107`
* At most `3 * 104` calls will be made to `randPoint`. | null | null | Medium | null |
472 | Hello gas myself Amrita welcome back to our channel technostat so in today's video we are going to discuss lead code problem number for 72 date is concatenated words so this is an hard difficulty problem but don't worry we are going to make it easy for you so nine Let's Get Started Let's First Understand the Problem Given and Are of Strings Without Duplicates Written All Concaved Words in a Given List of Words So in the Example You Can See We Have Bin Given One Are of Strings Date This Word Which Has Multiple Strings So See Need you check which string is concatenated nine let's understand you are going to check date so let's see we have one list of strings date is cat dog and dog cat so nine its thing is concatenate string is basically van string which is formed from the respect tu strings for example this dog cat is a chain of dog and cat so cat is noted what dog is tomato in this list of strings is dog cat but you are going to check date so basically what are you going to do Will take one string and will break it in two pieces for example if you have too see cat weather it is unconcrete or not so what you are going to do can see break it as we see and 80 right so see have you check weather see There is no it is not there it is not dear so date this is not an unknown possibility for this string c can also bracket and the respect way for example c can also say it jump be broken in ka and t c and t r also give This is not an incomplete string can see bracket further no see than it will come today d complete string itself that would be cat and null right but can see d complete string so it is already there so see do n't need you check nine let's take d Respect String for Example Nine See Are Taking Dog Cat So Firstly See Are Going To Break It As The End Ozzy Cat It's Not Dat Give Do G Cat It's Not Dat Next Possibilities Dog Cat And Then See Will Check Weather Dog Is There Yes It's There Give will check weather cat is there yes it is also there date men this is un concatenated string correct but no one more thing is there let if i change d input today dog is there let say cat d input today dog is there let say cat d input today dog is there let say cat is not there see have ka and t give also This is un concatenated string but give see are breaking it so see will say do o g cat it's not date give dog date it is not date give when see come every dog and not date give when see come every dog and not date give when see come every dog and cat will see date is there but this cat their cat Is not there give will de turn falls no right but it is not a related word so when you found this word you have too break our word today well let's name these words today prefix and six so they have two possibilities both prefix and six Are already present further it is in a list of strings correct and then one is date prefixes there but six also you need you break so when you will check she there know it is not date give father break it in ka and t nine ka and There is so here you will find date it is concatenated so d our possibilities date if you found prefix you have to further break the suffix in the prefix and suffix until you found date it is an unconcaved word so this is ho c need you check Where a particular string is an unconcaved word or not nine let's break this into these steps so what are the step numbers one so what you need to do is write the function which will check for each word and take each word and will check whether it is an kancardinated or not so in this function What are you going to do are going to first find the prefix and suffix correct once you found prefix and safe give you have to check the condition when both prefix and suffix are correct and prefix is There and six also you need to check whether it is concatenated or not you will call d se function and you will check whether it is con concatenated or not if both d condition are true then you can say date particular word is to date mains date is Concatenate So When Date What Is Concatenate You Need Same Data Structure You Store Where A Particular Word Is Continuated Or Not Right So For Date Let's Take One Has Map So In Date Ha Map We Are Going To Store D Word For Example Will Store Ka End C will return its value when it is concatenated or not this is not contiated so C are going to say this is one foot and then the next pay will be t come of all density is also not can be contiated when you come to the dog cat you Are you going to say it is concaved so you are going to return true and also let's say all these things in which one set of strings will take one set of strings in which you are going to store all the strings and then one set of strings will take H string you check whether it is concatenate or not when it return you are going to say it in d has map and come di and c can return d list of strings which are concatenate now let's try given solution for it so this is r class date is continated word nine let's try method date would be public static list of strings and let's name it as find all concatenated words write and what is d input is area of strings date is what nine what is of strings date is what nine what is of strings date is what nine what is d first step c are going You take one has said you store all d strings let's name it one say it should be equals you new has set so it would be set of strings and let put h word in d head set so for h word h string date this word which Is Present In D Words Arrange C Are Going To Add Date To D Head Set Correct So You Have Everything In Your headset Nine Let's Take A List Of Results In Which C Are Going To Say All D Strings Which Are Connect Date Would Be List Of Strings let's name it a result it would be and arraylist and nine for h string are going to check whether it is concrete or not so it will be i < word length i plus write a function for date so let's write it public and Let's take a hash map of strings and also we have to take one map in which we are going to store the value for h string let's take a has map so let's take d map of string earn boolean let's name it self this showing error science It is you have to name this set of strings and nine what you need to do in this method is you need to check if map has already date keep present then you can directly return its value whether it is true or false than it would be retained HMT word write and if it is not date then give what do see need to find are prefix and six let's try D loop for date because see have you check h string so it would be word dot take i++ and string so it would be word dot take i++ and string so it would be word dot take i++ and give see have You find are prefix and suffix prefix wood b substring of zero kama i+1 yi+1 because substring of zero kama i+1 yi+1 because substring of zero kama i+1 yi+1 because end index not included in substance method and what will be d suffix six wood b plus van til d length of d string so date wood b word dot Take and van tu found your prefix and suffix what would be the next step c need tu check van condition contents prefix and perfect give what do c need tu say date in the has give we put word earn its values true date in the has give we put word earn its values true date in the has give we put word earn its values true date mens It is continued and see can retain you and else what do see need you put us dot food word date mains date word is not continued so it on falls checking h word so far h word see need you call the function date what tu d result body word take the word are which has words like cat dog and cat dog so it has only one string that is contined which is cat dog so let's call preposition statement and let's call of function date would be find all concatenate words and d The word nine can see every output is a scam because it is the only correct word in this list nine let's take same respect word for example dog is not there and see have program thank you for watching | Concatenated Words | concatenated-words | Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`.
A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array.
**Example 1:**
**Input:** words = \[ "cat ", "cats ", "catsdogcats ", "dog ", "dogcatsdog ", "hippopotamuses ", "rat ", "ratcatdogcat "\]
**Output:** \[ "catsdogcats ", "dogcatsdog ", "ratcatdogcat "\]
**Explanation:** "catsdogcats " can be concatenated by "cats ", "dog " and "cats ";
"dogcatsdog " can be concatenated by "dog ", "cats " and "dog ";
"ratcatdogcat " can be concatenated by "rat ", "cat ", "dog " and "cat ".
**Example 2:**
**Input:** words = \[ "cat ", "dog ", "catdog "\]
**Output:** \[ "catdog "\]
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= words[i].length <= 30`
* `words[i]` consists of only lowercase English letters.
* All the strings of `words` are **unique**.
* `1 <= sum(words[i].length) <= 105` | null | Array,String,Dynamic Programming,Depth-First Search,Trie | Hard | 140 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.