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
78
are you recording hey everyone ali here today's problem is called subsets and it's been asked by these companies now let's take a look at the question together so the problem gave us an integer array called nums which consists of unique elements and it asked us to return all possible subsets or in other words the power set it also said that the solution set must not contain duplicate subsets and at the end it said to return the solution in any order so the order is not important for us it seems pretty easy question but let's look at the given examples also so for example if the input is one two three uh the output is null one two three one and three two and three and one two three itself or if the noms array just has one elements one zero the output is null and zero or the array itself it also gave us several constraints the first one is that the length of the numsari is from 1 to 10 and each item in the nums array could be from -10 to 10 and also again all the from -10 to 10 and also again all the from -10 to 10 and also again all the numbers of gnomes are a are unique so as you can see it's an easy to understand question and i don't think so that we need to talk about that further more so let's jump directly to the algorithm section and see the suitable algorithm to solve this problem with before i run the algorithm and show it step by step to you let me talk a bit about the intuition of this algorithm that i want to use one of the best algorithms for this problem is based on bit masking but what is bit masking in bitmasking we kind of map each subset of the given set to a binary number of size n then in this binary number which is known as bitmask we search for once and whenever we see a 1 we add its corresponding element in the set to the subset so for example here our input set is one two three now i wanna write all three bit binary numbers from zero to one and then look for ones to find out all the subsets so the first number that i have is 0 and as it doesn't have any 1 so it means our subset is null so it shows the null subsets then we have zero one and as you can see we have a one here and now we have to look or compare this binary tree to the set that we have so zeros shows that we do not add them to this offset but one shows that we have to add the corresponding number or element in the set to the subset so here three will be add to our subset or the next number is for example 2 which is 0 1 0 in binary so again we have two zeros and these two zeros map to one and three so we do not add one and three but we add two because the middle uh bit is uh one so we have to add two and it's the same when we have two ones or even three ones we just look to the number of ones and add the corresponding element to subsets so for example if we have uh this binary number we add one and three that corresponds to these two ones and ignore two so the subset would be one and three or when we have one we add all the elements of the set to the subset okay now let's run the algorithm to understand it better so first of all we are here and we have all zeros so nothing we have so the current subset is null and the output is also null so this is checked then i clear current and go to the next number so we have one here and don't forget that we traverse this number from right to left so this one corresponds to three in the nums array so the current uh subset that we have is three and i also add it to the output let me erase this and put everything in one place so we can save more time so we have three and we clear current and go to the next number so it's 0 1 0 and it corresponds to 2 so the current subset that we have is 2 and also i add that to the output and then we clear the current subset and go to the next number so it is 0 1 and because we see that from right to left so it means that we have a three and two in this subset so it is three and two and i also add it to uh the output then again clear current and go to the next number which is one zero and again we read it from right to left so it corresponds to 1 and we add 1 here again we clear it and go to the next one it is one zero one so it has one and three so three one and we also add it to the output again we clear current and go to the next number it is one zero so we have one and two in the subset two and one and also here again we clear current and go to the next number which is one and is the nums array itself so as we expected we found eight subsets uh of the set and you may ask that why i wrote current because it seems you know kind of extra that's because on the code section we need that so i'll cover that later on the code section and now that we understood the algorithm and we have kind of a intuition to that let's jump to the code and see how should we write the suitable code for this algorithm we take the nums array as our input and we return a list of integer lists which shows all the subsets so first of all i just declared the output which is a list of integer lists and then i assigned n with the length of num's array and then we have a nested for loop and in this nested for loop we want to solve the most challenging part of implementing this algorithm but what is the most challenging part of our implementation as you remember from the algorithm section we wrote bitmasks to calculate subsets now the challenge is with the zeros on the left side of each beat mask because we need to store them in the memory to calculate these offsets but we cannot do it simply in the code so normally if i store 0 1 for example i lose all the zeros on the left side and the actual value that is being stored in the memory is one to solve this problem we need to use a trick the trick that i used is with the index of the for loop so as you can see in the for loop the range of the i is from 2 to the power of n to 2 to the power of n plus 1. so considering this is the num array as n in this case would be 3 the range of the i would be from 8 to 15. now if i write corresponding binary numbers range of i would be from 1 0 which is 8 to 1 which is 15. and if we ignore the first bit of these binary numbers i range would be from 0 to 1. as a result we have generated all required bitmasks and also saved zeros on the left side of each bitmask in the memory so problem solved now let's see what happens inside this nested for loop so first of all i just created the current list that we use in the algorithm and then i assigned i to the temp then i wrote another for loop and in this for loop we iterate through the nums array to find all the subsets but how do we do this as you remember from the algorithm section we traversed each bitmask from right to left to find ones and added the corresponding numbers to the list of subsets here i want to do it kind of different to make our code more efficient so this time instead of traversing each bit mask we just consider the rightmost bit of each bitmask and then shift each bitmask to the right for example consider that our current bitmask is one zero one so we just look at the rightmost bit which is this one and on each iteration we shift this number to right so for example now we have one zero one and this bit is one on the next iteration this number would be zero one zero and the rightmost bit would be zero and the next one is zero one this way we not only traverse every bit of the bitmasks but also save more space and time now let's see that on the code so we take the rightmost bit by this mode 2 and if it's equal to 1 we take its corresponding number from the nums array as one of the subsets elements and then we do the right shift by this line afterwards we add each founded subset to the output list and after we found all the subsets we return the output now let's submit the code in and see the results so it's been accepted and now let's talk about time and space complexity for time complexity we have a nested for loop and the boundaries of the first for loop is from 2 to the power of n to 2 to the power of n plus 1. this adds an o of 2 to the power of n to the time complexity also on each iteration of the first loop we iterate through the whole numbs array once which adds an o of n to the time complexity therefore the time complexity is o of n times by 2 to the power of n and for space complexity in the worst case we have to keep all the subsets of length n thus we have 2 to the power of n subsets of length n which means that the space complexity is o of n times by 2 to the power of n
Subsets
subsets
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_. The solution set **must not** contain duplicate subsets. Return the solution in **any order**. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\] **Example 2:** **Input:** nums = \[0\] **Output:** \[\[\],\[0\]\] **Constraints:** * `1 <= nums.length <= 10` * `-10 <= nums[i] <= 10` * All the numbers of `nums` are **unique**.
null
Array,Backtracking,Bit Manipulation
Medium
90,320,800,2109,2170
1,508
In the shift of flash lights of liberty, we are this relationship, that soft morning, Samsung, I am the bank garage, by the way, here it is 1234, given that it can become many of its mornings, DJ Seven is a question in itself, so pay attention to it, then its 1234 Its time starting from two is like two three four earth starting from Mars time is like 3034 husband again starting Sardar Asset Isko So then total if I see then chain * inflation but oo a system see then chain * inflation but oo a system see then chain * inflation but oo a system of natural numbers here But if the NGO people have exercise number, then I have added one, they can ride in one, two, three, four, skin, 1, this is one, two, this is 123, 1234, then after that, two, three, four, square, three, loot, cloth. Survey Report Gare Natthu MP Service interval will be less like 130 60 2.5 inch plus 2.5 inch plus 2.5 inch plus dad clams and this is the question demand at the time of service that you physical cleanliness fold this joint this 123 low floor sorry second one ok 123 like austrian more 687 398 this is our subscribe to now we have passed the increase by tightening the platform hit one left and have passed the decrease you have to give any number within this range to the points if I move from here to here then all these It is okay by conferencing the numbers, how will all these Namaskar organizations look pregnant and request a quality solution for this, but for now, whatever we do, let us do it from Madrid and the same complexity will go in square route, then not in square and in square law. And specific Baahubali printer, okay, so first of all, our task is to say that whatever will remain with me with the name, what will we do with it, if it is needed, it will come for it, songs, request, share to you, a smudge request, why do you need invent exercise, 200 I am Hindu. I think that drop in plus wave fight exercise should be done and let's see what will remain. Let's make the index. IDA CEO, the sign of which is zero percent. Now we get the chords. Point raised, it is asked. So, this is the decision and request. And half the request is something like zero six. Let's start, if Ali has a problem now, we will make it grand. This is also the judge. These were the last budgets and if we want to see, then first we will make one. Every time we come to tell me tomorrow, we will make one. Is it initially zero percent? Will request from sample to sahu plus request to us 6.15 to 6.15 we will add request to us 6.15 to 6.15 we will add request to us 6.15 to 6.15 we will add our sa masala ad that use IDX plus job hide apps and then increment it. Will we give a good report to those who subscribe to me? If she does it, everyone will sit down, we will carefully look at the code I have written it till now, you can see it [ I have written it till now, you can see it [ I have written it till now, you can see it Scientist Dr Jhal Ajay has got Jhal, I have yet to fry, we have space Which has helped 1234 and I have a smudge of ours in which how many pages will there be and its form into 4th round at this point divide to address and 108 Thomas at justice ne point 560 inductive do this g what do I try from If the form of this day works, then I request to zero Anniversary for Dhoni's request to come, if it bursts, a rally will also be taken out, yes and a prosperous, what are we doing, we have a number market song which is on 0, som place is equal to two according to jail, see I will make this Zero and Norms for Baby Boy all updated at that time. If this one is in front of me, his 0h index has also been hired. We will press the zero position in the evening. On this question, get arrested in the evening and close it by making a byte of the index. Di is ok and this note will be circulated again and it will make ₹100 and this note will be circulated again and it will make ₹100 and this note will be circulated again and it will make ₹100 ok what will we do Sampla Surgical Strike Name 100 Index and Smallcap Index - 2012 Less than had been done by the Smallcap Index - 2012 Less than had been done by the Smallcap Index - 2012 Less than had been done by the communities now it will be printed so what will we do 100 index on the vehicle of index Will put the husband and press the index, the test is fine, now how many tubes will the updater give, then the round election will be 9483, 12336, the updated oil of the evening is equal to six, okay, where is it, we will do something about it. Sadhus of ideas in this award scheme will invest in vouchers 2 3 things and one person will melt and give Shiva okay understand the name is this and no and number you six plus 4 6 plus form request that this we are here on yours Adidas ki Age, how much heat, it is okay, now let's see, it is equal to a blind person, should I reach waste oil - a blind person, should I reach waste oil - a blind person, should I reach waste oil - history, the value like this will not work towards these schools, now we will go on high flame, maintenance had come, we should comment, there is a bit of frustration on the forest, the reason for this Since the old number was done its work has been done and in the evening we dished it a little bit to the statutory the studio creature will go again and will be high so first of all what should we do destroy James of one okay who see this is our waste pimple This style of ours will start listening to the heavy weapon list that the one with the name 'Zahr Naav Chahiye' that the one with the name 'Zahr Naav Chahiye' that the one with the name 'Zahr Naav Chahiye' did 28 in this two time interval and presented it here and the address's watch plus is okay JK Rowling imitating two to friend WhatsApp to WhatsApp If you took two three, then set the second spy pipe as your friend, you made its value six backward, then the name is African test and you completed it and set the vestige seven plus two 9 nine vehicles and filled the index with cement and I am like the one from Play Store. If it is for, now it will go back after, then we will come back and paint on the walls, I have come Mishra, this is done to us, our jo jaaye reset-1, us, our jo jaaye reset-1, us, our jo jaaye reset-1, our relationship will break at zero, and where did this of ours start, ICICI Back to Tujhe Ko Shampoo It starts from like cost to 13 then the number is 138 3G alum and after that Idea is ok at 2128 after that in the evening did you change the job dress and you set the press release 1017 and how much did the value of idiots become You are right even now, if we see that the efforts have already been made then it will not work quietly, otherwise we will fry the potatoes and leave the vegetables behind, active high cost reduction in this is requested Srila, where did the volume like this come from It will start from I but if you understand the volume then it is okay but now what will we do from the evidence Request name is the weakest to whom the dowry is set on this we set it here and value of its index is tank then the potato will go Excellent high that if she complains is okay And I have come to those who have come, now there will be bake to injured in treatment, so if I could outline, that is, I want my complete Gurjar song, that is the previous one, when I have decided that I have lagged behind, what should I do, I will start it, I will sort it. And I will submit the range from left to right, let me see how we will do arrange dot solid in the evening we got rid and Jai Hind I request to left - 110 Jai Hind I request to left - 110 Jai Hind I request to left - 110 why close loop that tweet keep it according to dating IS ALWAYS THINK WAY TO RIGHT - If you take the compound then what will you do with your - If you take the compound then what will you do with your - If you take the compound then what will you do with your placid and eye lashes behind it? There is an answer na Kabir Nagar which Mishra will add it from the districts and answer plus request you fennel my last will add it later in the day Junaid hai that serial remind me to see that Congress leaders are making something on our border committee and some romantic Tiwari must have been there because you can know that is why it is plus to this will take [ plus to this will take [ plus to this will take Gaant is a request [ Gaant is a request [ Gaant is a request This dynasty's 90th birth anniversary is on the way The Indian is this Value of my note and what will I do always? Answer: Pacific coast to some what will I do always? Answer: Pacific coast to some what will I do always? Answer: Pacific coast to some models. Then it is written like this. Jhaal's answer is equal to two models. Mode on and mode have been greatly influenced by Jhaal's suppressed mode. Research's sirvi seems to be buried below and last Even while leaving, turn off the mode of getting the answer done, let's copy a specific Ajay ko hua tha and kitna hai hua tha jhal, the chances of history are ours to submit this year, we should stop and it is activated and If there is a solution like Roti on Hogi Reduce, then if you like the voice of Vishnu Meena, who is optimized by this, then give it once in the comment and inside this we will talk about its time complexity, then if I see the total, then I have entered the name into a. B Plus is the account from number 122 which gives them the wavelength of this, we have a new everyone which has such rank depth, so I can say that the total fans are crazy about these numbers and they will be left behind in sodium and square law and square stomach. There is no chicken recipe and some other submissions, we can optimize it which will be using mountain, so if you find it below and once again, I will tell you in this video, thank you very much for watching and have. Size video mandated to the spot setting was on
Range Sum of Sorted Subarray Sums
longest-happy-prefix
You are given the array `nums` consisting of `n` positive integers. You computed the sum of all non-empty continuous subarrays from the array and then sorted them in non-decreasing order, creating a new array of `n * (n + 1) / 2` numbers. _Return the sum of the numbers from index_ `left` _to index_ `right` (**indexed from 1**)_, inclusive, in the new array._ Since the answer can be a huge number return it modulo `109 + 7`. **Example 1:** **Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 5 **Output:** 13 **Explanation:** All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. **Example 2:** **Input:** nums = \[1,2,3,4\], n = 4, left = 3, right = 4 **Output:** 6 **Explanation:** The given array is the same as example 1. We have the new array \[1, 2, 3, 3, 4, 5, 6, 7, 9, 10\]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6. **Example 3:** **Input:** nums = \[1,2,3,4\], n = 4, left = 1, right = 10 **Output:** 50 **Constraints:** * `n == nums.length` * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 100` * `1 <= left <= right <= n * (n + 1) / 2`
Use Longest Prefix Suffix (KMP-table) or String Hashing.
String,Rolling Hash,String Matching,Hash Function
Hard
2326
125
hey guys Greg here and let's solve valid pal drum so a phrase is a pal drum if after converting all the uppercase letters into lowercase letters and then you remove all the non-alpha numeric you remove all the non-alpha numeric you remove all the non-alpha numeric characters it's a palindrome if it reads the same forwards and backwards and they give you a simple definition alpha numeric means letters and numbers okay so it's saying that the text might have non-alpha numeric stuff like question non-alpha numeric stuff like question non-alpha numeric stuff like question marks and exclamation marks and whatever so here it actually has some commas in there and the explanation of why this is still a pound from is because if you ignore all this stuff so if you ignore the commas and the spaces if you just look at the letters and the numbers if there were any then it's amap and so on forwards and it's amap backwards so it's going all the way it's the same forwards and backwards and we're also saying that if it has uppercase letters just convert those to lowercase letters first so that actually is a pal drum so we return true for race a car will we remove the spaces and so it's just race a car that is not a pal androme there's saying it cuz it's funny because race car without the a race car is a paland Drome but race a car is not now the best way to do this is a two-pointer approach where we have a two-pointer approach where we have a two-pointer approach where we have a pointer L at the left and another pointer r at the end and people are going to be annoyed when I call this two pointers because I know like they're more so indices it's just this is the index zero and this is the index n minus one where n is the length of the string and sure they're not really pointers but like variables are basically pointers so we're just going to avoid that conversation it's we're going to call this a two-pointer technique cuz that's this a two-pointer technique cuz that's this a two-pointer technique cuz that's what it's called now at every single step we want to make sure we're looking at a lowercase English letter and both of them are and so since they are both looking at one well are they equal to each other if they're not equal to each other then we could immediately return false except they are equal to each other okay what does that mean well we need to keep scanning this forward so we will move L over one and we will move R over one towards each other now we do the same thing we make sure they looking at a lowercase English letter this is this sort of is it's an uppercase English letter we'd first kind of make a copy of this and actually just look at the character of a and so now they're both looking at lowercase English letters are they equal to each other yes they are so we need to keep this moving forward L is going to move over and R is going to move over now again are they looking at lowercase English letters or a number by the way numbers are fine too uh no it's not here okay so basically we found that L was looking at a non-alpha found that L was looking at a non-alpha found that L was looking at a non-alpha numeric character and so we're actually going to just move L over and we're not going to touch R because we just had an issue with L and so we'll just move L forward okay now they're both looking at letters but we just need to make a lowercase version of this we say are they the same yes they are they're the same as each other so we will move them forward okay same thing's going to happen here with L we find that we don't like what it's looking at so we're only going to move L forward now they are both equal to each other and it's actually at this point where we can immediately without even checking the spot we can immediately return true at this point so we can immediately return true if we've gotten this far that means it reads the same forwards as it does backwards and then there's just one other letter here now what you could do if you wanted is just to make sure that like these are still the same character like you could say like is r equal to l yes it is of course because they're the same letter well you don't really need to do that we can make the Y Loop condition here just while R is less than L okay we don't need to include the equals to because that's this case here we don't really care we always know that when they're equal to each other of course they're going to be the same thing and so that's not going to matter okay now this is going to yield a big o of n solution okay we're really just moving one pointer L over to the right and we're moving another pointer R over to the left and so that's basically just going through two times and so we have o of N and the space complexity of this is actually a constant solution okay so time is O of n but space is Big O of one because we're not storing anything other than these two you know pointers or indices okay so we're going to start by getting n is the length of the string and we'll initialize our two pointers we'll get L is going to be zero the first position and R will be nus1 that's the last position so then we can just do as we said while L is less than R if not s at L do is alum if the character at L is not alpha numeric as we said we just want to move on and so we'll do L plus equal 1 and we'll immediately continue okay we don't want to worry about R here if L had an issue we're just going to move L over now same thing for R this is just going to be a copy paste if we don't like what R is looking at then we are going to just move our down one okay so we will move them closer to each other if either of them ran into an issue now at this point we know that they're both looking at alpha numeric characters and so we're going to just check if s at l. lower okay that's going to convert it to lowercase that is not equal to S at r. lower then we can immediately return false okay so we know they're looking at either a number or a letter and if it's a number lower actually works on that as well the string of five. lower is still just five so we're checking if they are equal to each other if they are not equal to each other we can immediately return false cuz it did not read the same forwards as it did backwards now if they were equal to each other then we will be over here and so we will just move L over one and we will move R down one at the exact same time if we get outside of this Loop we must be happy with our result and so it we return true let me just zoom out a second so you can see the code on one screen sorry just to typo I put a lowercase L right there and that is our solution so as we said the time complexity of this algorithm is going to be Big O of N and the space complexity is going to be Big O of one okay we're not storing anything other than l r and N here all right I hope that was helpful drop a like if it was and have a great day guys bye-bye
Valid Palindrome
valid-palindrome
A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_. **Example 1:** **Input:** s = "A man, a plan, a canal: Panama " **Output:** true **Explanation:** "amanaplanacanalpanama " is a palindrome. **Example 2:** **Input:** s = "race a car " **Output:** false **Explanation:** "raceacar " is not a palindrome. **Example 3:** **Input:** s = " " **Output:** true **Explanation:** s is an empty string " " after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome. **Constraints:** * `1 <= s.length <= 2 * 105` * `s` consists only of printable ASCII characters.
null
Two Pointers,String
Easy
234,680,2130,2231
377
hello and welcome to another video today we're going to be working on combination sum 4. in this problem you're given an array of distinct integers in a Target and you want to return the number of possible combinations that add up to the Target test cases are generated so the answer can fit in a 32-bit integer so for this can fit in a 32-bit integer so for this can fit in a 32-bit integer so for this example one two three Target is 4 output is seven because we can have one on one and one two one three two and one two and three so the first combination sum you didn't want to count combinations multiple times right so one two and one two one were counted as one combination but now we want it kind of like the ordered matters and so we can have the same we can have different sequences of the same numbers and they want to count as the same combination so the way we're going to want to do that is pretty straightforward we're going to want to do this just like the first one except now when we pick a number so let's say we like pick this number in our new Target is let's say we like choose to pick number two and our new Target is two now we can pick any number again as opposed to before where we said like okay let's just maybe like sort these or something and then if we pick one we can either pick one again or we can pick something higher but when we pick two we can't pick one again because we don't want to go back right so if you don't want to go back you don't want to have something like one two and two on one but now we do so actually at every single iteration we're gonna have to try every single number right we don't want to keep track of like what we used and what we didn't we're actually going to try every single number so what that's going to look like essentially is something like this so let's say our Target is four we can actually draw this out and draw out all these combinations so let's give us some more space and we are going to obviously Implement caching but let's say our Target's four and we have numbers one two three and I'm just gonna say that for anything that gives us a negative term number we're not going to include because that'll be some base case for us like you know if the number makes I guess we can actually handle that in the actual minimization itself we can just say like okay look if the number is um you know if the number that we're subtracting for the Target makes our solution negative let's just not even do that so let's figure out essentially how we would do that right so let's just go through this so essentially we have Target four we can pick any one of these so let's just say we pick one now our new Target is three but also we can pick two so our new Target would be two and we can pick three and our new Target would be one now when we have three we want to do the same thing we can pick one our new Target is two we can take two our new Target is one and we can pick three and our new chart is zero and this is a solution so now we actually have a solution right that's one of them so now let's go through this so we can pick one where our new I might run out of space here but we'll see our new Target is one we don't even need to really write which number we picked we just need some more count like how many of these paths lead to zero so we can pick one our new Target is one we can pick two our new Target is zero that's also a solution and we can't pick three because then we'd be at a negative Target okay now for this one we can only pick one so we would just pick one and our new Target would be zero we're not I'm not going to write down what I'm picking I'm just gonna write down our targets and then we just count these number of zeros right actually a little bit clearer so this is a one because we picked one or the two okay now for this two we can pick one then our new Target will be one we can pick two under Target will be zero and we can't pick three then for this one we will just pick one enter your target will be zero for this one we will pick one energy Target will be zero and for this one we'll pick one energy chart equals zero so you can just count out like how many different ways you got to the zero so we have one two three four five six seven and hopefully that's correct so that is correct we have seven Solutions and we don't really care like what numbers we use we're just counting combinations so essentially all we're doing is it's pretty straightforward right we have some Target we try to subtract every number in the array of nums then if our new Target is negative that's invalid right so that's going to be like zero or we can just check for that beforehand right like if our new Target is negative we'll just not recurse there otherwise recurse with new Target until Target equals zero and then once the target is zero that is like our base case so for a DP solution let's go through it so for DP we need three things right we need state to base case and three recursive so for the state we're just going to have the target we don't really care about what index we are on because we're going to try the whole array right so we don't really care okay now for the base case Target equals zero that means we return one right because that's like a solution obviously if Target is less than zero if we somehow have that let's return zero we could do that as well and then finally we can use a little bit of tricks to end early so let's say we have like one two three but our numbers aren't guaranteed to be sorted and the time complexity of this solution is going to be uh N squared so we can actually sort our numbers so we can end early so let's say we have some numbers we'll just sort them so we'll just say they'll always be sorted then what we can say is we can have a few more base cases here right we actually technically let me think yeah I don't think we need we don't need all of our base cases yeah I don't think we need like all of our things but this is going to help for our recursive okay so Target is less than zero we're going to return zero fine now what about the recursive case so the recursive case is literally and this is where the Sorting will help Loop through numbers subtract Target or after subtract number from Target to get a new Target right so if our Target here is like four we would subtract one and so on we get a new Target then we can just to make it more optimal then if new Target is negative we can break the loop otherwise keep going and I'll explain that in a second so let's say our numbers are one two five six and our Target is four so we would subtract like one from the Target and we would get three which is fine right that's fine for new Target we'd subtract two from the target we'd get two totally fine but now we subtract five and we get negative one that means that like five can be in our solution and because we sorted anything past five also can't be our standard Solutions that's what sorting is kind of nice because essentially in hdp we will have to Loop through the whole thing but as soon as one number is invalid as soon as one number is bigger than the target then the whole rest of the arrays and valid so we can save some time there but that's pretty much it so we just have a state we have a base case where the target is zero we return one target is negative then we have an invalid solution then we have this recursive thing where we Loop through every single number and we subtract it from the number and keep going until we either leave through the whole thing or Target is negative and then for each one of those we will just add so we will do like a result plus equals DP of using that number right so you add up all of these states together so let's say we had one two three four we would say okay well if our Target is four let's say we had States one two three so let's get rid of it actually so we have this and our Target is four then we would say like okay our result is something it's going to be result plus equals DP of 4 minus 1 and then plus equals uh DP of 4 minus two and so on right every possible new state you just add to the result then finally you cash in your return so also yeah in a base case you need caching as always but that's pretty much it so it's pretty straightforward all we do is we just Loop through all of our numbers and we just keep trying them all and for anything that works we add it to the result now we can code so we are going to sort like I said because it does help to make it faster we're going to have a visited and then we're gonna have a DP that takes in a Target and so if Target zero let's return one actually know if Target can be negative let me think about this I don't think it can be yeah because we're just going to check for that before but you can also check uh yeah we're gonna check out that before to end our Loop prematurely so I don't think our Target can ever be negative because we can check for that before but we're gonna see if we have an error so we also have to check for visited so if Target and visited let's return visited okay now we are going to do our Loop so we're gonna make the results equal to zero and we're just going to say four number in numbers if the target is less than the number meaning Target minus the number will be negative let's just break because that's never going to be a valve solution so that's why you don't have to check for negative Target because we're just going to be checking here which will allow us to under Loop prematurely and it'll save us a lot of time then we just do res plus equals p Target number finally we cache it and then we need to just return DP using the original Target here okay let's see what happens I don't think we can get negative so I think this should be fine yeah so you can see it's pretty efficient runs all over the place kinda I think most solutions are kind of similar so you can see it's kind of inconsistent as far as the results but pretty good so let's think about the time and space here so obviously for the Sorting that's already n log n but it's not going to matter because this target can be up to a thousand right so if it can be up to a thousand this is going to be Target here but it's also going to be times the length of mountains right so if you think about it for an N log n solution quote unquote like sorting this is going to be n log n which this is like the end part right so basically we're saying this is better than or yeah sorting is basically free as long as Target is greater than log of 200 right and yeah and log of 200 is like exactly but you know somewhere around 10. so as long as the target is greater than 10 this is better and once the target gets small enough this is basically the linear time anyway so the store is going to take longer than the um yeah the sword is gonna start sword is gonna take less time than this part for unless it's for a very small number in which case it doesn't really matter because either way it will be fast so you if you wanted to you could get rid of this sort and you could uh could get rid of the sore and you could get rid of the break and then you could say if Target is less than zero return zero this should also technically work I believe it will just theoretically be slower yeah it is a little bit better the other way or you know a decent amount better usually so and there we go okay so that's going to be roughly this you can if you want to you can say like well you know maybe the sort might take longer so you could say like Plus on login if you want to which would make some sense but yeah so assuming your target is bigger than the login which it almost always is it's going to be faster that way okay and for the space so what do we have here um so we have this visited and visited can have any number up to Target so the space is just going to be oh of Target oh yeah and I think uh that's actually gonna be for this problem so not too bad and then they asked what if negative numbers are allowed how does this change a problem what limitations do we need to add so actually I believe with the Sorting I think it is just fine I want to say like we can test some stuff but I want to say it would just work for anything because we're kind of doing the same thing as long as we sort I think it would be totally fine and it would work right there you could test it on your own if you wanted to I'm not going to do this video but yeah it's gonna be it for this one uh and uh if you like this video please like it and subscribe Channel for a lot so I'll see you in the next one thanks for watching
Combination Sum IV
combination-sum-iv
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`. The test cases are generated so that the answer can fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\], target = 4 **Output:** 7 **Explanation:** The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. **Example 2:** **Input:** nums = \[9\], target = 3 **Output:** 0 **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 1000` * All the elements of `nums` are **unique**. * `1 <= target <= 1000` **Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
null
Array,Dynamic Programming
Medium
39
399
hey yo how's it going guys babybear4812 here coming at you one more time today with uh what i think is a tricky problem actually the problem is evaluate division problem number 399 only code it's tagged as medium uh i really think this one should be tagged hard but i don't make the rules uh so it's currently being asked by amazon google facebook bloomberg and microsoft uh you've heard of some of those companies and i think what makes it tricky in part at least um is because i think that it's a bit deceiving in the sense that it puts those of you with the uh who are mathematically inclined at a slight disadvantage i think usually an advantage but this time around i think it makes it a bit trickier because of where your kind of head goes or may go by default so let's uh let's take a look at the question then we'll dive into the solution so it says we're given equations in the form a over b equals k where a and b are variables represented as strings k is a real number and it's a floating point number okay given some queries return the answers if the answer does not exist return negative 1.0 negative 1.0 negative 1.0 they do tell us the input is always valid we can assume that our value we're evaluating queries uh with no division by zero no contradiction none of that stuff so we don't need to worry about error checking and all that um i think this would get a bit messier if we needed to so we don't really need to worry about that here so uh we're given equations values queries and obviously the expected uh result so uh what i've actually done is i've copied it over here because i think it's a bit easier to look at this way um and let's kind of take a quick walk through of what the you know how to understand the input and then ultimately what we want is output and afterwards you know how we're going to get there so first thing we're given is uh i wrote as an e for equation so we're told we've got these two equations a divided by or they're not equations yet but statements you know a this represents a divided by b this represents b divided by c the equation would be along with this values array you're given is a divided by b equals two b divided by c equals three okay or 2.0 3.0 equals three okay or 2.0 3.0 equals three okay or 2.0 3.0 these are the queries that are going to be running as input okay so in this specific example what we need to do is to say let's evaluate what would a divided by cv a divided by c turns out to be six so we expect the output to be six b divided by a we expect to be 0.5 b divided by a we expect to be 0.5 b divided by a we expect to be 0.5 so on and so forth we return everything in this result okay over here so the reason i think this may put some of you mathematically inclined folks uh at a disadvantage is because your head may originally go kind of like minded to like oh this looks like linear algebra so it's like well i've got you know if i know that a over b is two and b over c here maybe just algebra not even linear algebra per se um b over c is three well i can kind of you know maybe try to move variables around set the equations equal somehow and then maybe you realize that you know a or b times b over c is just you know those cancel out so you get a over c equals six it's like okay cool so like you're picturing these systems of equations in your head and um and so you're picturing these equations in your head and figuring out how to work those out mathematically and if you try to take that approach i think you'll be sitting here and kind of scratching your head for a while um and that's why i think that this one is tough and not obvious because it's easy for your head to go here keeping in mind the context that we have given you know we're on lead code you're preparing for your tech interview we need to think about what we're going to do um in terms of like do there exist data structures that can kind of help us out here okay and so keep that in the back of your mind as we kind of walk through i just want to look at a few cases of this output first so we get a real holistic understanding then we'll jump back to this point on what we need to do with data structures here all right so like i said it you know a over c is six okay we kind of mathematically put that together here b divided by a well we have a divided by b which we know is 2.0 that's a very ugly two that know is 2.0 that's a very ugly two that know is 2.0 that's a very ugly two that looks like a one all the way 2.0 um all the way 2.0 um all the way 2.0 um we so b over a must be reciprocal half it's like okay fine simple enough then we get ae well we realize like e is not really in there and so we're returning negative one here because as for instructions it said uh we return negative 1.0 if the answer does not negative 1.0 if the answer does not negative 1.0 if the answer does not exist so we're like okay so this is one scenario maybe i'll kind of put a star here so we got regular division that's one scenario uh division with an unknown variable like we didn't have an e in here so we're just gonna return negative one when we see a variable there so you might start to think like okay maybe i've got a i've got to keep these variables for maybe like a set or a hash table uh that'll tell me all the different letters or variables that i come across and um and then you know if i see one that i don't like i'll just spit out negative one no matter what a divided by a so number divided by itself is 1.0 a so number divided by itself is 1.0 a so number divided by itself is 1.0 it's like all right cool that's easy enough so maybe we put a star there um and then we get x and x we're returning negative 1 here even though we kind of know that any number divided by itself barring 0 of course will give us 1 but because x is unknown in the context of the variables we're given here we will return negative 1. so it looks like three things are two things three things are happening here one thing that's happening is when we've got you know one scenario is if we say uh the numbers aren't even in the set so first we have of check the numbers in b and be like well if number uh not in set okay that's easy we return negative one um otherwise i think the really simple case is a number divided by itself so maybe i'll say you know uh shorthand a divided by a we have something like that we can return one and when i say return i mean i just add it to this uh this results array here and then the third one which is really where the bulk of the work is actually going to be you know regular division and this is where we're going to make our money that is extremely ugly writing put a question mark here for now so like i said regular division this is where things just get weird so again this linear algebra approach ain't gonna help all so much so we think ourselves and especially when you're looking at this kind of cross multiplication here it kind of looks like well you know if i know what a over b is and i know what b over c is there a way for me to get from a directly to c this is what kind of did it for me when i tried to do this and i noticed the cross multiplication that these items cancel each other out it was like well i can get to a or i can get from a to c via b potentially and i think that's kind of the key in kind of recognizing that in fact we may need some sort of like a graph structure to order this question and this is like i think that's the crux of the problem is it's i don't think it's obvious at least it definitely wasn't to me um that like a standard evaluate division problem we would actually solve with the graph so let's think about that for a second you know if i'm going to keep using this example i've got a b c or 2 and 3. if i've got let's say i got a if i try to turn that into a graph i have a so if i think about a divided by b well you said that was going to give us 2.0 okay cool 2.0 okay cool 2.0 okay cool and we know b divided by c is 3.0 right and what did we say a is 3.0 right and what did we say a is 3.0 right and what did we say a divided by c was well a divided by c when it was 6.0 and so it a divided by c when it was 6.0 and so it a divided by c when it was 6.0 and so it actually it turns out if you kind of follow this logic that if we multiply every value along the way from start to finish we get the value of that division that we want and i think that's pretty damn cool like again i don't think that's intuitive at all uh it wasn't for me like i said i'm sure there's at least one person watching who like it wasn't intuitive for them either but that's the key here to solving this problem excuse me again the interesting thing is that we can actually also notice that let's reverse this relationship so i can go b divided by a and all that will be is the reciprocal of this value so this will be 0.5 so this will be 0.5 so this will be 0.5 and this one c divided by b will give me uh right 1 over 3 which would be zero point uh three i'll leave it at zero point three right which is the float so all of a sudden i can do a divided by b a over c e over a b over c over a c over b i can do all three of these once i set them up in this graph structure and so that is like understanding this and getting to here is a large chunk of the work the coding is a bit involved as well i'll be honest so maybe this might be a bit of a longer video probably in around the 20 minute mark or so but yeah this is like this is what we need to get we need to understand that there are three different scenarios that we deal with and that we can actually represent these not the queries but the equations and the values that we're given in the context of a i guess bi-directed graph in a way of a i guess bi-directed graph in a way of a i guess bi-directed graph in a way so yeah the um the way we're going to want to think about setting this up by the way you can pause the video if you want to think about how you would set this graph up um i'd like to be an adjacency list i think those are the most intuitive and maybe we can do something like this as we're adding items in we can kind of say well um i have a here and what do i want my value to be well you know age is just pointing to b right now but there's no reason why there couldn't be another variable d in here and you know maybe we're given what a divided by d is and so it could have many more um many more other kind of neighbors so typically we put that in an array of source right the issue is if we want to actually triggers through all of these and while we're traversing to know the value of the division at every step which is what we need then i would argue we actually need to put one more nested object in here so here we have a is connected to b and then a b 2.0 would be the value b 2.0 would be the value b 2.0 would be the value okay my next one that i would have would be something like you know this is how do i there uh then we've got b so from b we can actually go to two places we can go to a which will give us 0.5 or which will give us 0.5 or which will give us 0.5 or you can go to c which will give us 3.0 you can go to c which will give us 3.0 you can go to c which will give us 3.0 right b divided by c was three so that's the b value entry and then i think you get it for c which we're gonna go to b n and uh yeah equals to c goes to b so when we're adding these in with every kind of a equation value that we visit we also gotta add its reciprocal and so we can jump in any direction all right so that's what we're gonna do we're going to build this graph we're going to set ourselves up through these three scenarios and then we're going to think about when we actually need to do the division well actually we're not going to think but we kind of went through it we realized that to do this division we're going to have to do some graph reversing the solution i'm going to implement is dfs so i believe you can implement the same thing with uh with bfs i just find efs a touch more intuitive all right so what we're going to end up doing here is we're going to call some sort of a recursive helper function to do a dfs for us to see if we can actually get to where we want to get so uh at this point i've talked long enough i'm sure you're sick of me already let's uh let's jump into the code and see what we can make happen there so i'll move this over and give ourselves plenty of space here a couple things we want to do one was we wanted to say make graph and then two was do calculations all right so um i'm not going to do any error checking here because we were told the input would be valid and all that so we're kind of safe there so the graph we said that we wanted was there's just going to be a dictionary and i know there's a way to do this with i think like default uh dictionaries and maybe grouping by using the zip functions let's make this a slightly bit less verbose but i'm going to stick with the first principles here and really build it out from scratch okay um so what we want to do is this is we want to start by going through all the equations um in uh in order to the equations and the values excuse me so we can see um so we can see like who the what the neighbors are the neighbors really like where the division is happening with the values of that division so what i'm going to do is this is i'm going to say so typically what i want to do you know in equations comes in this nested array format so what i could do is something like i'll call them num and then for numerator and denominator uh in equations okay except i also want the values as well so i again i think you can definitely zip these like the equations and the values together but what i think i'm going to do is i'm actually going to track the index with i and i'm going to have to put these in parentheses so then we can actually uh enumerate through equations what this allows to do is basically say look at the index i'm in for each equation so i can find the corresponding value and then get the numerator and denominator as well which kind of come in this one package here so what i want to say is this is if my numerator is not in my graph then what i want to do is i want to say graph numerator is going to be some empty object for now then or if it's already in there we can say that graph the numerator is going to have so this is now referring to an object right that object we want to have a key of denominator and the value that we want there is the actual value of the division so what we'll do is we'll say equals values at i right and so the other thing that we want to do also is to do the other way around now so we're doing numerator denominator and then we're going to do denominator over numerator so we'll say if denominator not a graph then graph the denominator is also going to be some empty object and finally um graph denominator at numerator now again pointing the other way around uh will be oops will be equal to 1 divided by values of i so just the reciprocal and that's all we need to do that's going to be the adjacency list for our excuse me for our graph uh again points both ways and actually tells us what the values of the division is now here's the second part was to actually do calculations okay so we're going to need to have some sort of i'll call it a result right and i'm super creative uh we're going to return the result after we walk through well all these queries so the queries are basically as follows we are going to want to say uh for maybe i'll call the numerator and denominator again in queries right so queries is also a yep it's a nested array so we can say for numerator and denominator in queries all right and so here we said there were three scenarios and the first scenario we had just double check uh so if the number is not in a set if we're dividing a number by itself or regular division so we can say uh if num not in graph or then not in graph then what we want is to resolve that append a float of negative one or a negative 1.0 one or a negative 1.0 one or a negative 1.0 otherwise we said if the numerator equals the denominator then result not append one okay if only the question was this easy but we got to do that last part else what we're going to want to do is we're going to you know basically result that append um the result of a dfs call so self.dfs um the result of a dfs call so self.dfs um the result of a dfs call so self.dfs and we'll figure out what the heck we want to pass into there eventually this will run through all the queries and we will spit out the final result so to actually make this dfs graph we're gonna have to push in a couple things one is going to be the graph i'm sorry i said dfs graph dfs traversal of a graph first thing we're going to put in is the graph itself we're going to want the numerator and the denominator which will kind of act as our starting and ending point we're going to want to keep a product going because we said as we jump from one end to the next we need to multiply by whatever the result of the division is uh so i'll keep that as one for now and we're going to keep it out of one so once we start multiplying things they're not there's no kind of value that's already altering the modification finally the last thing i'm going to pass in is actually going to be a visited uh set or array so i'll create a new set here and we'll use that just to keep track of the nodes we've already visited so we don't end up getting in cycles during our dfs so this is actually it apart from obviously this helper function which we're going to write now this is the bulk and the entirety of what's going to go into this main calc equation method so now for the actual implementation here the first thing we're going to want to do is to say let's take our visited set and add to it the numerator or maybe our starting point maybe i'll call this start and end i feel like that might be a bit more intuitive um once we do that we also want to say let me um let me think let me get all my neighbors from this actual point so i want to get all right so let's get this thing implemented first thing we want to do is to take the visited set and add to it the starting point and with that starting point we want to get its neighbors as well so we can say something like neighbors equals um this will be uh excuse me graph of start all right and then we've actually got um what i'm going to do is i'm actually going to set an answer variable i'll set that answer variable to the negative one by default and we're eventually going to return it because what we want to do is to basically do our dfs and search through all the different possible paths if we don't ever end up finding and doing any multiplication that we need this answer is going to stay as negative 1 so that's what we're going to return otherwise we're going to return the answer itself so we'll modify that variable in just a few steps really what we want to ask ourselves first is whether or not the point that we want to get to this end is in our neighbor set right now or in our neighbor object so if the end is in neighbors then all that we want to do is we want to see that the answer is going to equal to the product we have so far times like the value to get to this end here so times i guess it would be neighbors end all right that's it otherwise so we wouldn't get into this if this was the case we wouldn't get into this else statement we would jump and return the answer otherwise we're now essentially going to need to loop through all of the neighbors and check each one of them individually now the neighbors uh exist within an object themselves because graph of star rate is another object so what we can do is we can say for a neighbor and value in and we'll do neighbors dot items so this is actually going to return a nested array of key value pairs from this object and what we're going to say is this if there's a neighbor that we haven't visited yet go visit it okay so if uh neighbor not in visited then we want to go visit it in particular we are curious like we're curious in knowing what the answer is going to be after we visit it once we do this multiplication as we go so i'm going to say that the answer is going to equal self d of s and we're passing in the graph the neighbor is our new starting point the end point is still the same uh the product we're going to keep and we're going to multiply it by the current value that we're at right now okay so we can take that value into the count and then keep going and finally be visited okay now we do all this work once we jump out of here we want to know did we actually find an answer or not well we found an answer if we're no longer a negative one here right so if answer is not equal to negative one then we're like oh or float of negative one like oh sweet like i found an answer i don't want to keep checking any more neighbors like i got to where i needed to go so i'm gonna break once i break that'll take me out here we're going to return our answer and everybody's happy and that's it guys i want to leave like the code here so you can see the whole thing in one screenshot let me run it first and just make sure i didn't make any silly mistakes but i think we'll be good that should work i'm gonna submit it there we go 98.82 um yeah 98.82 um yeah 98.82 um yeah so just a quick recap what we did was we essentially noticed that this is a problem that we need to answer using graphs and i hope the intuition we kind of built up there helped convince you of that then we had to make the graph itself we had to do the calculations there were three different kind of conditions for combinations that we had to do and finally to do that last one we had to do it by doing a dfs through the graph that we created so this was our quick little dfs that we put together uh i know this was a long video i think it was a problem that deserves a long video because i don't think it's intuitive at all so i hope you guys enjoyed it i hope you guys found it useful if you did you know what to do you know what to click you know who to share with um yeah and if not or you know if you have any other comments questions suggestions drop them down below as always i'm happy to address them and i will see you guys next time peace
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
452
hey everybody this is Larry this is day 18 of the leco d challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's F and uh yeah if you're celebrating it or maybe I'm a little bit late anyway happy St Patrick's Day uh New York it's apparently a big thing chaos everywhere but um all right let's take a look at today's form 452 hope everyone had a good weekend and hope everyone's uh you know upcoming week is as good as I don't know it's just good I guess but yeah uh let's take a look not going to lie if I wub my eyes a lot my apologies I'm having um it's spring is here so or more or less I guess so I'm just having allergy stuff and yeah I may sneeze a lot during the video apologies ahead of time but yeah let's take a look 452 minimum number of arrows to burst balloons there spal balloons taped to fat worldall that at represent XY point the balloons represent the 2D aray X start y start or sorry X start xn Den know a balloon CR horizontal diameter stretch from X to xn horizontal diameter okay yeah you do not know the exact Y coordinates of the balloon I always going be shot positive uh vertically in a positive y direction from different points on X a b x okay so it's not really a 2d thing I mean you could think of as 2D but okay so then you have 10 to 16 so this is kind of the same idea that we've been playing with the last couple of days with Intero so basically what is the actual question right so you have these points minimum number of hours that must be shot to burst all balloons oh that's a fun one um so you may be tempted uh the reason why I'm kind of just pausing is a little is because this is actually kind of trickier than um you may imagine it to be maybe not I don't know but the idea here is that uh first of all greedy doesn't work right you can probably construct some stuff where um or like yeah GRE doesn't work right because you can struct like a lot of balloons on the left side a lot of balloons on the right side they're tied together by one balloon if you I don't know or something like this right where um if you try to do it you know it'll be well m maybe I say that in the wrong way um I think greedy does work or there is a greedy solution but I just mean like you have to really um the first naive greedy doesn't work in fact I guess greedy does work right basically um but it's not a at least for me it's not an obvious thing though this is a medium so maybe is obvious it's just that Larry's a little bit slow today uh so slow that I'm referring to myself in the third person apparently say we're scanning from left to right in a number line a 1D number line and basically you scan from left to right well when you think about it when would you shoot the balloon you would always shoot the balloon at the last point that you can if it's not already popped right and what I mean by that is that um yeah because if you because you scan from left to right and you don't shoot that balloon at the last point that you can shoot it in a greedy lazy like you call lazy and that you want to just like shoot that as late as possible um and because if you don't shoot it at the latest then it then um whatam call it well then you just miss the balloon you have to shoot that balloon no matter what right so I guess you're in that way it's like a forc greedy um and the thing the kind of um that's pretty much the idea really um the only thing that you might have to kind of think about is that um is that you know when you shoot you may hit multiple balloons and that's basically the idea all right let's kind of play around with that idea then and then let's get to it I don't know if I'm getting an I don't know if I'm explaining quite better maybe I could draw it out but I don't even think drawing out really matters but I guess I'll draw it out because I think there are a couple of cases that is in my head that I think I'm just not saying out loud explicitly um cuz I think I see the edge cases but it's just that or not even edge cases cuz it's not it does I don't think it affects the problem or least my solution implementation but I think I'm not articulating it that part well right uh all right let's just PL in oh there you go I was holding my pencil backwards and I was like why is this not drawing well uh maybe I am slow today but yeah you have a number line and let's just say you have a selection of balloons and I just per of balloons by some intervals right and what I'm saying here is that you always only care about the right end points right well in terms of shooting so there other you have to care about the left end points by other reasons but yeah you only care about the right and points by shooting right and the reason is because um if you're going from left to right if you don't shoot it at this point there's no other time to shoot it for this balloon right and kind but of course you know if uh if you care about this one for example um you know you might not need to shoot this one because by shooting this one's also popped right so that's basically the idea and then there's some like you know uh thing so in a way you're kind of forced to shoot at that time and yeah still not sure I explained it that well but we'll play around the code so then for XY in points what do we want to sort goodbye uh we actually want to sort this right cuz the input is just in random order I'm trying to think whether we care like we sorting I guess we only care about the right end point right because that's the only end point that we are um that we are actually shooting the balloons and then the left side will come into play anyway because um the left side will come in play anyway because um because left is before the right side sorry I'm trying to think through some scenarios I don't know that I want to implement it this way actually so I'm going to take it back uh some stuff but yeah but basically the way that I want to do it is just separate out the start and the end so that maybe I have like four index uh XY and in well I guess just start and then in no need to confuse more and points right and I'm just going to have some defense right and maybe I would have two type of Defense one is the beginning and one is the end right so we'll do um uh the x axis right uh the start and maybe we have two like I said two right yeah and maybe the index so that we keep track of which one we care about right and then the same idea uh for the end and then now we can sort it and then now we can just pause the events right um yeah for X the type and the index in events uh and maybe we have um uh we keep track of which one we already burst right first it I don't know or shot I don't know Force time n right and then we also have maybe a current is a set of end points that we care about and then here we go okay so if T is equal to start then we care then we want to set current is we add index to it and that's pretty much it I think we don't even have to care about X I don't think right and by definition it is not bursted but then now uh else which is T is equal to n of course there's only two scenarios then now shoot up well first of all we want to make sure that it is not bursted so if not if bursted oops it burst of index then we just continue you know we already shot it there's no reason to need to shoot it and then after else um we want to shoot right and what happens when we shoot well when we shoot we get rid of everything in set that's basically the idea so for uh for I don't know for C and current oops uh we want that first of C is true because that means that you know when we shoot we shot everything also I have to keep track of the number of shots I forgot uh and here we shoot right so we shot once we burst all the balloons by sing them to burst and I think that should be good um there is a Nuance here that I didn't really talk about which is that what happens when it's tiebreaker right meaning that um the S point and so basically if you have one into here let me make sure that at the beginning and end points then what happens well you just have to think through what happens right which is that when you shoot straight up at the endide um you want to catch the I think so anyway unless I'm just reading this wrong um then you also want to catch the beginning of the next one so in that case you want the starts to go before the end so that when you go by the time you get to the end all the tiebreaker stuff would have burst and you would have gotten good right that's one way to do it and yeah so that's want it real quick uh I think an old gr I have to use click on use example tou I we got uh hopefully this is right what all these like running time is so weird all over the place but uh I'm just going to take a look real quick this is pretty much this is actually exactly what I did except for now what is the faster way that I did H oh I am dumb uh I guess I did the same I did the last time uh I meant to do it or I meant to fix it but I forgot which is that we have to um reset the set right all right because that is actually pretty bad that messes up the complexity a lot uh and also as you can see it doesn't have to be a set it could be an array because we just go through it anyway but uh yeah uh so what's the complexity here right so this is n o of n but this is going to be n log again so yeah so after that everything is all of n all of end Loop all of One stuff and yeah so this is n log and dominated by the event sword um yeah I think that's all I have for this one to be honest yeah um the idea is just kind of like playing with intervals and stuff like that I think you know it's something adward k a lot um definitely get familiar with it uh we don't have a premium problem which I'm going to do an extra problem after this so stay tuned hit the Subscribe buttton leave a comment for support and yeah that's all I have for today have a great weekend if you if I will see you soon uh or weekend have a great week I don't see you soon but stay good stay healthy to your mental health uh let me know what you think about this Farm in the comments uh join in Discord I'll see yall later and take care byebye
Minimum Number of Arrows to Burst Balloons
minimum-number-of-arrows-to-burst-balloons
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons. Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. **Example 1:** **Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\]. - Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\]. **Example 2:** **Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\] **Output:** 4 **Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. **Example 3:** **Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\]. - Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\]. **Constraints:** * `1 <= points.length <= 105` * `points[i].length == 2` * `-231 <= xstart < xend <= 231 - 1`
null
Array,Greedy,Sorting
Medium
253,435
1,567
hi everyone welcome back so it's quite a tough contest this week and i'm planning to make videos for question two and question three so stay tuned and today let's solve the question uh maximum length of sub array with positive product okay the question statement so given an array on nums we have to find the maximum length of subarray where the product of all the elements in this array is positive so it's pretty straightforward for example one we can see that the product of all the elements in the array is positive so the output will be the length of this array which is four and example two we can take the sub ray one negative 2 and negative 3 and their product will be positive so the output will be 3. and example 3 is either the sub rate negative 1 or negative 2 and negative 3 so the result will be 2. and you can see that the tricky part in this question is that in the array there can be positive and negative numbers or even zeros and there's a very similar question 152 the maximum product sub array but in that question we have to calculate the maximum product of the subarray but in this question is to find the maximum length of the subarray with a positive product but the algorithm we will use are the same which is dynamic programming and it's quite rare that you have to use dp to solve median questions in the contest but basically to use a dp you have to first think of what is the intuition of the dp array and its initial states and the state transition functions and the data structure we will use are two dp arrays which is positive and negative array and the meaning of this array is the length of the longest sub array which ending at the current element num side with positive or negative product now let's look at a code so the first part of the code is to set up the dp initial states so the initial state of the positive and negative array is a rail of zeros and the size is the size of the array nums and you will see later why we initialize both arrays to zero and if the first element in the num's array is positive then we will set positive 0 to 1. otherwise we will set negative 0 to 1. and first initialize the output variable result to the first element in the positive array and next part is the dp state transition equation so go through the array and if the element is bigger than zero then positive i will be equal to one plus a positive i minus one and negative i will be 1 plus a negative i minus 1. if negative i minus 1 is bigger than 0 otherwise uh reset to 0. and if the element is negative then positive i will be 1 plus negative i minus 1 if negative i minus 1 is bigger than 0 otherwise reset to 0 and negative i will be 1 plus positive i minus 1. and finally update the result to the maximum of a result or a positive i and now let's see the code in action and here we are we will look at example 3 because the nums array has all negative positive number and 0 and the output should be 2. and remember the dp array is the length of the longest sub array ending at the current element numpsi with positive or negative product so the first element is a negative so we will set the first element in negative array to one and next element is negative so we will use this equation positive uh i is equal to one plus negative i minus one which means that uh this sub ray negative one and negative two its length is two so we will update a positive array the second element from 0 to 2. and for the negative array we'll update from 0 to 1 using this equation negative i is equal to 1 plus positive i minus 1. and why is that because if you think it's true the dp array is the length of the longest sub ray up to the current element so if the current element is negative and which means that if we only have a negative a sub rate up to this point then the product of the sub rate on its left should be positive so that is why uh it should be one plus positive i minus one and here we also update rest uh from zero to two using the equation here and the next element is negative three so the longest uh positive product sub ray is uh the length is two so update positive array from zero to two and longest uh negative product sub rate is three so here is three and rest still is still two and now we have a zero and you can see that because we initialize the positive and negative array to zero so here uh the element won't be updated it will remain zero and you can think of it like we will reset the length of the sub ray to zero so that is the main reason why we initialize the dp states to 0 at the beginning and finally we have a positive number so we'll update the positive array from zero to one and finally the result is two finally let's review so the main algorithm we use for this question is dynamic programming and the data structures are two dp arrays positive and negative and their meaning is the length of the longest sub array ending at the current element num site with positive or negative product and time complexity linear time space complexity is linear too but if you think it through you will notice that because of a dp array uh every dp value only depends on the previous one so we can actually reduce the space complexity to a constant space using the code here okay and that's all for today thanks for watching if you like this video please give a like subscribe to my channel and i will see you in the next one
Maximum Length of Subarray With Positive Product
maximum-number-of-vowels-in-a-substring-of-given-length
Given an array of integers `nums`, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return _the maximum length of a subarray with positive product_. **Example 1:** **Input:** nums = \[1,-2,-3,4\] **Output:** 4 **Explanation:** The array nums already has a positive product of 24. **Example 2:** **Input:** nums = \[0,1,-2,-3,-4\] **Output:** 3 **Explanation:** The longest subarray with positive product is \[1,-2,-3\] which has a product of 6. Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive. **Example 3:** **Input:** nums = \[-1,-2,-3,0,1\] **Output:** 2 **Explanation:** The longest subarray with positive product is \[-1,-2\] or \[-2,-3\]. **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.
String,Sliding Window
Medium
null
844
hey guys this is Jay so how's everything going in this video I'm going to take another easy problem eight four backspacing string compare we're given two strings as ante return if they're equal when they both are type in the empty text editors hash ming's backspace character know that after backspacing and empty text the text will continue empty so a B back slash C so this will generate AC this the same with eight this so they are true okay so the ABC a be back pack then empty right so this empty also so they are equal this a empty C so it becomes C and this is empty a empty so we still see a so we see this is B so it's not the same well we can just a mimic the real typing right so for the a be back slash back space see first we type a uh-huh and space see first we type a uh-huh and space see first we type a uh-huh and then a week type B okay and then back slap backspace we get a and type C right so we get a C well how could we do it we could just create an array to do this right we could just create a empty array and then look through it and we if we met like backspace we can just pop it like okay first we get a and then B and backspace and really pop and then a B and this AC right and at last we compare if they are equal yeah that's it so the solution would be like we create a youtube function called get result get like get typed okay we get input we use a rate hope t use array to hold the DBT letters A for let factor of input if character if equals to backspace we will just pop right for EVD there is nothing to pop this will just do nothing if now we just wait push capture and then return result enjoy yeah so we could just call this function against two input to check if they are the same right and they should be okay yeah cool so that's it so what's the time and space for time it is you two will actually look through all the characters so the cat ears will be so it's linear time suppose n count of the letters space we use a array to hold the letters the worst case is that there is no backspace and it will cost us just the same s and letters right so cool so that's it pretty easy hobby helps see you next time bye-bye
Backspace String Compare
backspace-string-compare
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t become "ac ". **Example 2:** **Input:** s = "ab## ", t = "c#d# " **Output:** true **Explanation:** Both s and t become " ". **Example 3:** **Input:** s = "a#c ", t = "b " **Output:** false **Explanation:** s becomes "c " while t becomes "b ". **Constraints:** * `1 <= s.length, t.length <= 200` * `s` and `t` only contain lowercase letters and `'#'` characters. **Follow up:** Can you solve it in `O(n)` time and `O(1)` space?
null
null
Easy
null
1,837
welcome guys welcome to my lego summit section so today let's talk about this 1837 sun of dj in base k okay so a given integer array and the base k return sum of digits of and after converting and from 10 to base k so idea is that uh right so for example only goes to 34 which is in base 10 if you change it to base 6 then it becomes uh i think become what it becomes 5 and 5 4 right because 6 plus five plus four that's 36 right and uh and 10 if you 10 is 10 right if you use 10 in 10 meters you get the same okay so this problem is basically the first uh to solve it easier is that once you understand how to write uh given an integer in base 10 to base k and finally you just sum of all digits okay so my algorithm is very easy so let's quickly talk about how to get base b so right suppose you have an integer n and you want to get base b then for each digits right so the first digit is just you already know it's just an uh the remainder right and remainder of b so this is the first digits and the remaining is and you just calculate the quotient right so then you put all your quotient into your n so the algorithm this should looks like a while should look like if your n is greater or equal to one then you should just define your own to be an uh remainder and you just take the digits so for each digit is this a modulo b so this is your digits right so you can create at least two a panelist digit but this is the final digits right so you finally you need to reverse the digits so this is the standard base b algorithm i think so if only zero you return zero then d is to be empty if n is greater uh y only exists basically greater than zero then your djs append appended remainder right okay and also a appended remainder and then you unchange it to be quotient then finally you just uh reverse the list right because the first remainder your compute should be the right most okay so finally you define the answer to be number to basically to include and finally sum of answers right so answer is at least basically each element is a digits then finally you sum of them so that's it and these algorithms should be very fast because you just use the division okay so yeah that's it i'll see you guys in the next videos
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
1,770
1777 maximum score from performing multiplication operations yeah let's first try to understand the problem so we are giving an array of nums and another array of multipliers and this nums is the length of the nums is more than equal to multipliers yeah so this is also reasonable yeah because we're going to use the multipliers one by one so for the first case for example we're going to use a three and this three can multiply by this three or this one because it must be at the hand of the tail of the nums yeah and for the next step we're going to choose the second number and this number will choose the head or tail yeah so for the first example this is three would times three and then this is two would times two and the last one would times one yeah and the final answer is 14 and the numbers can be um positive or negative numbers yeah uh we should understand that this is not a gritty problem yeah because uh maybe you're going to think we always going to choose the um biggest number but there is also negative numbers it is a yeah it is not the case I think it's really easy um to find counter examples yeah and this is actually a DP problem I think for DP it's more safe to solve such kind of a problem yeah so for each of the time we can choose from the hand on the tail and then for the next number we're going to choose from hand on tail and finally we just needed to check the maximum number yeah so for me I'm prefer to use uh the DFS plus memorization so for this C of DP because this is easy to write for the multidimensional DP yeah it's easy to analyze and easy to write yeah I'm going to prepare a left and right poter so this left and right poter is for the nums and another I will another one I'm going to prepare a Index this is for multipliers so I'm going to prepare a index at the same time I'm going to prepare the M should be equal to the length of the multipliers yeah now I can start the DFS uh finally for my return I'm going to return the DFS with zero un less of nums minus one this is from the right side and the index going to be starting from zero yeah because this uh the length of the multipliers is always smaller or equal to length of nums so for the S cases I can directly use the index if this index equal to m i going to return a zero it means there's no uh it means it has already finished the multipliers there's nothing to do so I going to return a zero now I'm going to prepare a result it will be negative Infinity so here for this result you cannot prepare for zero yeah because for the first calculation it might be a negative number but you cannot update it to zero so this is why we're going to always choose the negative Infinity because there's negative numbers if there's no negative numbers yeah maybe you can try to yeah put a result as zero yeah now we're gonna um prepare yes we just needed to check the nums so the nums can go from the left or right side so what it going to be so would be maximum of result yeah let's first try the left side because we don't know so if we choose form left side what it going to be L times the multiplier yeah the multipliers index yeah we get to the result and plus the DFS so the BFS would be uh because L has already been calculated and it should be removed yeah according to the question it should be removed so it will be L + one and the r removed so it will be L + one and the r removed so it will be L + one and the r would be the same and inside the index through plus one because it need to go to the next multiplier yeah now let's go to uh let's continue to check another side check the right side if we choose the right side it going to be m r and the multipliers going to still uh still be the same yeah and here going to be L and here going to be r + to be L and here going to be r + to be L and here going to be r + one yeah actually this is the entire code as you can see that it is not so difficult because we just use DFS plus memorization yeah now let me run it to T um yeah it is a non type yeah let me just check what is wrong with it unported types plus int and non type so this means my DFS there is a non type for the DFS yeah because here I did something wrong it should be R minus one yeah because the right poter should be shifted to the left and not r+ one let me just run it left and not r+ one let me just run it left and not r+ one let me just run it again uh it's the same else with plus one uh n l times DFS L + one r index + times DFS L + one r index + times DFS L + one r index + one and the result with nums R times multipliers index and uh index + one yeah this is the Str normally I should not make such C mistake um yeah this is the DFS l+ um yeah this is the DFS l+ um yeah this is the DFS l+ one r index oh I don't know yeah I get a int and non type definitely this going to be a int yeah if this index equal to M I'm going to return uh zero yeah let me just delete I don't know why I make such a mistake let's let me just start again so the yeah the result would be negative infinity and I will update my result it should be maximum of the result and with the left side it would be number l u times the multipliers uh with the index zero and plus DFS it would be l so the plus one and R and inside uh it should be uh index plus one yeah so what going to happen if I don't write to the second line yeah it is still something wrong with it I don't know why H yeah normally I think if I write it for the first time for the second time I should not make a mistake because For the First Time I didn't make a mistake uh this is the strings R minus one uh yeah because I didn't uh return the result yeah so now I think it should be okay yeah because for each of the time I should uh return the result now at least yeah at least the program works but I got the wrong answer for the first time it is a 10 and this is yeah not right uh let me just check uh what is wrong with it so yeah because I going to choose the maximum number uh this is a negative infinity and yeah this one I didn't change it I need to change it to R and now let's just check it yeah now as you can see it works now let me submit it to T if it can pass for all testing cases now as you can see it pass for all testing cases yeah I should be more careful about it so sometimes if I just use a copy and paste I will forget about yeah something and for this time I for I even forgot about the return um the time complexity is o n * n although you can complexity is o n * n although you can complexity is o n * n although you can see here there are three indexes actually for this L and R it going to always be smaller and smaller this is just like a two pointer because L will always be shifted to the right R will always be shifted to the left so this is actually o n and for the index so this is o m so the time complexity is O M * n is o m so the time complexity is O M * n is o m so the time complexity is O M * n yeah because we use the pass we use the memorization so that is why it can pass and let's check the and M so the m is 300 and N is the num length is 10 to the^ of 5 so this means three * 10 to the^ of 5 so this means three * 10 to the^ of 5 so this means three * 10 to the power of seven can pass for this kind of a problem thank you for watching see you next time
Maximum Score from Performing Multiplication Operations
minimum-deletions-to-make-character-frequencies-unique
You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`. You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will: * Choose one integer `x` from **either the start or the end** of the array `nums`. * Add `multipliers[i] * x` to your score. * Note that `multipliers[0]` corresponds to the first operation, `multipliers[1]` to the second operation, and so on. * Remove `x` from `nums`. Return _the **maximum** score after performing_ `m` _operations._ **Example 1:** **Input:** nums = \[1,2,3\], multipliers = \[3,2,1\] **Output:** 14 **Explanation:** An optimal solution is as follows: - Choose from the end, \[1,2,**3**\], adding 3 \* 3 = 9 to the score. - Choose from the end, \[1,**2**\], adding 2 \* 2 = 4 to the score. - Choose from the end, \[**1**\], adding 1 \* 1 = 1 to the score. The total score is 9 + 4 + 1 = 14. **Example 2:** **Input:** nums = \[-5,-3,-3,-2,7,1\], multipliers = \[-10,-5,3,4,6\] **Output:** 102 **Explanation:** An optimal solution is as follows: - Choose from the start, \[**\-5**,-3,-3,-2,7,1\], adding -5 \* -10 = 50 to the score. - Choose from the start, \[**\-3**,-3,-2,7,1\], adding -3 \* -5 = 15 to the score. - Choose from the start, \[**\-3**,-2,7,1\], adding -3 \* 3 = -9 to the score. - Choose from the end, \[-2,7,**1**\], adding 1 \* 4 = 4 to the score. - Choose from the end, \[-2,**7**\], adding 7 \* 6 = 42 to the score. The total score is 50 + 15 - 9 + 4 + 42 = 102. **Constraints:** * `n == nums.length` * `m == multipliers.length` * `1 <= m <= 300` * `m <= n <= 105` * `-1000 <= nums[i], multipliers[i] <= 1000`
As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before.
String,Greedy,Sorting
Medium
1355,2212
26
Loot Hi Everyone For Today We Are Going To Solve This Problem Point To Remove Duplicates Dark Clean Problems The Giver Shot Dead Cells Remove Duplicates In Place Which Element Of Years Old And New Length Of The Space For Adv You Must Be Modified Into The River In The Term Memory So One Example That They Can See The Giver Is One To Two To The Number 109 That [ __ ] Pure Function Shoulder Return [ __ ] Pure Function Shoulder Return [ __ ] Pure Function Shoulder Return Request U Because Judge The First Two Elements Of Observing One Interactively 1600 Will Be Modified Something I Want To Elements of elements which contains all the elements in the number 12304 land acquisition the number 109 demise 16 subscribe so they can see the white jhalda example 100 suppose that being another 1.2 2134 ok khush sudhir wa morning us service 1.2 2134 ok khush sudhir wa morning us service 1.2 2134 ok khush sudhir wa morning us service center The Video then subscribe to the Page if you liked The Video then subscribe Number Three And Will Be Again Are Not To Worry About The Length Of The Problem No Problem Solved The Process Of Birth Date With Best Solar System Is Like Using Pointers So What Does It Is That Will Keep 2.1 Under 2.1 Under 2.1 Under 10.25 Will Be Doing So Will Start From The Very 10.25 Will Be Doing So Will Start From The Very 10.25 Will Be Doing So Will Start From The Very First Time And It's Something Like This Point To Weiler Replay Element The Little Bit More Attention Pimple Text On Social Media Two And Three And 400 Ko Ka Point Now Here Point 12.21 More Extinct The Number one will Point 12.21 More Extinct The Number one will Point 12.21 More Extinct The Number one will not ignore this will be the first player of the year to the difference between the way will give one will dare attack you will happen impatient and that and will appear and 2nd three and 400 right now water condition is that we have to front Rock Hair And Din Power To Do The Thing In Noida Will Check Plumber Se Different From Others And Gives Pen Tool For The Third And Third Soft Veervansh Will Update You Will Be The Fighter Man 2 And 321 Ki And Aakhri And 404 Dars And Any Person Of The Country Daily Point and Share and Point to Verses and You Can Go to the Which Reporter Say Good But Just So This Is Not Win in To-Do Solt Record The Solution Soft Win in To-Do Solt Record The Solution Soft Win in To-Do Solt Record The Solution Soft in To-Do List Two Wick Point So Let's in To-Do List Two Wick Point So Let's in To-Do List Two Wick Point So Let's Start From The Very First Point Ranges From Wave Raw To The Length Of Yesterday Morning Expert Check Foreign Policy Director To Numbers And Different And This 2.5 Inch Exams Off Side Is Not And This 2.5 Inch Exams Off Side Is Not And This 2.5 Inch Exams Off Side Is Not Equal To The Norms Of Ujjain In This Condition Me To The Journey To The Value What will happen Speaker and MLA Ashwini Wig A Plus One Because To Intact Starter Sure Vinit To Return That Modern Literature Shiromani Plus One Components Soft Porn Image K Skirt Meet To Do A Length Of Norms Equal Juda Vikalp 047 Pass So It's 10 Workshop Bay So Let's Raw Test Encephalitis Corrector Note Or Which Accept Saunf 125 K Late Submit So Accept 100 Gram Tried This Problem With A Different Poses For This Is The First April 2012 Pointers Solid Thank You
Remove Duplicates from Sorted Array
remove-duplicates-from-sorted-array
Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. Then return _the number of unique elements in_ `nums`. Consider the number of unique elements of `nums` be `k`, to get accepted, you need to do the following things: * Change the array `nums` such that the first `k` elements of `nums` contain the unique elements in the order they were present in `nums` initially. The remaining elements of `nums` are not important as well as the size of `nums`. * Return `k`. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int\[\] expectedNums = \[...\]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** 2, nums = \[1,2,\_\] **Explanation:** Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,0,1,1,1,2,2,3,3,4\] **Output:** 5, nums = \[0,1,2,3,4,\_,\_,\_,\_,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-100 <= nums[i] <= 100` * `nums` is sorted in **non-decreasing** order.
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
Array,Two Pointers
Easy
27,80
1,920
Ajay Ko Hua [ Hua [ Hua Hello One And Welcome To New Video English Video Viewers Problem Number 90 From The Problem 000 Have to agree here and today let's come in the middle of this in the name of That will be there at once and from the railway station duty reduce 2002 number of clans given till minus one ok ghee problem example2 m30 this which is ours this is our meaning and here 0share 0 0share for this If we click on top one then what will happen then our today's head off if we check which row for answer of one what will be the name clearly then here if we put it in place of then What we have to do is like we will keep so we will submit and 20 so see here what we will do here our 2008 will soon be gone here name shop names of three which instead of numbers of five don't threaten 12345 this fragrance will do This is so then for when we see here then answer add so our what's this side and set our name fennel nfo how many 1234 so here we subscribe 12345 44000 as we like this a little bit that this is the example given to us Hello We have been given 105 1234 Now we have to make ours, so first of all we have to answer the answer for here if we if ours which will remain ours then ours which is ours these people do not threaten the sum of 9808005005 set the jhal zero work will have to be named Saturday or removed Naam se kya faltu sid ke liye to hamara 2012 to hamara jo yeh so here for us subscribe to our channel if you subscribe for 10 minutes account statement hoga 2012 i.e. one ho's account statement hoga 2012 i.e. one ho's account statement hoga 2012 i.e. one ho's see this don't forget to subscribe If we are 1234, then our 3232 here, we need to subscribe for this, so for this, we were the first to approach Amazon subscribe, first of all, who will make the patient false, which is this, which will be our size of salt, its size. And the time is right, like this is ours, then from where do we get our time, we have been appointed the president and now inside this we will fold it at number eight and as if the oil is finished here, then ours is ready, now we will call it time. From time to time, which will be clear if we talk about its space complexity, Space Congress President is coming, then this is our code, first of all, I took it as per the order, we will enter it, we will appoint it, this is called subscribe. The second is the laddu solution, what we have to do is to make it a loop, come as soon as possible and subscribe to the channel, tell someone inside it like we have finished the solution together and we will finish it like this, post your answer and subscribe to us and What is the result and this has been our success, this is from the Faster Than convention and what Meghnad 3000 does, for this problem keep watching our channel subscribe time complexity of notification and paste this we do this a new Instead of doing this, update the same as to what we have to do, here also we will make these changes, first of all we will take out our N which is because the size, subscribe our channel, after that we will give the value of change here. Something in the exam so that we can change this person in such a way that first of all we are appointing him here and what can we do to finalize whatever will happen with him. Let us assume in every position, if I for the first position, then we can do something like this: for the first position, then we can do something like this: for the first position, then we can do something like this: Name data is equal to 9 This is aimed at and multiply the number at I and multiply and what we will do in this is village or table and We will take this sentence, okay, we will take this and as we get this, we will cut it for the number * * * for the number * * * 1234 500 600 800 to 1000 times unity is 0, our first element is Namaskar, what will it become and ours will go something. In this way, if you calculate for some then what will we do, now we see what will we do for them, our Here we should have got that i means norms of number tie we should have got one comes from in times index in the answer we should have got should get so we like we divide this so here we do so we here But you can type 06 so if for then how much is this how much is our wake up here if from here we want what is the value here we don't want we will divide thirteen by them if we divide it like this education then we are getting two so there But today's if we want the value of what was already here we will have the value. If we take this as percentage but cent end then we will get the value meaning if we take this thirteenth of those people this is its original divide. Set this measurement that you can make our ghagra flat. Subscribe to your special 5985 K0 12345 2014. If you divide the education and get it then you will get six * 4 plus original velvet six * 4 plus original velvet six * 4 plus original velvet 20123 blind. Now we will make it 20% of the original. With this we will 20% of the original. With this we will 20% of the original. With this we will get and which is our channel, now instead of our idli, divide which is our 0123, complete our in the same way * * * 40 subscribe will be five, this will be 5.5 at cent and what will be five, this will be 5.5 at cent and what will be five, this will be 5.5 at cent and what will be 565, thirty plus will be taken out instead of 3033. Here we are the guest at home, if you take us out and do the original thirty percent, then we will soon, if we want it here we will talk, then click for us, subscribe to our Naan, our channel here into three plus our channel. Subscribe and we will get its original vegetable 22% course and we will get its original vegetable 22% course and we will get its original vegetable 22% course that we will get four because the map of 6042 is 1618 subordinate value and if we want it our which will finally divide by terrorism which will be our channel this problem here we are an actress. From the name, here we look at the time and space solution for this and see that this is ours which is our today's two Jhal name set name from the shop number on the left side st and a plus this should be the first institute. Amresh put inside this inside the parents plus not for and after that we like our complete is over time and plus and we hate table and after that we will get the hello complete result so let's see if we are on our fearless then our old solution. Let's remove this, we will take only one thing that intense cold not limit from here we will now turn on a potato here from where to where Chadana is equal to zero six transaction size and we will cut it inside this we will cut it We will open it * cut it We will open it * cut it We will open it * which is ours, we will have to take it and after that, like we will add it here, our loop will be like this is finished, run it quietly, we will run it till where from the village, we will run it is equal to zero six. That's 06 this is done and that's going to last and inside that what we have to do is keep doing a sentiment and here what we have to do is equalize house add and our potatoes now after that we'll return this number of ours okay If you submit and subscribe the result, this is an example. We submit this particular chapter note solution and if we have used less space than 498 A, then you will consider the solution a coward. If you like the solution society, then like this video. Share with your friends and if you want to practice regular problems then you can join our telegram channel Thank you for watching my video
Build Array from Permutation
determine-color-of-a-chessboard-square
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** **Input:** nums = \[0,2,1,5,3,4\] **Output:** \[0,1,2,4,5,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[0\], nums\[2\], nums\[1\], nums\[5\], nums\[3\], nums\[4\]\] = \[0,1,2,4,5,3\] **Example 2:** **Input:** nums = \[5,0,1,2,3,4\] **Output:** \[4,5,0,1,2,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[5\], nums\[0\], nums\[1\], nums\[2\], nums\[3\], nums\[4\]\] = \[4,5,0,1,2,3\] **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < nums.length` * The elements in `nums` are **distinct**. **Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)?
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
Math,String
Easy
null
61
foreign with the lonely Dash and today we're going over lead code question 61 rotate list which says given the head of a linked list rotate the list to the right by K places okay so we know that k equals 2 and we have a linked list right here which we are going to rotate by two so what does that mean well if our linked list is in order one two three four five if we rotate it to the right one position or two positions each one of these is going to move so one will move to two will move to three will move to four will move to five which means five will then have to move all the way down here to the one position and that gives us this rotate the rotate one position but since k equals two we have to do it again so 5 goes to one goes to two to three to four goes all the way down to where the five position is and that gives us this answer here rotates two times where the new head of our linked list is actually this four and the tail is this three so that's all the question is asking is taking all the nodes and moving them to the right K number of times now it sounds pretty simple but there's there it's kind of more complex and we're going to dive into how we're going to do that now so down here I have the exact same linked list one going all the way to five and K is equal to 2 here and we're going to solve this mathematically okay and I'm just going to go through each of the steps and it'll kind of fall into place of what we're doing so in order to solve this we're going to need a pointer and this is our current pointer and I'm going to stick it here at the head of our linked list and the first thing we're going to need to calculate is going to be the length of our linked list now we can't just ask like hey what is the length of linked list we actually need to count it so the first thing we're going to do is take our pointer and we're going to Traverse our linked list one two three four five to determine that the length is 5. okay so we have a length of five next thing we're going to do is after we know how long it is we're going to connect our last node to our first node like this so that we have a cycle it's cyclic so Five Points to one points to two points to three points to four points to five awesome okay one is still our head but we've created this cycle and that's really important um because without this cycle happening when we cut uh one of these connections then we're gonna have two separate linked lists and we just don't want that so we got to make sure that they're stuck together now here comes the mathematics we need to figure out which node is going to be the new head of our linked list and we already know that this 4 is going to be the head of our new linked list because we did it just above it's right up there we know the answer already but how do we make this determination well we got to use math we know the length is 5 and we know that K is 2. so in order to figure out where to move our current pointer in order to find our new head we're going to have to subtract K from our length so in this case 5 minus 2 is 3 1 2 and 3 therefore the node just passed our current pointer is our new head and we can cut here and then we're done because that'll be four points to five to one to two to three and again we already know that's our answer because it's up here so the simple mathematics is we're going to take our length we're going to subtract our K and we're going to move our current pointer that number of nodes forward now there is an issue okay and the issue is within our constraints okay so we're going to look at our constraints and it's simply that K is going to be any value that is more than Z or equal to zero but less than 2 times 10 to the ninth and it's possible that K could be greater than the length of our um that our linked list because it only goes up to you know five so what happens when K is greater well let's just say k is 12. all right and we're going to put our current pointer back here we counted that the length of our linked list is five if we come down here and we take 5 and we subtract 12 that you know gives us negative seven we have nowhere to move our current pointer I mean I guess we could go backwards one two three four five six seven and that does sort of work but that seems counter-intuitive work but that seems counter-intuitive work but that seems counter-intuitive because if it was I don't know a huge number such as this the current pointer would have to go back around and it just takes up too much time okay so instead we're going to do a little bit of mathematics and we're going to use the modulo symbol so that's down here okay so our new calculation is going to be K the value of K modulo the length okay so in this case we know that the modulo just provides us with the remainder after a division so 12 divided by 5 is 2 with 2 as the remainder so K modulo length is going to end up being 2. which as you can kind of guess was our original answer anyway once we have done that we can take our length and subtract K from it which is three so we're going to move our current pointer one two and three and what do you know that brings us to this position here and it solves our problem so this is a way of making the arithmetic work in our advantage it will make it go much faster so to sum everything up what we're doing in order to solve this problem is we're going to count the number of nodes that we're dealing with to find our length once we have our length we're going to determine if it is well if our length is greater or less than K if our length is greater than K we're just going to subtract K from our length and then move our current pointer those numbers of positions connect the last and first node and then cut to find our new head however if K is greater than our length here we're going to have to do this mathematics here in order to do the same thing to move our current pointer forward and find the new head so hopefully that makes sense let's go into a little bit more depth with our constraints to see if there's any other edge cases that we might have to consider so we've already looked at the constraints um and the number of nodes in the list is in the range of 0 to 500 and we've already talked about how what would happen if K was greater than the number of nodes and we solved that uh by using our modulo symbol down here now it would still work if we didn't use the modulo but we could run into some timing issues so that's why we're using the mathematics in order to solve this so we're golden outside of that we know that the values within our nodes are going to be between negative 100 and 100 inclusive so that's okay and K could equal zero so if k equals zero you might just want to say okay it's not rotated at all let's just return the head of what we're given but outside of that it could also be rotated an enormous number and again that's what we were talking about using this modulo mathematics to solve the problem so that's pretty much the only Edge case we'll have to consider it's not something we need to do right away we've kind of baked it in to our solution so let's move forward and start with some pseudo code so for our pseudo code I'm just typing into the python work area of the lead code website and I know we just went over a couple of Ed well sort of an edge case but something to mention one more time is basically if there is no linked list provided remember because in our edge cases it said it could have zero nodes to 500 nodes meaning there is no head what can we do well we can just return nothing or null which are nothing null none whatever we need to do in order to take care of that edge case and while it's not necessarily an edge case it can shorten the amount of time um for our solution to process okay so once that's taken care of it's time to code something hooray for coding um the first thing we need to do is create a current pointer in order to uh you know first count the number of nodes in our linked list and that's going to be at the head um of the linked list so we're creating our current pointer and then we're going to need to create a counter uh to determine the length of the linked list and of course that's going to start at zero right because we're going to end up needing to actually you know what that's going to start at 1 because we are putting our pointer on the head of our linked list so that's why it is starting at one all right then we're going to use a while loop um use a while loop that will Traverse the linked list to determine the length of the list stopping the pointer at the end of the list right and so that's going to look like basically while the pointer.next like basically while the pointer.next like basically while the pointer.next exists that's how we're going to get this to stop at the end of our uh our linked list so once that's done um once the pointer stops we are going to then point the last node of the list to the head of the list this creates um our cycle or Circle right and this is a really important thing because again I've talked about the importance of connecting it so that half of our linked list doesn't float away when we cut that linked list with a new head then you using the calculated length of the list right because that's all we did we're using the calculated length and I don't think that's how we spell using the calculated length of the list we need to determine how many nodes to the left we need to shift the new head of our linked list and again it's not really the number of nodes to the left it's a full on calculation of how many nodes we need to move our uh count or our pointer to the right so how many nodes to let's see move the current pointer uh to the right in order to find the new head of our olings list there that makes a little bit more sense to me um okay so then we'll do yeah that's basically all we need to do there then we need to move the current pointer through the cycle until we stop at the last node of the new list we need to create a variable or a pointer or something to hold the value of the new head of the link new linked list that way when we cut it we have something to return right then we're going to detach or cut the pointer of the new Final node and point it to nothing right because it needs to be the final node and it can't be pointing at anything it's the final node finally we can just return the new head of the new linked list and we're done so this is all of the pseudo code we are going to need in order to solve this problem uh let's take it copy and paste it and uh get coding okay so we're working in the JavaScript work area of elite code website and there's all my red squiggly lines for my pseudo code and we're just going to kind of follow along so the first thing we're going to do is deal with this Edge case it's not really an edge case but it's something I like to stick in at the very beginning which is basically saying if the head value provided is null or doesn't exist or has nothing we're just going to return null anyway so it kind of gets rid of the case where if this head has no value then obviously K doesn't matter so we're just going to return what we have not really an edge case but it uh might shorten the runtime a little bit here now we get to code real stuff so we need to create a current pointer at the head of our linked list so let's call it I don't know current let current equal head and we're sticking it at the head of our linked list and we also need to create a counter because we need to count the length of our length list or a linked list so we're going to call that length uh you could call it counter whatever you need to but we're going to start it with a value of one and we're starting it with a value of one because our pointer already should count the head it's on we're going to move our pointer and some people will start this at zero which will be a big mistake so just remember we've already counted our head that's why we're starting at one and we'll eliminate it that's pseudocode now we're going to do a while loop to Traverse our counter or sorry our pointer through each one of our nodes to add to our length so we can calculate the length of our linked list so while in this case current.next is not null right so while current.next is not null right so while current.next is not null right so while there is a value for our current pointer to move to what are we going to do well we're going to move our pointer to it by making our current pointer move to the current dot next value and we're going to add 1 to length so length plus okay now this should stop our current pointer at the final node because as long as this 2 exists that moves forward 3 exists this moves forward 4 exists this moves forward five exists this move forward nothing else exists we break out of our Loop and our current pointer sits on the very last node that's what this while loop is doing so we're using our while loop to Traverse it and stop the pointer on the last node once the pointer stops we need to point this last node of the list to the head of the list this creates our cycle and a circle so we're breaking out of our while loop and we're going to say that the current dot next value so wherever our current pointer is pointing needs to be the head this is the most important uh code script of the entire thing because without this our mathematics won't work so we have now pointed our final node to the front of our linked list and we go to the mathematics so using the calculated length of the list we need to determine how many nodes to move the current pointer to the right in order to find the new head of our linked list and that goes back to our mathematics here now I originally thought to myself oh I can just use a quick if statement if the length is greater than our K value then we can use this math here if otherwise if our K is greater then we can use this math here but that's kind of unnecessary step because even if we just go straight to this math it'll work right so two modulo 5 is still two 12 modulo 5 is still two a million and two modulo 5 is still going to be two so we're going to go straight to this mathematics here which means when we're dealing with this math we're going to say that K is going to be equal to K modulo length right our new uh calculated length and then K is going to then equal length minus whatever K value we just created and we can simplify this mathematics as well by taking this value here I'm going to copy it and we're going to replace it here so we don't need this line at all so that's how we're going to do this mathematics and create a new value of K that we're going to have to move our current pointer to the right that's what this line is doing so hopefully that math makes sense to you now we actually have to move this current pointer through the cycle and stop it at the last node of the new list so how are we going to do that we need to move our current pointer K number of times so we're going to use a while loop and we're going to continually subtract the value of K until it reaches zero so while K is greater than zero what are we going to do well we're going to move our current pointer to the next node and we're going to subtract 1 from K so let's say k equals 3 which is in our example uh if k equals three we're going to move our current pointer 1 and then K now equals two if k equals 2 we're moving our current point or one subtracting it to one if k equals one then current pointer moves and then it equals zero when we break out of this Loop so that's how we moved our current pointer three times okay so that's our movement of our pointer now we need to create a variable to hold the value of our new head so coming back here we moved our current pointer one two three and Our intention is to cut this line if we don't hold this value and we cut this line or this pointer four and five are just going to float off into nothingness so we're going to have to hold it with a value so in order to do that we're just going to call it new head so let new head equal the node that is next to our current pointer so current dot next that's pretty simple all right so that is now holding the new head of our linked list now we need to detach our pointer so that this 3 is detached and pointing off into nothingness instead making it the end of our linked list so in order to do that we're just going to say that our current dot next is going to equal null nothing so our current pointer points to absolutely nothing and then we're done we just have to return the value of our new linked list which of course is return new head and we are done with all of our coding so hopefully I'm just kind of Squish it in here hopefully it will run without any issues I'll hit run see how we did against the test cases it does seem to work ooh 100 milliseconds seems pretty long but I'll hit submit and see how we did against everybody else on the internet and we did just fine so it looks like 94 in run time and 84 in memory so that is a simple and straightforward way of solving rotate list that isn't quite o of n because we have to go through it at least once to calculate our length and then move uh partially through it again with our current pointer but it's pretty darn fast uh way of solving it using JavaScript foreign
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
110
hello fellow YouTubers today we're going to look at balanced binary tree which is lead code problem 110 this problem states that given a binary tree determine if it is height balanced for this problem a height balanced binary tree is defined as a binary tree in which the left and right sub trees of every node differ in height by no more than one so if you look at example one here you see that the three has a left branch and it also has a right branch which is longer but if you take the right branch which is length two and subtract the left branch of length one you get one and so it can differ by at least one or at the most one so this is true but barely and again to read this it's 3 9 20 and then the null is because the nine has no left or right Branch then 15 and seven now example two is a nogo because even though each of these nodes is differ by no more than one the distance from here to the four is definitely more than one than the distance from the one to the two here so this one will be false all right let's see how we're going to do this I question whether some of the this is marked as easy and I question whether it's an easy one but anyway more binary tree fund with recursion so here is the method lead code gives us so basically if the root is null we're going to return true um there's no reason the left and right are both empty so as far as we're concerned it's balanced then we're going to return the height so we need to determine the height of the root and to do this we're going to compare the left to the right and if when we run this method and it returns a negative one then that will return a false otherwise anything that's not equal NE 1 will return true all right so let's define this method it's going to pass back an integer and we'll pass in the node the tree node okay so if node is null we're going to return zero meaning that the node yeah if node yeah okay so yeah the node left or right we're going to end up assigning this to the left or right so if it doesn't have a left or right it's going to return zero so int left equals we're going to call height again more recursion but this time we're going to pass the node. left and then we need to check the right value of the node to so we're going to call height again and pass node. right now we're going to determine the distance between left and right so we're do a math.abs which is short for do a math.abs which is short for do a math.abs which is short for absolute which basically means any number that's negative is just going to be returned as positive so we're going to subtract left minus right in the case where right is greater than left it doesn't matter because we're doing absolute value so if the distance is greater than one which was what leite code deemed as um balanced is if it's one or less or if the left is equal to negative one or the right is equal to negative one then we're going to return negative one which will'll return false otherwise we're going to return one for the current node plus the max of the math Max of either the left or the right and that is it so let's run this through the debugger oh yeah I got my handy chart here too okay so we're going to take the first problem here basically I recreated this tree and now we're going to run through and figure out if it's balanced okay so the first thing we're going to do is take the root now if you look here the root node is three it's not false so now we need to figure out the height so we come down here the node is not null so now we need to determine the left node so node left now we're back in height but we're now using the value Nine and Nine does not have a left and so we go to the right nine does not have a right either so that returns null now we're going to close out the nine we're going to take the distance between the left and right which is just going to be zero because it doesn't have left or right and none of these are true and so it's just going to return itself basically 1 plus left and right so that is what we got okay so now we are on back to the three and we've done the left now we need to go on to the right okay so now we have the 20 has a node left so now we're into the 15 it's not all but the 15 doesn't have a left and it doesn't have a right so now we're going to determine the distance between the left and the right which is zero none of those are true and it returns one so this is now the value of the 20 has one left and its distance is one so now we'll go on to the right value or the right branch of the 20 and so here we are with the seven and the Seven doesn't have a left doesn't have a right so again zero for left minus right absolute value and distance is not greater than one left and right are not equal to negative 1 so it will also pass left okay so now we're back to the 20 and the 20 has a left of one and a right of one so we took the absolute value of that and the distance is not greater than one distance is zero math so one plus left and right all right so now we're back to the three and we're going to the right we finished off the right so we have a distance of two the right has a distance of two the you know 20 to the 15 to the seven is two away from the three but the left is one because we have the nine branch and so we're going to take 1 - 2 which is negative 1 but absolute - 2 which is negative 1 but absolute - 2 which is negative 1 but absolute will make it one and so that is not greater than one and left and right are not equal to negative one and so we're going to return this actually this really doesn't even matter we're take the max of left and right plus one so it'll be three but all we're looking for is the Boolean or that it I'm sorry the yeah the integer we're looking for the integer here so this um as long as it's not equal to negative 1 it's going to return true and that's exactly what it does so this tree is balanced all right let's put it through leak code here run it with that first example it is accepted and then we run the code oops run it twice just to be sure look at that again fastest submission all right so let's go through the space and time complexity so time complexity is O of n increase the number of nodes it's going to increase the execution time go through all those nodes and then because I did the height balanced determine if a or make the tree height balanced in my last video and that was log of n but because the tree doesn't have to be height balanced in this case we're checking for that it's just o of N and that is it so as always let me know if you have questions thanks for watching and we'll see you next time
Balanced Binary Tree
balanced-binary-tree
Given a binary tree, determine if it is **height-balanced**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,3,3,null,null,4,4\] **Output:** false **Example 3:** **Input:** root = \[\] **Output:** true **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Binary Tree
Easy
104
1,461
hey guys let's paws Finnegan is chaser in this video I'm going to take a look at 1 4 6 1 check away the string contains all binary codes of size k give me the binary string s and integer K return true if all binary codes from this K is a substring chops as otherwise return false while the battery codes up to R then to where 0 to 1 0 1 and they can be all found in straps substrates while the good for searching for this solution for this problem is very simple I think we find all the possible means of the binary codes which will be 2 to the power of K and for each we'll search right service search or cost us s then go to say n so this is the time complexity I think well if we search on the string every time for any the binary form it will cost a lot of time rather we could do it in a reverse way we get all the strings and then we just check if 0 exists in a constant time right which say get all substrings and then check existence by constant time so with that case we actually could improve it to go 2 to the power of K no we don't need to actually track check the park' because the input are all the park' because the input are all the park' because the input are all valid we can adjust to check the size okay this will use a set and just to check this check to set size it is constant well we cool right ok now we just need to traverse through the string and get the two of the power of K an end of cake right so we get substrate substring of cake costume who you just say substrains raise a set and worry that I to 0 I plus K minus one if distance is 1 then the meant is I itself right class one management so this is the ending the ban was plus so we just add a suction to it right s slice cool and what we need we just returned we just check because the input is all valid binary string we just check the size staring the size 42 to the power K right it equals way then all by reforms are in its radical I think we're doing great yeah or accepted and let's try to unless the time typically time this will cost us as linear time and for the slice forecasters came so yeah okay inkay and space we were at those who've acosta step to spawn okay right okay that's all for this problem for the help I'll see you next time every time we first subject problem rather than we gets the substring and search maybe we can do the reverse way and find all the possible sub strings and just to check them tip the easy distance by one by constant time but in strict special case like this problem we just check the site so we need to do it in a flexible way I'll be out of the UPS that's the exact driver
Check If a String Contains All Binary Codes of Size K
count-all-valid-pickup-and-delivery-options
Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`. **Example 1:** **Input:** s = "00110110 ", k = 2 **Output:** true **Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all found as substrings at indices 0, 1, 3 and 2 respectively. **Example 2:** **Input:** s = "0110 ", k = 1 **Output:** true **Explanation:** The binary codes of length 1 are "0 " and "1 ", it is clear that both exist as a substring. **Example 3:** **Input:** s = "0110 ", k = 2 **Output:** false **Explanation:** The binary code "00 " is of length 2 and does not exist in the array. **Constraints:** * `1 <= s.length <= 5 * 105` * `s[i]` is either `'0'` or `'1'`. * `1 <= k <= 20`
Use the permutation and combination theory to add one (P, D) pair each time until n pairs.
Math,Dynamic Programming,Combinatorics
Hard
null
1,796
welcome back for another video we are going to do another legal question the question is second largest digit in a string given an alphanumeric string s return the second largest numerical digi that appears in s or negative one if it does not exist a alphanumeric string is a string consisting of lowercase english letters and digits example 1 s is d f a 1 2 3 2 1 a f d the output is 2 explanation the digits that appear in s are 1 2 3. the second largest digi is 2 example 2 s is a b c 1 the output is negative 1 explanation the digits that appear in s are 1. there is no second largest digit let's work for the code we can use hash set to solve the question we first iterate full characters of string if the character is a digit and not in a set we add the digit to a set finally if there are more than one elements in the set return the second largest digi in the string else return negative one time complexity is o n space complexity is o1 the solution works thank you if this video is helpful please like this video and subscribe to the channel thanks for watching
Second Largest Digit in a String
correct-a-binary-tree
Given an alphanumeric string `s`, return _the **second largest** numerical digit that appears in_ `s`_, or_ `-1` _if it does not exist_. An **alphanumeric** string is a string consisting of lowercase English letters and digits. **Example 1:** **Input:** s = "dfa12321afd " **Output:** 2 **Explanation:** The digits that appear in s are \[1, 2, 3\]. The second largest digit is 2. **Example 2:** **Input:** s = "abc1111 " **Output:** -1 **Explanation:** The digits that appear in s are \[1\]. There is no second largest digit. **Constraints:** * `1 <= s.length <= 500` * `s` consists of only lowercase English letters and/or digits.
If you traverse the tree from right to left, the invalid node will point to a node that has already been visited.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
114,766
1,740
hello and welcome back to the cracking Fang YouTube channel today we're solving lead code problem 1,740 find distance in binary tree given 1,740 find distance in binary tree given 1,740 find distance in binary tree given the root of a binary tree and two integers p and Q return the distance between the nodes of p and value Q uh in the tree the distance between two nodes is the number of edges on the path from one to the other so let's look at an example we have this binary tree here and we want to find the distance between the node p and the node uh sorry P equal 5 and Q equals 0 so that's this node and this node uh we can pretty easily see that we go from 5 to three that's one from 3 to one that's two steps and then from one to zero is three steps so that's how we get our solution of three here so this problem is pretty straightforward if you're just looking at the graph like your brain can very easily solve it but how do we do this in code so there's two approaches here um and I'll kind of say both of them and we'll code one of them up uh the first one is the least common ancestor approach so what we want to do is in the graph we'll find each node and then we will basically find the lowest kman ancestor of them uh and we'll keep the distance to the lowest common ancestor so if you remember we solved the lowest common ancestor problem um on this channel but basically we would find it which is three here and we're going to keep track of the distance of each node to the least common ancestor so from this side it' be V1 from this side of V2 this side it' be V1 from this side of V2 this side it' be V1 from this side of V2 and then simply add them together and we get the solution now some people on leak code say that this is a one pass solution but I don't think so because they're calling their DFS function to find both nodes now if your tree looks like a linked list where it's like this and let's just say it's really long and Q is here and P is here you're going to do a search all the way to P to find p and then you have to do the same search to do Q so people who say that it's one pass this is not true because I think in this case you would have to do two passes because you're basically traversing the entire tree um if they're just one node apart and Q is the last node in this like linked list type tree um then you're actually going to do basically two passes through the tree so anyone who says it's one pass I'm not too sure about that one anyway that's the least common ancestor one I don't really like that approach I would much prefer to do it as a graph and we've done this question before it's just been in a different word so actually we're going to build a graph um which Maps I guess like each node to all of its edges uh node to its edges right so basically where from each place we can go and in this way we can basically just start our search at either P or q and then with the graph we're just going to Traverse it uh Traverse the graph and then basically just BFS until we get to um either P or Q to find and then that is going to be our distance and we simply return that so that solution obviously to build the graph you have to daverse the entire thing so it's going to be Big O of n to do that and then potentially in the worst case it's going to be also a big O of n uh in the case that you have a graph that's like this or a tree that's like this where p is here and Q is here you have to basically Traverse all the way up this way and then all the way up the right side so that's why I could potentially have to visit all the nodes in the worst case but at the end of the day the time complexity is still going to be Big O of n same with the LCA uh and then also the space complexity is also going to be Big O of n for the graph and then yeah for your BFS you're also going to need Big O of n so it's just big O of n plus Big O ofn but ASM totically it's also just Big O of n so yeah you have two options here again you can go with the least common ancestor approach or you can go with the graph approach personally I like the graph approach the time complexities will be the same space complexity are the same I think explaining the graph is a bit easier um but this is just a good example that for one question there are potentially multiple Solutions and in an interview it's actually good to list them out um and then you can just go with whichever one you want obviously if one was more efficient than other than the other then you should do the more efficient one but in the case here where they're the same time and space complexity I'm just going to go with the graph solution because I like that one better and it's easier for me to explain so again we're going to build the graph um of basically all the nodes we can reach from a given node and then we're just going to start our BFS from let's just say p and we're going to BFS until we get to q and then however many steps it takes that's how long it is um between them so that's how we want to solve it let's go to the code editor and type this up okay so we went over the intuition we went over two possible solutions and now we're going to code one of them up first thing we want to do is let's just clear away all this kind of boiler plate and just have a clean working environment so first thing we need to check is actually if P equals Q we don't need to do anything obviously the distance between two nodes which are the same are going to be um zero right and one thing that we need to actually realize if we look at the constraints of the problem I probably should have said this before is that all the values are uh unique and that P and Q exist in the tree so if P equals Q oops how do I get rid of this okay fold um then we're done so if P equals to Q then we return Zer because of the same node okay so we want to build our graph and remember we're going to be mapping for each node basically all the other nodes that you can reach um in that tree so we're going to say the graph is going to be collections. default dict and this is going to be a list now to do this we're going to have to BFS over archery and basically build the graph uh node by node so we're going to say uh we need a q here to basically process everything so we're going to say Q equals collections. default dict oh sorry not default dict um uh deck we want to use a q uh and we're going to pass in the root now we're going to say while we have something to process and if I could just type today that'd be great we're going to say the current node is going to be q.p left and now what we want to do is q.p left and now what we want to do is q.p left and now what we want to do is if the left node exists then we want to populate um that relationship in the graph and also if the right node exists we want to populate that relationship in the graph so we're going to say if node. left we're going to say graph of node. Val and the reason that we're storing the values here is because they're all unique um we actually AR we don't need to actually store the nodes themselves we can just store the values because they're guaranteed to be unique we don't have to worry about any sort of duplicates or anything um so we can just store the values directly so we're going to say there's going to be an edge which goes from node. Val to um append node. left. Val and conversely we need to do the opposite because it's bidirectional um so we're going to say graph of node. left. valal um we're going to pend node. Val and then we just need to append uh that left node so it can be processed further so we're going to say q. pend node. left same thing for the right node we're going to say if node. right exists we're going to say graph of node. Val we're going to append node. WR doval and we're going to do the same thing for node. write doval we're going to append um node doval okay so and then the last thing we need to do is we need to make sure we do q. pend node. write so it also can get processed so doing all of this will build our graph now obviously we need to process that graph so we're going to do a BFS we're going to start at node p and we're going to search for node Q so what we're going to do is we're going to say a q is going to be collections. deck and we're going to populate Our Deck with what we're going to use a tuple and we're going to start our node at p and obviously we've done zero steps so far so we're going to store that um we've done zero steps now whenever we do a BFS we want to make sure that we actually don't get caught into a cycle obviously our graph has bir directional edges and we could actually go in a cycle if we didn't keep track of where we visited so we're going to say a visited set is going to equal to set and we're going to put p in there because that's where we start our search now all we need to do is just kick off our BFS go from p and then as soon as we hit Q we can stop and then just return the number of steps we took so we're going to say um while Q we're going to say the current node that we're processing and the number of steps we've taken is going to be q.p left and we've taken is going to be q.p left and we've taken is going to be q.p left and we're going to say if the current node it actually equals q and remember that um the current node we actually put the value in there so we can just compare it to Q directly because p and Q are actually integers uh they're not given to us as nodes so if the current node equals Q we're done we found Q we can simply return the number of steps it took otherwise we need to consider uh continue our BFS so we're going to say for Edge in graph of whatever the current node is we're going to say if we haven't visited that edge obviously we don't want to get caught in a cycle here so we're going to say if uh Edge not in visited then we want to visit that edge so we're going to say visited. add. Edge and we're going to say q. append um what the edge and then steps plus one because now we need to go uh one step further and that's actually it we're done so as soon as um this return trips up we will be done there's nothing more we need to do let me just make sure I didn't make any syntax mistakes and looks accepted submit this thing and it is accepted cool so let us go over the time and space complexity uh we talked about this earlier but basically to build the graph is going to take Big O of end time and then to BFS over it is going to take Big O of end time so let's just do that so we have the time complexity so this is Big O of n um to build graph and then we need B AO of n to BFS graph so this means that it's Big O of n plus Big O of n which is Big O of 2 N but we know that ASM totically this is the same as Big O of n space complexity it's the same thing it's going to take Big O of n um to build the graph uh plus Big O of n to BFS over it because we need to maintain the Q so again this is Big O of 2N which ASM totically is just Big O of n which is actually the same runtime complexity of the least common ancestor solution so both of them are the same um but yeah okay so that is how you solve fine distance in a binary tree I quite like doing problems like this where you basically take a binary tree transform it into a graph and then Traverse that graph to get your answer I really like that solution pattern I don't know maybe it's just years of working at Facebook and traversing graphs and nodes and all that I just like graph problems anyway that's how you solve it if you enjoy the video why not leave a like and a comment uh And subscribe to the channel really helps me grow otherwise thank you so much for watching and I will see you in the next one bye
Find Distance in a Binary Tree
count-subtrees-with-max-distance-between-cities
Given the root of a binary tree and two integers `p` and `q`, return _the **distance** between the nodes of value_ `p` _and value_ `q` _in the tree_. The **distance** between two nodes is the number of edges on the path from one to the other. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 0 **Output:** 3 **Explanation:** There are 3 edges between 5 and 0: 5-3-1-0. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 7 **Output:** 2 **Explanation:** There are 2 edges between 5 and 7: 5-2-7. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 5 **Output:** 0 **Explanation:** The distance between a node and itself is 0. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * All `Node.val` are **unique**. * `p` and `q` are values in the tree.
Iterate through every possible subtree by doing a bitmask on which vertices to include. How can you determine if a subtree is valid (all vertices are connected)? To determine connectivity, count the number of reachable vertices starting from any included vertex and only traveling on edges connecting 2 vertices in the subtree. The count should be the same as the number of 1s in the bitmask. The diameter is basically the maximum distance between any two nodes. Root the tree at a vertex. The answer is the max of the heights of the two largest subtrees or the longest diameter in any of the subtrees.
Dynamic Programming,Bit Manipulation,Tree,Enumeration,Bitmask
Hard
1177
173
tree iterator problem number 173 on leak code and you are to implement the bst iterator class so you have to implement the constructor for this class and then two methods one called next and the one next is called has next so um you're given uh the root of the tree in your constructor and then you're supposed to keep track of a pointer and just say return for this one you can just say what's the next one and this boolean is going to return true or false whether or not there is a next one given the route that was passed in the constructor so um it says you may assume that the next calls will always be valid you mean that you don't have to check whether or not there is a has next before you return this next so for instance you're given this tree here um you would be past this route and then it would just tell you um net when you're calling next you would return three then seven um then whether or not it has next you would say true because you're not at the end of the tree um then you would return 9 if you're checking if it still has another one you will return true then 15 and then 20 and then you're going to return false because you don't have any more nodes left so um you can see clearly that um in this constructor we need to keep track of an index and um instead of iterating through the entire tree we can just keep a list too so um we need an index um to keep track of the current position and that would say the next would increment the index and return the value from that node has next would check to see if you add one to the index if there's still some left um so probably the best thing to do is to just take this route and we can just make a list from it so what we would do is first just traverse through the entire list the entire tree add the values to a list and then we'll just keep track of an index and just go through that so um when we call our constructor you can even you can add these objects here in this public constructor method but i can even just initialize them um right at the top so we're just going to make an array list of integers i'm just going to call it l i'm going to initialize it right here and i'm also going to have a new index and i'm going to initialize it here too i'm going to start the index off at negative 1 because i can always increment it before i call it so let's just i can come back to that but let's just see how this works out so um the first thing we're going to do is just make a list from this root and we can even make this a void because we have access to this list right here so we're just going to say void make this list and it's going to be this tree node root that we pass through um we're going to just call this recursively so for our base case we'll say if root is null just going to return and we can just traverse this so we could say first we're going to go left then we're going to add it we're going to add this root value and then we're going to go right so that is um we're just traversing it we're first going left and then we're taking the center and then we're going right that's an in order traversal so this will be adding all of our root values in order as soon as the constructor is called so um we are going to say um start off with has next first so we're just checking to see if from our index value if we add one to it is that going to be less than the size if that is true it'll return true if it is false then it's going to return false and then to get the next value we're just going to return list and we are going to get the index but before we get the index if we do the plus before that is going to increment it before we access the index so the first time the index is accessed it's going to be a zero the next time it's accessed it's going to be a one so if we do this plus beforehand then we can always access the right index we want and then also we can use the index plus one here in case has next has been called first that is going to start off at zero so we're never going to access it as negative one but in this way we're not changing the value of the index here we're just checking to see if we have this index and we add one to it is it going to be less than the size we are going to actually change the value of the index here as we move to the next one and so that is as simple as that again if you have there's different ways to um initialize objects you can just initialize them here you can also initialize them within the constructor um just initializing them here and so there's going to be access to them when we do this traversal through the tree and it's also going to be accessed here and here so that we're not passing it as a parameter we're just all accessing the same index and let me run the code and so that should work okay um let me just put this here okay thank you
Binary Search Tree Iterator
binary-search-tree-iterator
Implement the `BSTIterator` class that represents an iterator over the **[in-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))** of a binary search tree (BST): * `BSTIterator(TreeNode root)` Initializes an object of the `BSTIterator` class. The `root` of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST. * `boolean hasNext()` Returns `true` if there exists a number in the traversal to the right of the pointer, otherwise returns `false`. * `int next()` Moves the pointer to the right, then returns the number at the pointer. Notice that by initializing the pointer to a non-existent smallest number, the first call to `next()` will return the smallest element in the BST. You may assume that `next()` calls will always be valid. That is, there will be at least a next number in the in-order traversal when `next()` is called. **Example 1:** **Input** \[ "BSTIterator ", "next ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\] \[\[\[7, 3, 15, null, null, 9, 20\]\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 3, 7, true, 9, true, 15, true, 20, false\] **Explanation** BSTIterator bSTIterator = new BSTIterator(\[7, 3, 15, null, null, 9, 20\]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `0 <= Node.val <= 106` * At most `105` calls will be made to `hasNext`, and `next`. **Follow up:** * Could you implement `next()` and `hasNext()` to run in average `O(1)` time and use `O(h)` memory, where `h` is the height of the tree?
null
Stack,Tree,Design,Binary Search Tree,Binary Tree,Iterator
Medium
94,251,281,284,285,1729
81
welcome to tim's leco challenge this problem is called search and rotated sorted array 2. there is an android num sorted in non-decreasing order but not necessarily non-decreasing order but not necessarily non-decreasing order but not necessarily with distinct values before being passed to your function nums is rotated at an unknown pivot index such that the resulting index is basically rotated so if we had this array here we're going to pick a pivot index take everything from that point on this subarray and prepend it to the beginning of our original array so it looks like this at the end now given this array after the rotation and an integer target return true if target is in nums or false if it is not in gnomes so essentially uh this problem is definitely a binary search problem right and originally this was going to be part of a larger video with binary search problems but i found this problem to be particularly difficult and it's very deceptive because really the only difference from the rotated sorted array one is this distinct values allowed or disallowed so with this question here duplicates are allowed but that changes a lot of edge cases here because what we want to do is find that pivot index right but if we had duplicates allowed this becomes much more difficult to do in log n in fact it might even be impossible so for now let's just assume that everything is distinct if that was the case then what we would do is find the pivot point and then we would do a binary search using that pivot point to adjust where our midpoint is everything else would be the same so say that we want to find our pivot how do we do that well let's first start by getting our length of nums and one edge case is if n equals to 1 we just want to return whether the single number here is equal to target right and this will avoid some edge case edge cases next we want to calculate our l and r pointer our left and right pointer which would be zero and n minus one finally let's do our binary search to find the pivot so while l is less than r let's calculate the midpoint to be l plus r divided by two how are we going to find this pivot well if you remember from the original rotate distorted array problem what we want to do is check the mid and one of the ends say the right and we want to see is the mid smaller than the right because if it is that means everything's sorted properly here there'll never be a case assuming that there's no duplicates allowed where the mid is going to be larger than the index on the right and everything's stored properly that doesn't make any sense right so the pivot point has to be on the left side so if nums not mid if we find that this is smaller than nums dot r that means everything from the right mid to the right side is sorted properly so the pivot has to be on the left side so that would mean let's make r equal to mid now otherwise we're gonna make l equal to mid plus one and the reason i did it like this rather than having minus one here is there's some weird cases that happen when we have like let's say just there's two numbers left and we're going to calculate the mid right well technically the mid is going to be the same as the left and we want the right to just go to the mid we don't want to overshoot and go like uh before that right this is the pivot not the thing that comes before so that's why we did like this um and that would be it really all that comes after this would be to find our actual target so this would be zero n minus one let's do a normal binary search and we would calculate the mid to equal well first i'm going to save the pivot point here call that pivot and the mid is going to be equal to again l plus r divided by two but let's calculate the actual mid call that a mid can be equal to mid plus the pivot point and let's do a modular n in case we have to wrap around the array now everything else is the same we say if the same as any binary search we'll say if nums actual mid is equal to target then return true else if nums actual mid is let's say less than target well that means um the midpoint is less than the target so we have to search the right side so make l equal to mid plus one otherwise make r equal to mid minus one and finally if we can't find anything then we just return plus and this would work fine if everything was always distinct so let's like this example this should work fine and but once we have duplicates things get very wonky so if i were to like submit this i already know um it will not pass like so for example this case here what happens is we first check to see where the pivot point is we check uh left right middle right and we see okay everything's sorted properly here so must be on this side so now we check here and we don't know what to do like well looks like left is the same as mid we know technically we want to move to we want to move all the way to the beginning here but for this algorithm there's no way for them to really know which way to go so if i was to do something like well all right like else if let's say numbs on mid uh say that it turns out to be greater than numbers that are then we want this otherwise let's just say l minus one so like this okay and this would be kind of like we're doing binary search but if we don't know what to do we'll just decrease our left pointer or right pointer or whatever this would be right pointer right yeah but technically this works for a lot of the problems but this won't work for some certain cases like if we had say one uh let's say you won't uh we'll be good example one maybe like zero one something like this like say we had something like this well we don't know where to go right so technically we would move our right pointer back like this and then we would check again but ultimately what's going to happen is like we've kind of lost our we've kind of lost the okay so okay sorry this isn't the best example actually but basically what happens is there's going to be a lot of cases where we're going to lose the index point that we want so like um if we just we don't know which way to move should we make our right pointer left uh decrease just one or should make the left pointer increase by one because there's certain edge cases where it's not going to fly um if we want to get that index point certain things will uh fall out uh yeah so basically that's just a long way of saying it's kind of impossible to find a pivot point unless we have a while loop to just ignore the duplicates altogether so what we might do here is say all right instead of all this we'll say while l is less than r let's say look if um numbers are r minus one if it equals nums that are all right we're just going to completely ignore it okay and we'll just say r my square one i will do the same thing here let's say num l plus one this is both l we're going to increase our l here and we can do this to kind of avoid a lot of the edge cases so let's just like take this for example um and this should work and it looks like it so let's go ahead and submit that so yeah this technically works um although it's kind of not very good right because worst case scenario is going to be an o of n um but really because of those duplicates it becomes unavoidable um to find this worst case scenario now one other way we can go about this is actually not even worry about the pivot there's technically you could kind of reframe this problem because i kind of got led astray by trying to follow the very first problems approach a better way to kind of think about this is rather than having all finding the pivot point instead we can think of all the different cases that occur knowing what we know so rather than having this pivot point and then doing a binary search what we might try to do is say okay while l is less than or equal to r let's calculate the midpoint right and first thing let's first get rid of our duplicates okay so we can say get rid of our duplicates actually then calculate our midpoint and what we'll do is again try to check to see if it's sorted correctly on the right side because one of the things we can figure out pretty quickly is all right look if everything's sorted on the right side here then all we need to do is check all right is the target between nums.mid and numbs r because if it is nums.mid and numbs r because if it is nums.mid and numbs r because if it is then we know okay we gotta move to the left side here right so if we find this is the case what we can do is say all right check to see if nums.mid nums.mid nums.mid is it less than equal to target and is nums dot r is it greater or equal to target and if that's the case we know that we want to move to the right side of our array so l will equal mid plus one right yeah otherwise it's got to be on the other side so r equals mid minus 1. now otherwise see wondering if i need to do just else or do it like this but well let's see if this works we'll say else this i forgot sorry i will first check the very first thing is nums mid if this equals target then return true right else if this then this if case else the only other case that means um the pivot has to be on the left side so what we want to check is if num nums.mid is wait it's going to be on the left side pivots on the left side i'm sorry no pivot's on the right side because otherwise pivot's on the right side so then we want to check okay everything's stored on the left side so it's nums dot mid is it greater or equal to target and it's numbers.l numbers.l numbers.l less or equal to target okay that means it's got to be on the left side so r equals minus one l plus one finally if none of these fly then return to and let's see if this works i may have messed something up okay it looks like it works and there we go so i might have made this sound a lot easier but believe me this is pretty complicated and it took me a really long time to get to this solution um in fact i didn't even come up with this one i had to look up some of the solutions but my original solution that took a really long time for me to figure out and it was very deceptive because i felt like this was an easy problem um but you know sometimes you get humble because you think you know it and then start coding it out and turns out it's way more complicated than you thought so i hope this helps a little bit um don't feel bad if you don't get it because i think yeah it takes some practice to kind of understand what's going on here so all right thanks for watching my channel remember do not trust me i know nothing
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values). Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`. Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._ You must decrease the overall operation steps as much as possible. **Example 1:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 0 **Output:** true **Example 2:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 3 **Output:** false **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * `nums` is guaranteed to be rotated at some pivot. * `-104 <= target <= 104` **Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
null
Array,Binary Search
Medium
33
920
hey everyone today we are going to solve the readable question number of Music playlist so your music player contains any different songs so you want to listen to your gold songs not necessarily different during your trip to avoid your boredom you will create a playlist so that every song is played at least once a song can only be played again only if okay other songs has have been played so you are given any goal and K return the number of possible playlists that you can create since the answer can be very large return is a module 10 to the power of 9 plus 7 okay so let me explain a main point to solve this question to solve discussion I use a 3D dynamic programming and we access like a DPI and J so dbij represents the number of positive credits of length I containing exact J unique sum so in the end our goal is to return the like a playlist of lengths go and using a exact n unixon okay at first let's consider the scenario where we are the new song that hasn't been played yet to the playlist as the playlist links increase by one like from I minus 1 to I uh the number of unique song also increased by one right from J minus 1 to J so that's why for each playlist of lengths I minus 1 with J minus one unique song we can add a new song to make the playlist length I and the number of unique song J so in this scenario so how many new songs are available for us to choose from so at this point so the playlist contains J minus 1 right and since there are total of any unique song the number of new song we can add to playlist is n minus J minus one right so more precisely so n minus J Plus one right so now we are talking about the this part and then with n minus J plus one choice for a new song so the number of new playlists we can create by adding a new song is so DP I minus 1 and J minus 1 is our previous result multiply so number of new song right so that's why we keep this result to current new um like a DPI and J position okay so let's think about when we deployed all the song We already added to playlist so the playlist length increased by one from I minus 1 to I right but the number of unique songs remain the same J right so as a result for each grade list of links I minus one we stay unique songs we can increase the playlist length to I by depending The Horizon while streaming and maintaining the number of unique songs as J so in this scenario so how many previous prayer song can we choose from at this point the playlist contains the J unique songs so we can choose from these jsons however uh due to the constraint that we cannot pray a song Until other song have been prayed so we cannot choose from the song played in the last case Lots so that's why if J is greater than k so in this case the number of all the song we can replay is J minus K right so given the opportunity to select from J minus K the number of new playlists we can create by replaying the old song is DPI and J unique song multiply J minus K song so that's why if this condition is true so we added this value to um DPI and J position okay so let's write Circle first of all um in size mode equals 10 to the power of 9 plus 7. and create a DP dpra so this is a 2d array so zero so inside zero and for underscore in range and the n plus one and uh for underscore in length and the ball first one and the first of all initialized zero position so zero position with one because uh so this is a empty playlist so definitely one right so after that so this is a main point I explained in the previous section so for I in range and then from I uh from 1 to go plus one and then we use one more folder for J in French and then from one to mean and the I or and plus one so this mean I N is solved to constrain the calculation within the range where the playlist length I does not exceed the total number of songs n so this expression ensures that the greatest length I is controlled and not to go beyond n and so on for example so when attempting to create a list with larger goal so potentially exceeding the value of n so it's not feasible to include more unique songs in the playlist than the total available n songs so that's why using your mean Ming i n becomes a crucial to limit the play list length I to not surpass n and then so after that so as I explained here so DP d p I and the J equal so DB I minus 1 and J minus 1 so previous result multiply so in this case as I explained earlier so n minus J plus one and then divide mod and then next we think about the uh we declared all the song We already added to playlist but there is a condition so if J is greater than k in the case so DB I and J equal so DP I and J Plus TP I minus 1 and the J multiply minus k and then we should divide mode so after that return DP and a goal and a handsome yeah that's it so let me submitted yeah looks good and the time complexity of this solution should be order of gold multiply n so we need to iterate over two dimensional DP table size like a goal plus one by n plus one in each cell we perform constant time operation so that's why and the space complexity is also order of gold multiply n so we create a 2d array so goal multiply n 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 question
Number of Music Playlists
uncommon-words-from-two-sentences
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, goal = 3, k = 1 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\]. **Example 2:** **Input:** n = 2, goal = 3, k = 0 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\]. **Example 3:** **Input:** n = 2, goal = 3, k = 1 **Output:** 2 **Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\]. **Constraints:** * `0 <= k < n <= goal <= 100`
null
Hash Table,String
Easy
2190
46
hi guys today let's discuss the lead code question 46 permutations given an array nums of distinct integers return all possible permutations you can return the answer in any order so permutations is the arrangement of the given numbers so let's go to the example one so the example one nums is equal to 1A 2A 3 since the length of this nums is three we'll be getting three factorial arrangements so which is six so the output is 1A 2A 3 1A 3A 2 2A 1A 3 2A 3A 1 and 3A 1A 2 and 3A 2A 1 so let's go to the example two so the input nums is 0a 1 so there will be two factorial arrangements so which is two so the output is 0a 1 and 1A 0 and the example three is num is 1 and output is also one so there is only one factorial which is one Arrangement possible let's go to the constraint section as well so the constraints is nums do length uh ranges from 1 to 6 and nums of I the values can be from Min - 10 to 10 I the values can be from Min - 10 to 10 I the values can be from Min - 10 to 10 and all the integers of nums are unique so there are no Corner cases to this so there exists at least uh nums do length will be at least one and it is less than 6 less than or equal to 6 and nums is from - 10 to 10 and they're all unique from - 10 to 10 and they're all unique from - 10 to 10 and they're all unique so we need not handle any of the corner cases I hope it is very clear from this question description let's go into the explanation part of it for the purpose of explanation let's consider the nums to be 1A 2A 3 so with this 1 comma 2 comma 3 let's look at the recursion tree and how we are going to arrive at all the permutations so from this we'll be getting three branches out of which the first branch is going to be 1 and 2 comma 3 so here 1 represents let's assume this one as a permutation and 2A 3 as a remainder of the nums so which means that all the nums are not utilized and the first one is going to be the permutation and the second branch is going to be 2 and 1A 3 and the third branch is going to be 3 and 1A 2 now let's look at the recursion tree for the next level so where we are going to pass uh we are going to split 2 comma 3 further and we are going to arrive at two more branches and the two branches that we arrive at are 1A 2 and 3 and 1A 3 and 2 so these two represents the first one 1A 2 and 1A 3 represents the permutation and the remainder of nums is 3 and two let's look at the different branches that we are going to arrive from 2 and 1A 3 so we are going to arrive at 2 comma 1 and 3 and 2 comma 3 and 1 let's look at the BR uh third branch that is 3 and 1 comma 2 so we are going to arrive at 3A 1 and 2 and 3A 2 and 1 so from this level we can see the remainder of nums is just the length of it is just one so which means that we are reaching the end of this recursion tree so the last step is going to be the first one we are going to get a combination 1A 2 comma 3 and for the next one we are going to get a combin we are going to get a permutation of 1A 3A 2 and for the next one we are going to get a permutation of 2A 1A 3 and for the next one we are going to get a permutation of 2 comma 3A 1 and for the next one we are going to get a permutation of 3A 1A 2 and for the last one we are going to get a permutation of 3 comma 2 comma 1 finally we are going to store all of these things yeah and finally we'll be arriving at the uh required output I hope it is very clear from this explanation let's go into the code coding part of it let's start by creating an empty permutations list that is going to store the results it is going to be an empty list then we are going to create a helper function in order to uh Aid with this permutations so we are going to store two arguments inside this so the first argument is going to be the permutation and the next argument is going to be the remainder of nums if the length of permutation equal to length of nums so which means that we have used all the numbers or integers that are provided in the nums in the permutation so which means that we have formed a permutation and we can store it in the permutations list so we are going to append permutations do append we are going to append this permutation that we have computed else if the length is not equal which means that there is the remainder underscore nums list is uh not empty and which means that there are further elements that needs to be added to this permutation so in that case we are going to Loop through this remainder nums for I in range of length of remainder uncore nums and we are going to call this helper function on the permutation plus remainder underscore nums of I we are going to add this particular uh I index value of the remainder nums to this permutation and then we are going to uh we are going to just uh reduce the size of this remainder underscore nums so that is going to be remainder underscore nums of we are going to just exclude this I value from it so it is going to be remainder underscore nums here it will be I + 1 okay yeah I think it that's it we are going to call this helper function initially the permutation is going to be an empty list and uh remainder nums is going to be nums and finally we are going to return the permutations yeah I hope we are done let's quickly run the code yeah can only concatenate uh list not into to list yeah I made a mistake so here this is going to be an integer value so we are going to add this one also in the form of a list now let's quickly run the code yeah uh let's quickly submit it as well yeah it is accepted hope you like the explanation for more such videos please subscribe to my channel thank you
Permutations
permutations
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Example 2:** **Input:** nums = \[0,1\] **Output:** \[\[0,1\],\[1,0\]\] **Example 3:** **Input:** nums = \[1\] **Output:** \[\[1\]\] **Constraints:** * `1 <= nums.length <= 6` * `-10 <= nums[i] <= 10` * All the integers of `nums` are **unique**.
null
Array,Backtracking
Medium
31,47,60,77
1,816
hello uh hello to all and welcome to my youtube channel today we will be going to solve uh another lead code problem for problem number 18 16 the problem name is truncate sentence so let's just read the problem sentence is a list of words that is separated by single space with no leading or training spaces each of the words consists of only uppercase and lowercase english letter no punctuation basically here they are defining what is sentence for example this hello world a sentence uh is a list of what that contains a space or it can be lowercase or uppercase with no punctuation mark so basically we are given a sentence and an integer k we want to create a truncate as such that it only contains first k words written s after truncating it so there is the example so the sentence is hello how are you contestant so k equals to four so it means that after uh we have to uh con we have to return this hello our how are you string because uh the first four words are hello how are you so similarly the ks4 and what is the solution to this problem so what is the solution to is the uh output of this input okay so uh and this is another example that chopper is not a key so k equals to five so one two three four five so the whole sentence the first five words of the sentence is already there so we return this edge okay so i think the problem is very clear to you so let's just dive into four before driving into code i will give you what was the logic behind this problem so what we do we first traverse the whole string okay and we are given k so we decrementing uh k uh from if uh suppose if we find a space so decrement our k okay and then second space then third space and then fourth space after we hit our fourth space and then k we decrementing our k then if k becomes to zero we return that substring of s okay so i think the logic is clear to you if not uh in code it will be very clear to you let's just type into code so i less than s dot a plus so first we travel through the string so if plus i first equals to a space and minus k equals to zero so we're decrementing k we are pre-decrementing our key pre-decrementing our key pre-decrementing our key because if we did not do this so the space uh will gonna go here like in this case um suppose that just k s equals to 1 so our answer would be only hello so the k we are pre decrementing so k equals to 0 and the condition will be true and so we written that substitution so ok so we return uh s dot sub str so it is inbuilt function that is returned in subreddit r in c plus written from 0 to i that is including 0 and excluding i okay and after that we return our s okay let's just submit our code yeah you could see that the test case is accepted our output matches let us submit our code i hope everything will be correct okay so now it is run time is zero million millisecond faster energy solution let's just try and code uh this code so first time uh when we traverse to this si does not equal to space aside s i equal to space here then k decrement it's pre-decremented ka value is four so it's pre-decremented ka value is four so it's pre-decremented ka value is four so three doesn't equal to zero so redundant written here then k equal goes to this then this index would be then k equals to 2 and here k equals to 1 and here k equals to 0 so uh we saw we return the sub we return the substring from 0 index to this index like after you touch this space so written that substring i hope this is clear for you and if you any doubt you can comment i would love to help you thank you very much
Truncate Sentence
lowest-common-ancestor-of-a-binary-tree-iv
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a sentence `s`​​​​​​ and an integer `k`​​​​​​. You want to **truncate** `s`​​​​​​ such that it contains only the **first** `k`​​​​​​ words. Return `s`​​​​_​​ after **truncating** it._ **Example 1:** **Input:** s = "Hello how are you Contestant ", k = 4 **Output:** "Hello how are you " **Explanation:** The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\]. The first 4 words are \[ "Hello ", "how ", "are ", "you "\]. Hence, you should return "Hello how are you ". **Example 2:** **Input:** s = "What is the solution to this problem ", k = 4 **Output:** "What is the solution " **Explanation:** The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\]. The first 4 words are \[ "What ", "is ", "the ", "solution "\]. Hence, you should return "What is the solution ". **Example 3:** **Input:** s = "chopper is not a tanuki ", k = 5 **Output:** "chopper is not a tanuki " **Constraints:** * `1 <= s.length <= 500` * `k` is in the range `[1, the number of words in s]`. * `s` consist of only lowercase and uppercase English letters and spaces. * The words in `s` are separated by a single space. * There are no leading or trailing spaces.
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Tree,Depth-First Search,Binary Tree
Medium
235,236,1218,1780,1790,1816
1,887
hey everyone today we are going to solve the reduction operations to make the array elements equal okay so first of all look at this so I always think about the solutions with a small and simple input so let's focus on one two in this case if we uh reduce one from two so we will get the output right in this case one time and how about one to three so one time 4 two and two * 4 three right in time 4 two and two * 4 three right in time 4 two and two * 4 three right in this case three and how about 1 2 3 four so one time for two * 4 three and three time for two * 4 three and three time for two * 4 three and three times 4 four so total should be 1 2 three and six so how about the 1 2 3 four five one time for two times for three times 4 four and the four times four five right so 1 2 3 4 5 and the total 10 operation so did you notice something so seems like we have a solution pattern so let's focus on 1 2 3 4 5 and let me put index number so 0 1 2 3 4 so output is 10 right so if we uh add all index number so we will get so one 2 3 four so total 10 right so it's equal to Output so point is the number of operations is equal to cumulative index numbers and it seems like a sorting the input array makes problem easy so more precisely sorting allows us to compare numbers that are cross in magnitude with each other okay so next case is what if we have the same numbers in input array so like one two three so in this case reduce one time and two times right so total four times and as I explained earlier so we just add index number so one two three so total six so seems like we need to calculate number of operations in this case right so how can you simplify it so let's go back to the like one two 3 four five and break the problem into small parts and uh this question is reduction operations so let's think about the output from large two small number so we reverse input array so that's why 5 4 3 2 1 okay so first of all let's focus on this part and try to make all numbers four in this case just uh we need one only one operation right so make this five four and one operation and let's focus on this part and try to make all numbers three so in this case uh we need two operations right so this four will be three and this four um will be three and the total operation is now three and then next let's focus on this part and I try to make all numbers two so in this case we need three times right so this two this three will be two and now total operation is six and then so let's focus on everything and I try to make all numbers one so in that case we need to we need four operations right so this one this two will be one and then total operation is now 10 now all numbers are one then finish so now we sort and the reverse input array but we still have the same output so we just add all index numbers like 1 2 3 4 so total 10 right it's equal to Output okay so let's sort and reverse this input array like 3 two one but output still four right and let's it one by one and basically we compare current number and the previous number so that's why we start from index one to prevent out of bounds so we start from index one and at first we compare index zero and index one so in this case we need a one operation right so because this is a index one so that's why add one to our total operation and I move next so now index zero is two and the current number is two and the previous number also two so they are same in that case we don't do anything and then move next so we find the one and the previous number is two so um in this case we need to add three right and the total four so somebody wondering are you sure this is correct yeah actually it's correct so for this three time should be so we reduce um one here and one here three times right and now all are one so looks good that's why output is four it's same as this four right so why this happen that's because between any two numbers we reduce large number once at most even if we skip reduction when we find the same numbers uh index number will be increased by one if we move next so that is total number of rest of large same number so that's why when we find a small number in later part we can add index number including number of reduction of the same numbers okay so let's check this example quickly so we have four five and one and we start from index one so first of all we skip right because the current number and previous numbers are same and then move next so we skip because uh same reason five and then move next also skip right so same reason five and then we is the last index and uh so look at this skip part so even if we skip reduction index number is increased by one right so when we find a small number in data part so last index number current index number is four is equal to number of reduction of the same number so which is five so now index number is four and the number of five is also four so that's why uh we can add current index number to Output so that's why in this case output is four so add four for index Z One 2 3 so that we can make all numbers one yeah that is a basic idea to solve this question so with being said let's get into the code okay so let's WR a code first of all we sort and reverse input array so nums and sort and reverse equal two and then um so let's say operations so this is a return value initial be zero and uh we need to like a PR uh unique so start with uh index zero number and then uh for I in range we start from index one and uh until RS of nums and if current number equal So Pro unique in that case um we just uh continue if not the case if nums and I so current number is less than PR unique so it's time to add operation so just very simple so operations plus equal index number and then after that update PR um unique equal current number yeah that's it after that just return operations yeah so let me submit it yeah let's get and the time complexity of this soltion should be order of n because of Sal algorithm and the space complexity is I think a order of log n or o n so depends on language you use because sort algorithm needs some extra space 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 question
Reduction Operations to Make the Array Elements Equal
minimum-degree-of-a-connected-trio-in-a-graph
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps: 1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`. 2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`. 3. Reduce `nums[i]` to `nextLargest`. Return _the number of operations to make all elements in_ `nums` _equal_. **Example 1:** **Input:** nums = \[5,1,3\] **Output:** 3 **Explanation:** It takes 3 operations to make all elements in nums equal: 1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\]. 2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\]. 3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\]. **Example 2:** **Input:** nums = \[1,1,1\] **Output:** 0 **Explanation:** All elements in nums are already equal. **Example 3:** **Input:** nums = \[1,1,2,2,3\] **Output:** 4 **Explanation:** It takes 4 operations to make all elements in nums equal: 1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\]. 2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\]. 3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\]. 4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\]. **Constraints:** * `1 <= nums.length <= 5 * 104` * `1 <= nums[i] <= 5 * 104`
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
Graph
Hard
null
129
hello coders today we are going to solve another lead for daily challenge and the question name is time and 5 so the numbers that comes out to base 495 right a girl is and we have to calculate the overall sum so the first number is 495 second number is 4 9 and well right this is the second part from root to sleep node so it is 490 1. and third part is 4 and 0 which is 40. so since which is 1 0 and 2 X2 this is the overall sum so basic ideas and we will calculate the overall spring value commit to sum it up to our ultimate sum so let's put this I have already folded it I'll hold it again for you guys so many happy example Global variables and um five two initially and conditions then what we have to do T left again tomorrow number into 10 plus them look at every step what we have to do like agarham or again 40. 9 right we have to multiply it by 10 right 49 into 10 right and then what we have to do we have to add our current value is we have to multiply the above number with 10 and add our current value so this is and we have to edit our ultimate sum which is our sum so we will add this one and this is our final step we will return so this was our base condition let's write this project part because the part is very simple other natural evaluate the left to Traverse is F and our somewhat what will be our sum right we have to multiply it by 10 right this is what we have to pass on and this is for the left we will do the same thing for me type if it is not null then what we will do we will simply call for root dot right and you will do the same thing number 10 plus to install okay and to the test cases are working fine let's give it a submit it is also working fine so thanks for watching I hope you guys find this problem and thank you for watching please do subscribe my channel
Sum Root to Leaf Numbers
sum-root-to-leaf-numbers
You are given the `root` of a binary tree containing digits from `0` to `9` only. Each root-to-leaf path in the tree represents a number. * For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`. Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer. A **leaf** node is a node with no children. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 25 **Explanation:** The root-to-leaf path `1->2` represents the number `12`. The root-to-leaf path `1->3` represents the number `13`. Therefore, sum = 12 + 13 = `25`. **Example 2:** **Input:** root = \[4,9,0,5,1\] **Output:** 1026 **Explanation:** The root-to-leaf path `4->9->5` represents the number 495. The root-to-leaf path `4->9->1` represents the number 491. The root-to-leaf path `4->0` represents the number 40. Therefore, sum = 495 + 491 + 40 = `1026`. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 9` * The depth of the tree will not exceed `10`.
null
Tree,Depth-First Search,Binary Tree
Medium
112,124,1030
795
Hello Everyone Suggest This Solving Number Of But Maximum And Used As A Valid Which Change To Question And Give Positive Enters Into Positive Winters Left And Right The Number Of Class Ninth Subscribe Maximum Element In This Loot Mein Strike Enters Into All The Element Lose Weight Chandra Equal Her Ones 300 Flats Considered The First Servants l22 Is Equal To Left And Electronics Students And Lose Nickel To Right Tubelight Subscribe Now To 151 Th Maximum Elements To And Again Its Prey Condition Does All Subscribe Now To 4 * 4 Element Does All Subscribe Now To 4 * 4 Element Does All Subscribe Now To 4 * 4 Element Is 4 Greater Than There Right When You Will Not Be Part Of The Solution In Fact All The Best Suvichar Best Food 10000 Solution Subscribe Maximum Element 3D Song Serial Element Which Is The First Indian To Three To According Remake This Condition And Where Are Electric Schezwan Sauce 309 Points Review Simple And The First Visit To A Solution Is Amazing That You Will Find Some Elements And You Will Like And Subscribe Button Solution Is Not Accepted And Very Time Consuming Solution Subscribe To 100MB Left Images from Lord of Hadf Thank You Too of Annually Suresh Yadav Candidate 116 Considering Example and Being Given This Disorganized Are Left Samsung Galaxy S8 Android Apps Something Say 600 800 What Will You Find Out What Are the Possible subscribe and subscribe this Video subscribe and subscribe the Channel subscribe and Problem Disagreement Will Not Be Responsible For Maxim Element 123 Body For The Amazing Brightness Element Should Discard 137 Kinds Of Break Point Lost Let's Get Unlike Most Elements Of Break Point A Lawless Moot 504 505 Alone In This Line Between Left Android needle to shift valid start for information and in fact reach solution subscribe and left and right vijay phase solution element ko subscribe and subscribe the 12345 ab samjha na subscribe Video subscribe newly appointed subscribe this Video subscribe our hui hindi film one step 1625 So let's check the element which loot and element 3636 Individual for the individual will contribute to and subscribe the Channel subscribe and subscribe this Hair starting position for 6th that this holiday 786 That there sure can more solution for this channel subscribe elements Which loop is certain to be defeated 2868 Earlier tomorrow morning Mirchi will define hidden talents of her elements of elements which lies between left and right talents of the elements which is smaller than their life in these letter head elements and position for its subscribed position of wealth And Values subscribe to the Page if you liked The Video then subscribe to the Page Question 2015 Solution Please Subscribe And Solution Counter This is the Value subscribe The Channel subscribe button se withdrawal 1906 End Elements and Share And subscribe sweater delivery starved for do and on your friend ips so no isi encounter per element which number five subscribe is name white is greater than enough power to love but is lesson equal to a phone number 10 10v stabilizer radiant acid elements total hits Plus 2 And Nor Will Also Avoid Taxes Witch Tales Us Jhaloo Film Not A Love Story Vikram 0n Earth Total Account Fifty Plus Two Hai A Sudden Is The Best One Ad Hit Super Difficult All Subscribe 3651 Content Will Be Id Don't Forget To Subscribe To main abhi left his last time name safai danveer vipin short tricks painter know what do subscribe video subscribe to that not only but it is a nice and knowledge elements of button right because dhawan condition is in that case and head 2009 daughters will all the bases The main issue of 'Of This Time 2009 daughters will all the bases The main issue of 'Of This Time 2009 daughters will all the bases The main issue of 'Of This Time Again' which is Lips Returns Song is ' Again' which is Lips Returns Song is ' Again' which is Lips Returns Song is ' Chief Manch Hai Hua Hai A British Province in this eve a son that a download speed when scooter do and loot online according to and love has been looted that this is only the primary education received, then thank you. You Have Destroyed A Number Of Forever Mehboob Maximum Hai
Number of Subarrays with Bounded Maximum
k-th-symbol-in-grammar
Given an integer array `nums` and two integers `left` and `right`, return _the number of contiguous non-empty **subarrays** such that the value of the maximum array element in that subarray is in the range_ `[left, right]`. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,1,4,3\], left = 2, right = 3 **Output:** 3 **Explanation:** There are three subarrays that meet the requirements: \[2\], \[2, 1\], \[3\]. **Example 2:** **Input:** nums = \[2,9,2,5,6\], left = 2, right = 8 **Output:** 7 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `0 <= left <= right <= 109`
Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?
Math,Bit Manipulation,Recursion
Medium
null
60
Hello hello guys welcome back to tech division in this video you will see politicians sequence problem specific from list to date 24th june challenge so let's not look at the problem statement in this problem where given interview k when is the number of units and want to No and will not give me the information subscribe to the Page if you liked The Video then subscribe to the detention Dissolve in ascending order descending order to this permission to find the subscription 110 is inter problem no very simple approach to solve this problem is by using Here react and by using jquery function but using recjan you will have to create all possible permissions starting from the earth is very costly library functions will be doing the same thing you will be computing every politician and you will be selected candid total time complexity of problems Which will not be time complexity and you to the time complexity of mathematics in solving problems will be solved by using pattern letters in the door and values ​​to pattern letters in the door and values ​​to pattern letters in the door and values ​​to form agenda and person 125 Show viewers welcome to three way can create a total of respect to Politicians And Have Already Known To Find The Fifth Edition To This Competition Will Not Rise In This Video You Can See The Question Three Idiots Should Be Possible That We Can Just Feel to the Video then subscribe to the Page if you liked The Video then subscribe to the who is the second two values ​​of having two is the second two values ​​of having two is the second two values ​​of having two during post graduate and last values ​​are during post graduate and last values ​​are during post graduate and last values ​​are having three fatty acids and divided into subscribe fennel 125 what will be the uses of the question is valid only you can be divided into five plus one which will be very simple To Find In Which Will Subscribe Fifteen Days Third Box Will Take Place At North Block Number Three To 10 The Video then subscribe to the Page if you liked The Video then subscribe to the Is Present In Just A Single Number Subscribe Now To Receive New Subscribe button for updates You have already subscribed Elements from Thursday Subscribe That Saumya Total number of deductions will be 400 Value of vaginas will be equal to one 90 Only request to accept this You can Seervi and the temple Subscribe to Jewelery Now You Can See That This Looking and Disposed Digit Purpose Will Be Divided Into Four Boxes 04096 Servy Boxes Were Due to Be a Mother and Father Video subscribe and subscribe the Channel Please subscribe and subscribe the Channel in Order to Find No Place Which Will Not Be Amazed At Will Robber The Factorial Of That Would Request You To Give Effect To Real Value Message The Black Eyes Will Be Stopped To Real Look Soft And Packing The Digit Tweet - 151 - 24 - 2nd I Am I Divided Tweet - 151 - 24 - 2nd I Am I Divided Tweet - 151 - 24 - 2nd I Am I Divided Into The Subscribe The Amazing You can find out what is the Veer 102 subscribe to the Main work in digits are will be keeping track of all districts which you want to include in order to form and number in this case and request for that they already know the Best All The Digit Subha Unique And Request For The Number From 124 Ok 100 Grams Digit Swapping Is Channel Number And Will Be Removed From Which Are The Number You Will Not And You Want To Do The Current Answer Which Will Be Removed From This Is It Will update you should not solved example and subscribe question because were required to front four digit number ok so will start feeling sad significant digit so what will be the result according to the calculations you can see the subscribe The Amazing - 1the subscribe The Amazing - 1the subscribe The Amazing - 1the subscribe my channel subscribe to the Page if you liked The Video then subscribe 102 Avelu Index Renu Indicator and Number will be present in the second Box Office Number Representative will be the Sid 12345 which will consider what is the Date of Birth York Position Subscribe Rafiq But Will Be Removed From Doing This Is To Updates And Subscribe Elements Of Elements Is Dead So How Many Elements Do We Need To Skip Actually Need To Skip The Number Of Balram Kumar Multiplied By The Number Of Elements In Which of this is the number of boxes and elements in What is the meaning of this is the number of side effects to the app and minus one which is nothing but the soul from which is the value of subscribe to the Page if you liked The Video then subscribe to the Page if you liked The Video * Size of two numbers should be found actually known before * Size of two numbers should be found actually known before * Size of two numbers should be found actually known before making the call OK will be implemented properly or you can avoid making person indicating number digit already have already The Video then subscribe to the Page if you liked The Video then subscribe to the Page Kids Value Dowry Nothing But Dhal Minus One Factorial Soayenge Us Person 210 More Okay So After Finding And What Will You Need To Withdraw Its True Value 2025 Video then subscribe to the Page if you liked The Video then subscribe to The Amazing - Video then subscribe to The Amazing - Video then subscribe to The Amazing - 142 That Your Convenience Will Be Equal To So Actually Be Appointed As Most Significant Tips Dene 2012 6021 So When You Get This To The You Will Consider That Will Be Block Number 2 And Sons Were Taking This Blog from 0210 Free The Significance Did n't Do So This Is The Richest Man Ever You Are Facing In The Element Which Will Be I Am If You Will Be Able To Understand That You Are Not Doing So Hello Friends Values ​​080 Value Wave Raw Hello Friends Values ​​080 Value Wave Raw Hello Friends Values ​​080 Value Wave Raw One Will Remind You Will Update And Will Be Updated Daily With Appointed - 21806 Coming From Updated Daily With Appointed - 21806 Coming From Updated Daily With Appointed - 21806 Coming From This Channel Subscribe Next Time When You To Two To Check Airtel - 101 Ways To Reduce It's Worse Tell Again Will Move to the next index in the call will be left with only one digit and will by the way update and K values ​​Gourmet - Factorial Nuvve values ​​Gourmet - Factorial Nuvve values ​​Gourmet - Factorial Nuvve This Process Will Just Avoid Number One Can See You But You Can Read and Write Clear Subscribe Veer Quarter Kuching All the digits in and all the digits will call you solve function will be storing result in directions Answer and will return the answer Sudhir Vashistha and Yash Lee The Amazing 3.5 Video Subscribe Veervar subscribe and subscribe the two and Answer Will REMOVE IT FROM THE PRESIDENT CAN BE USED ONLY AFTER DOING THIS WILL UPDATE YOU WILL GO ON RECORD 110 DAYS TO DETAIL LITTLE BIT MATHEMATICAL DUTY TO LORD SHIVA AND ONLY YOU WILL BE ABLE TO UNDERSTAND ONLY SO IFIN HERE PLEASE SHARE WITH EVERYONE Can Benefit From Like Share And Subscribe Our Channel Like This Video
Permutation Sequence
permutation-sequence
The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`: 1. `"123 "` 2. `"132 "` 3. `"213 "` 4. `"231 "` 5. `"312 "` 6. `"321 "` Given `n` and `k`, return the `kth` permutation sequence. **Example 1:** **Input:** n = 3, k = 3 **Output:** "213" **Example 2:** **Input:** n = 4, k = 9 **Output:** "2314" **Example 3:** **Input:** n = 3, k = 1 **Output:** "123" **Constraints:** * `1 <= n <= 9` * `1 <= k <= n!`
null
Math,Recursion
Hard
31,46
920
Hello friends today let's solve number of music playlists um so we are given integer and it means we have a different sums and we want to listen to Go songs but they are not necessarily different we must make sure some can only be played again after chaos songs have been played if you look at this example you will wonder why we don't have a playlist as one two one because we can play one again after K sums but the issue is that we must make sure every song is played at least once so in this case since the lens of this goal list is three so we must play older and songs once so there is no duplicate songs in one playlist in this example we can play the Samsung just continuously because the case zero so we will have one two so how do you solve this problem um if you notice it says the answer can be very large we can return it a module this number so it indicates we can solve it via dynamic programming and the how to solve Dynamic program question we need the initial dilation and the state transition function how to Transit um to current state via the price dates that's what we need to figure out so in this question what do we want to return is like we want to play goal songs and we have in different zones how many playlists so we can just easily represent it as an integer array right so it means the total waste to oh or a playlist we have we either to play Go songs and we have a different songs so in the end we just return the DP goal and so why I write go before and it's because we need to Transit the states right so in that case I mean I can understand it either it's like the Outer Loop is the number of songs we want to contain in the list let's record them go and then I increment the four into J equal to one J less or equal than and J plus so basically it's the same order as this array we can understand it either it's like uh no matter how many different songs we have we can usually return DP I something but when we have more different songs uh we just uh like DP go if we have one different song we can have some ways and if we have two different so we can have more ways so I think this order makes sense so how do you trans Transit states there will be dpij like currently we will have some just increment it well what is the current ways if the is we are currently J right we have J different songs if the current additive sum is different from all the songs we already included then it would be elements one J minus one right because it's like current AJ is a new song total new song so it would times a minus J plus one so how to understand it is like if J equals to 2 while we have three different zones so in the ply wrong prior round we played one song from one out of three songs right a lot of three songs so now I have two ways to I mean I have two options right two options but things for the prior round I already chose one song so it's a three right and for either one I have two options now so it's times not a plus and another way is like um the current The Chosen sum is the one I already chose so it would have the same J because this current zone is not a new song so what I should at times well it depends on whether I can choose the Samsung once it's like I cannot choose then zero but why I would say I can choose it means J minus K should be greater than zero like here if k equal to 2. like I need to play a song after another two songs then now it's zero I cannot actually have more options here but if K is one then I can actually play a new song right since 2 minus one equal to one so I can play and um yeah I can already play an I can already play um if J equal to 2 k equal to one I can play a new song after one song oh so actually I just have the of like the opportunity I minus one thing but if k equal to 3 I can play it the same so after three other songs but since J is less than K I certainly cannot play so it's zero so this means the current song is a totally new song from other songs so we no matter what Germans want in the pride rounds we should adjust add up the options but if the song already played before we need to choose to check the weather is after okay other songs and then we need a d p i j um module mode so we needed the mold give or two um and the things either can make larger than Inked so we just write long in the end we convert it to unit and also the initialization the dp0 equal to one it means if we have a difference of zero difference of and we want to make at least have zero something we have one option and we'll find that things we only use are minus one the prime row so we don't necessarily need to save this information so we just removed it so we just remove it well since now this DP J can represent other rows so we just use the same information not increment okay so now Mojo so but actually we just remove this row okay the only issue is like the initialization it means if we have a different sums we have one way to make a list right since we don't have any real songs but if here our goal is more than one song then if we only have one different song it means we actually only have one zero weight right because previously it means uh like we have zero different song but if our goal is also zero then we have one way but here it means we have more goals but still if we have zero different songs then we only have zero ways not one way I think that would be thank you uh oh sorry one important mistake like because if we remove that row we actually need to reverse the direction of the inner loop if you are familiar with knapsack you should know this yeah just don't need to remove reverse the direction okay thank you for watching see you next time
Number of Music Playlists
uncommon-words-from-two-sentences
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, goal = 3, k = 1 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\]. **Example 2:** **Input:** n = 2, goal = 3, k = 0 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\]. **Example 3:** **Input:** n = 2, goal = 3, k = 1 **Output:** 2 **Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\]. **Constraints:** * `0 <= k < n <= goal <= 100`
null
Hash Table,String
Easy
2190
1,605
hello and welcome so today we'll be discussing one of the very important problem of uh lead code which is a problem number one six zero five and the problem is find valid matrix given row and column sum so what you have given row sum and column sum and you have to find the valid matrix so what this problem is all about so let me read this problem for you so you are given a two arrays you have given a two errors one is known as row sum and another is known as columns i'm fine of a non-negative as columns i'm fine of a non-negative as columns i'm fine of a non-negative integers fine these are actually a positive integers fine of a non-negative positive integers fine of a non-negative positive integers fine of a non-negative integers where non-negative integers where non-negative integers where non-negative integers means where 0 is included so you have to keep this in my non-negative means zero and in my non-negative means zero and in my non-negative means zero and positive fine okay so where a row sum i is the sum of element of i-th row that is the sum of element of i-th row that is the sum of element of i-th row that is a row sum i if i say about any row then row sum i is containing the sum of element of ith row similarly column sum j is the sum of the element of jth column of a 2d matrix so what it is all about i'll be explaining by taking an example that will become easy for you to understand okay fine in other words you do not know the element of the matrix but you do know the sum of each row and column that is you don't know what our element of a matter if i say this is a 2 cross this is a matrix 2d matrix so what actually you know the sum of rows you know the sum of columns but you don't know what this elements are you actually don't know what this element are suppose if this is a 3 cross 3 matrix so you know what is the sum of this row you know the sum of this column some of these columns some of this column but you actually don't know what comes here and here fine so this is what actually the problem is let me read further for you now comes the question that find any matrix non-negative that find any matrix non-negative that find any matrix non-negative integer size row sum in length into column sum length that is suppose row sum length is uh 3 column sum length is 3 fine that you have to find 3 cross 3 matrix your job is to find three cross three matrix then matrix should have an element fine that's satisfied which actually satisfied roof sum and column sum that is you have to written a 2d array representing any matrix that fulfills the requirement it is guaranteed very important at least one matrix that fulfills that so there will be existing one metric it will not be like something like that where no such metrics exist so before no if i will not take the example it will become tough for you to understand so let me take one example from this question itself so that it becomes easy for you to understand what i'm talking about so let's take one example now i'm taking this example so let me explain you about using this example so fine okay yes so here you have given row sum that is row sum is 5 7 and 10 and then column sum is 8 6 8. so let me make one matrix for you okay fine but it is given row sum is given 5 then seven and then ten fine okay and then column sum is given eight six and eight now your job is to find this element this fine so your job is to find these elements let me change the color of my fan so that it becomes easy for you to understand now how will i able to judge i know the sum of these all element is 5 i know that sum of all these element of a column is eight but what this element will have so the method there could be n number of methods fine so the method which i'm just going to discuss with you right now is one of the easiest method fine so what how to do how to solve this question is that first initialize the entire matrix with zero element so let me rub all these things fine so let's initialize all the matrix with zero element so i have initialized the entire matrix with 0th value fine with 0 okay now you have to start the matrix suppose i is representing the row and j is representing the column the length of row sum is 3 the length of column sum is 3 that is you have to build a 3 cross 3 matrix fine okay now what to do from the pointer i to the pointer j find the minimum value among 2 so out of five okay so there are two pointers i and j fine so there are two pointers i and j find the minimum among two so out of five and eight which is minimum five so change here make it five now reduce the selected element from both i and j so if you reduce five from five it will become zero five and if you reduce five from eight it will become 3 fine okay now the parameter which becomes 0 will no will be increased since i is a what you can say is a pointer which whose value becomes zero so it will increase from this position to this position fine so where i am right now i'm at this position fine because j is at this position i is at this position now find minimum between the two that is seven and three so seven which is minimum seven and three is minimum so finally three we will replace this with three now reduce the selected value so if you reduce the selected value it will become zero and it will become what four if you reduce three from seven it will become four now which becomes zero i or j becomes zero so i'll increment j will come here so finally i would at which position here so among four and six which is minimum four so i'll replace it with four fine okay now i'll replace and reduce four from both i and j so i when i reduce this four will become zero and the six will become two so the which pointer has become zero i so i'll increment i will point here j will remain at its own position now where i am right now here fine so among 10 and 2 which is minimum 2 is minimum so i'll replace it with 2 i'll reduce 2 from both i and j it will become 8 and it will become 0 since j has become zero it will get incremented fine it will come here now where i'm actually pointing i'm pointing here so out of i and j which is minimum both are eight it could be a ticket it can be any eight fine so i'll replace it with eight now both become zero now only to do that something fine so the both become zero so finally what you have no got the matrix so uh have you actually achieved the correct matrix now let me remove all those things five eight six and eight fine okay then eight six and eight let me remove this okay then fine so this is five fine okay so now see have you got the answer so the sum of this row is 5 very right fine the sum of this row is 5 very correct the sum of this column is 5 3 8 correct the sum of this column is 6 very correct the sum of this row is 7 very correct fine so actually you have got the answer so this is actually the method this is the method which you have to apply for solving this question which is find the valid matrix now you might be thinking that your answer is 5 0 3 4 0 and then 0 2 8 list of list i'm talking of python fine it's a list of lists so you have got this matrix you might be thinking that oh i'm not getting the same answer this answer is 0 5 0 my answer is 5 double 0 so there could be a number of ways to solve this question i gave you one way so i'll be also discussing how they have solved how they have given you this input and output so let us build first code that will become easy for you to understand so let's build the code so that you can understand what this problem is all about fine so okay let's start with the code uh so i'm taking python so i'm building my code in python itself so let's have two variable one is rows fine and let's say another is columns c o l s columns you can take any rows and column whatever you want you can take fine and let this be equal to when length of you have what you have given row sum if i'm not talking you have given a row sum yes and you have given column sum let me show you okay see this so you have given one row sum and then column sum and this length is the length of this so length of row sum fine and then it comes calls length of call some c o l you have to use the same variable name as it is given see you can see row sum and column sum you cannot change you are not allowed to change anything like that fine so you have initialized both the variable rho sum and column sum with value of length of row sum and length of columns of fine then comes next thing uh then next part is okay you have to let's take one matrix mat and now what i'll do i'll be initializing this matrix with all element having zero elements so how list comprehension is used for okay for j n for j in where j is representing suppose column so for j in range calls cols calls fine for jane calls then after that it comes for i in the range i in range rows r over w s i wonder why this is red in color i wonder okay fine yeah i got the point because of indentation problem so uh what is the meaning of this line this is actually a uh list comprehension in python so what am i doing is that you know what you actually do for suppose i'm taking an example of c language what for rows and column what do you do for i uh you one you runs the loop of i for no for number of rows then you run for j in the neurons for columns and then view what you do matrix suppose r matrix is uh then you initialize this with zero so this is what you do in c language so what you all can do in number of lines you can do by list comprehension in a single line so what am i doing over here is that i'm using a j loop for columns i'm using loop i for a number of rows and for all those values i'm initializing it with 0 fine so nothing is something very different which i'm doing over here it's all very common thing fine so let me proceed further to build the code then okay then let's so what we did right now we have created two rows and columns and initialized with the length of rows and column and i have initialized on matrix by the name of mat and the value is now having zero all the element now i have two variables i and j you can take any variable and let's initialize it again with zero so i'm having two variable i and j and i'm initializing it value zero now am i taking a loop while why while i is less than rows r o w s and very important and g is less than column c o l s columns fine so what am i doing is here is that my till when i have to move till my i and j are less than rows and columns this is a common sense very common sense what next thing then we have to find what matrix i and j is what is actually a minimum of rows very important you might be thinking that so when we have taken one matrix let me so let me make one matrix for you then what was that i don't know i don't exactly remember what was the 5 16 i if i'm not wrong yes it was 5 6 10 and it was 8 uh 8 6 10 or something like that i don't know do not exactly remember so what actually you was doing so you was taking minimum from these no fine so this element matrix i say this is 0 will be what minimum of 2 so this matrix 0 will be minimum of row of i that is this and this fine okay so uh let me move again further fine okay so i'm sorry for this where i was actually yes i was here okay then what i have to do is that then i have to reduce that element fine reduce that number those sum of i what it will become minus equal to what you have it will become mat of i comma j the element which you have selected for that matrix reduce that element from what row sum and reduce that same element from columnism also this is what we did we are doing now is that reduce same thing from column c o l s u m called somewhat called sum for calls and we are using value of j and that you have to reduce that is minus is equal to matrix or that you of i and then you have to reduce that from j also fine so this is what you are actually doing now then comes fine so on reducing you have to check that which pointer needs to be moved that which value has become zero either i have to move i or i have to move j fine okay so in that case what you're doing if what if row sum r o w s u m if rho sum of i is equal to zero then in that case what you have to do you have to increment i find this is what i already told you that this is plus equal to one then in that case you have to increment i else not else if only if not else if called some c-o-l-s-u-m called some j c-o-l-s-u-m called some j c-o-l-s-u-m called some j has what become zero then you have to move that also fine else means what you have to check only one but here using f in both the cases that you have to check both the statement fine then you have to increment j that you have to increment j by one fine on doing all such thing what you do you just return what the matrix you created you have created what matrix mit find so you have to return fine you have to written that matrix fine so what you are actually doing let me explain you now so let me love all these things fine so let's now let's take the example same example by which i will be explaining you uh very clearly why okay so you let's take example the rowsum is 577 it's 5 7 and 10 and column sum is 8 6 and 8 fine what you did you took rows and column from length of row 7 column so length of row sum is three and column sum is so rows is now three calls is a variable is three you what you did you made one matrix and by using what this list comprehension that is for i is equal to zero uh from range of rows for j in range of column you are initializing each element with zeros what you are actually doing is you are initializing each and every element of the matrix with value zero fine now you have again created two variable i and j and you have initialized those value with values zero point so till three these three lines has become very clear now what you are doing is you are using a while loop while i is less than rows and while j is less than column it's currently true so what you did you are finding what minimum of row sum i in column so what you are actually doing you are finding minimum because your i is here your j is here you are finding minimum of these two and you are replacing that value here so mat zero matrix zero element will be a minimum of both so minimum of both is five so this has become five now what i told you that you have to reduce these five selected five from both this both the rows and columns so row sum i will have what subtraction of this matte i say so it will become 0 and this column sum will become 3 on reducing this value 5. now what you have to check which pointer you need to move i or j is row sum i equal to 0 yes row sum i is now 0 increment i will get incremented is column sum j equal to 0 no this will not get incremented so keep on when you keep on doing the same procedure what you will get the answer and after getting answer you will return this matrix fine bus only this much so let's run the code so that uh let's run this code fine okay so let me run this code now for you okay fine so the code is actually running accepted you have put 3 8 and 4 7 and this is clear cut it's running now let me submit the code okay fine it's accepted so let's come to the description part once again and you might be wondering why i haven't know shown you the method which they are using how my answer is differ from their answer so i'll be discussing those also this thing also so oh okay let's use the spam fan okay fine so let me explain what day people are using how they are solving this question fine so okay so what they are doing the same job fine five seven ten eight six eight how they are getting zero five zero is like this so what yeah they are doing is that they are finding what they are finding minimum of the entire row is this minimum of the entire column sum is this now among these two they are selecting minimum so what is minimum it's five and it's uh it's five and six from five and six they are getting five so it will become one fine and it will become 0. now again they'll find minimum so minimum from this and minimum from this excluding 0 so a minimum of this is what this is a 7 fine and then minimum of this is 1 so this will become yes exactly so this will become 1 so 7 and 1 will give you what 1 fine so this will become 0 fine this will become 0 now they again they are and this will become 6 so again from 8 and 6 it will become 6 because of this they are getting 0 5 0 6 1 0 so this is their own method of solving the question so till then uh i thought i have explained you uh in a best and possible manner what this uh how this uh problem can be solved so thank you so much for watching thank you so much thank you very much
Find Valid Matrix Given Row and Column Sums
minimum-number-of-days-to-make-m-bouquets
You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column. Find any matrix of **non-negative** integers of size `rowSum.length x colSum.length` that satisfies the `rowSum` and `colSum` requirements. Return _a 2D array representing **any** matrix that fulfills the requirements_. It's guaranteed that **at least one** matrix that fulfills the requirements exists. **Example 1:** **Input:** rowSum = \[3,8\], colSum = \[4,7\] **Output:** \[\[3,0\], \[1,7\]\] **Explanation:** 0th row: 3 + 0 = 3 == rowSum\[0\] 1st row: 1 + 7 = 8 == rowSum\[1\] 0th column: 3 + 1 = 4 == colSum\[0\] 1st column: 0 + 7 = 7 == colSum\[1\] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: \[\[1,2\], \[3,5\]\] **Example 2:** **Input:** rowSum = \[5,7,10\], colSum = \[8,6,8\] **Output:** \[\[0,5,0\], \[6,1,0\], \[2,0,8\]\] **Constraints:** * `1 <= rowSum.length, colSum.length <= 500` * `0 <= rowSum[i], colSum[i] <= 108` * `sum(rowSum) == sum(colSum)`
If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.
Array,Binary Search
Medium
2134,2257
238
hey guys welcome back today we're taking a look at product of array except self which is a pretty tricky array question that requires a bit of a creative twist on what we know so given an integer array nums return an array answer such that answer at index i is equal to the product of all elements of nums except nums of i it's guaranteed to fit a 32-bit integer uh you might write you 32-bit integer uh you might write you 32-bit integer uh you might write you must write an algorithm that runs in linear time without using the division operation this is pretty key uh pretty um intuitively if you try if you wanted to use the division operation then you could kind of just tell that uh in the case of this then you could just kind of get the product of all of these and then divide them by each index or each element at index i um you'd have a few edge cases with zeros but for the most part this would be a pretty simple question so you can't do this uh so let's take a look at what we actually are given and what we have to do then so we have the array one two three four and our output array is 24 being the product 234 12 being the product of one three and four eight being the product of uh everything except three so one two four and six being the product of everything except for so three two one so that's what we have um let's figure out how we're actually going to do this then without using the uh division operator so if we're not using the division operator then somehow we're going to need to get all using just the multiplication operator we're going to need to return an array such that this array is one or sorry um everything except one so it'd be two times three times four um this array is going uh the index here is going to be one times three times four you next at uh this second index is going to be 1 times 2 times 4 and this last index is going to be 1 times 2 times 3. and this might not seem obvious at first but something we're actually doing is taking um everything before multiplied by everything after so at this zero index we're taking everything before and we can just assume that if there's nothing there then we can assume that it's one and we're multiplying that by everything after which is two times 3 times 4. then at index 2 what we're doing is we're taking this 2 and we're multiplying everything that comes before by everything that comes after multiplying 1 by 3 times 4 and then for this next index at index 2 element 3 we're multiplying everything that comes before one times two and we're multiplying that by everything that comes after four and then for this last one we're doing the same thing which is multiplying everything that comes before uh one times two times three times everything that comes after and there's nothing here so we can assume that's a plus one that's a times one so what could we do first we could uh create uh two arrays we could call these pre and call this post and for this pre-array this pre-array and for this pre-array this pre-array and for this pre-array this pre-array could have everything that comes after so excluding one so starting at index one starting at index zero it would be one and then we could essentially start the actual calculations here where we keep a running total of one and then it's one times whatever was here and then it's uh two times whatever comes before that so two times um the element multiplied by everything that came before and then for this last one we would have this element you know the element at the index right before because this is index three zero one two three then for this last element what we get is the index from the original array at position at index position two multiplied by what was in this array at index position two and then we'd get six like this and then for this post we could do a very similar thing except working the other way around where we'd start at one and then sorry zero one two three two one zero and then at this index we would get this index or sorry the index above that would get this index four multiplied by whatever came over here so four and then uh continuing onwards um at this index one we would take the index above that i didn't next two we would take three and multiply that by whatever was in the index before and this would be um four times three it would be twelve and then finally we could do the same thing right here uh two the index two which is the index above uh one above index zero so two multiplied by whatever came before so that was this would be 24. then you have these two arrays and what you can actually do is you can just multiply them directly to get your product array which is going to be 24 12 um eight and six and if you scroll up in the example 24 12 8 and 6 this is actually exactly what we want in our output array um is this a linear time yes you only well yeah you're going through this once to get our prefix array and then you're going through it once backwards to get our uh post array and then you're iterating through all of them again so this is going to be of three and time complexity um which just simplifies to o n and as for space complexity it takes the pre the post and the final which is of three of n which is again simplified to o of n and we can actually optimize this a bit by converting this 3n to just o of n uh we would skip this 3m by skipping the fact that we have a pre post and product what we could do is get rid of this pre and post get rid of these two arrays and then just directly work with product how would we do that uh let's take a look right so we have this array that we're working with and what we want to do is get it all into this product array of the same length and we want to get everything multiplied together so we're kind of doing the same thing as we did in the pre and post but instead we're just going to keep track of everything in here so uh we'll do this first iteration so as we iterate through we'll keep track of product as um one we'll start with one and then we'll do the exact same thing that we did with keeping track of the pre-element so this is index zero the pre-element so this is index zero the pre-element so this is index zero one two three it's index one so we'll take the index before one multiply it by this we have one again here and then for this two we have two times one and then for this last one we have three times two six and then we can actually iterate through this product of backwards one time and instead just do the same thing so we would do six times one and then instead we would just multiply it by whatever we would have initially had in the product array and then you would have this times one um and then we would do times four so times four and then over here backwards continue onwards we would do times 12 and then lastly we do times 24 and then in that way we can get our product right so let's see how this actually looks like in the code and hopefully it'll make a little bit more sense so the very first thing we're going to want to do is instantiate a solution array which is just going to be an empty array that we're going to slowly start to fill in um then our we're going to do this uh i guess pre multiply multiplication and then this is going to be let product equal one because remember we're always starting at one and we want to create the array so we're given one two three four and we want to turn this into one uh i believe yeah one two six and then so the way we're going to do that is by doing an iteration for let i equal zero i is less than numbers.length equal zero i is less than numbers.length equal zero i is less than numbers.length so we're going to iterate through the entire nums array and we're going to say the result at index i is equal to product which we set to be one initially so at the zeroth array is going to be product and then we're going to multiply product times equals num's i so as we continue through this loop this product is going to continuously be updated by whatever the nums element is at that index so um we have this product after res i uh which is how we can get the update to be an index before is what it seems like right and then at this point our solutions our solution array looks like 1 2 6. this is exactly what we want now we can just iterate backwards so we'll let product equal one again and we can iterate backwards for let i equals number length minus one greater than or equal to zero and minus we can it when we're iterating backwards we'll do pretty much the same thing except kind of flipped uh result times equals product so in this case we don't want to set it equal to the product we want to multiply it by this new backwards product that we're keeping track of and again we do the same thing here with product times equals nun's i so we're just updating product again if we return res or sorry if you return saul um not sure why i've been doing results instead of solution uh then we should get the correct answer here so yep that works
Product of Array Except Self
product-of-array-except-self
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`. The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. You must write an algorithm that runs in `O(n)` time and without using the division operation. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** \[24,12,8,6\] **Example 2:** **Input:** nums = \[-1,1,0,-3,3\] **Output:** \[0,0,9,0,0\] **Constraints:** * `2 <= nums.length <= 105` * `-30 <= nums[i] <= 30` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. **Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
null
Array,Prefix Sum
Medium
42,152,265,2267
1,091
hi everyone in today challenge we are going to solve this problem the problem name is path in a binary Matrix and the problem is one zero nine one all right guys so first of all we are going to clearly understand this problem statement after that we are going to move to the logic part we are going to see how we can solve this problem and after that we are going to move to the implementation path we are going to implement our load you can see plus Java and Python programming language fine guys now let's see what this problem say right so let's understand this problem statement so problems is given n cruise and binary Matrix grade written the length of short scalar path in The Matrix if there is no credit path later minus one so guys simple line it says that we are given first of all grid a matrix binary Matrix that means we will have only zero one value in Matrix and the size is nothing but n close and that means it is a square Matrix right all right and now what we have to do we have to find a clear path in this Matrix right so we have to find clear path and if there are exists more than one killer bar so we have to find the shortest path so one thing is clear that if there are more than one path axis we have to find shortest one and second thing if there is no path exists so we have to get a minus one I hope this makes sense right so this is basically the meaning of this line so that let's understand this what is clear path right from the top left cell to the bottom right side such that they are too condition right so basically a clear path is nothing but in simple what we can say if we are able to move from zero comma zero cell to the last bottom right cell that means n minus 1 to n minus one if we are able to reach from this cell to this cell if we are able to meet these from this cell to the cell that means the uh the that path is nothing but a killer path right and there is some condition between this particular thing if you are starting from this cell and you want to use the cell so there are some condition the first condition is nothing but all the basic cell of the path are zero so let's understand this with example so guys here if you are here right zero comma zero right this is the initial starting we can sell and you want to reach this one common one right so you can't take all other parts which have valuable you can take only those path or we can see those cells which have a value zero right they have clearly mentioned all the wizard cell of the path r0 means the visited cell should we have a value zero right so here from 0 comma zero you can't take this path that you can't move to this cell why because this is a value one you can't move to this one because this also available so you can take only this one which is nothing but have a value 0 right so it's the second condition is nothing but all the adjacent cell of path are it actually connected now let's understand this so guys let's assume you are standing here right so this network one comma one we can say Index right so that you can go to a direction from there how you can move to this one so you can move to the left you can move to the right you can move to bottom right now you can move to this diagonal as well you can move to this one diagonal you can move to this title you can move to this tag as well so you have eight possibilities from this particular cell where you want to move I hope this making a sense right so you can move to a directionally at a particular cell so these were the two conditions uh from moving zero comma zero to n minus one command minus 1 that you can take only those cell which have value 0 and you can move to a directionally at a time I hope guys now you understood the problem if I some want to summarize it so let's summarize this particular line so basically you are given one Matrix grid Matrix will have a square Matrix and a binary Matrix means having a valid Zero from one the second thing we have to find a clear path in this Matrix which means we have to start from zero comma 0 which n minus one command minus one such that the sun we are taking between uh that particular path should not have a value one and we can move to a direction right and if there is exist a one killer path that uh more than one kilo pass so we have to return the shortest path means the short uh less number of cell we have listed and if they not exit any single path clear path so we have to return minus one so this is what the basically uh summarize of this particular problem statement now let's see the example these two example how the answer 2 came for this example and how answer fourth in this next example so here guys you I hope you understood this from this cell we want to reach this so we are taking only this path so this is giving answer to how because they have no tell that we are starting from here we have to reach the cell as well right so we have visited this one first cell now we can't take this one but we can take this one so we jump to this particular cell from the cell and we have visited this one also so total cell we have listed nothing but two so we are going to written two but in the next sum this particular example you will understand better how this particular answer this particular plate have a four answer so if you are here right let's see I jump to this particular initi 0.0 initi 0.0 initi 0.0 register this one right so every one cell I move to this one because I can't move bottom it has valuable I can't move to this one because it also have valuable so I move to this one and I have visited now those two cell right but I am here right now I can move to this one I have listed three cell this is a clear path right but this is not a shortest one so we have to find shortest one so the shortest one will be nothing but uh if we don't take this path right if we don't move to this one cell if we directly move to here then we are gonna uh we can see we can uh minimize our cost we can minimize our length right so we can say now we just need to visit only four cell one two three and four so total we can say optimal way or total the shortest clear path is nothing but four because we have visited only four cell to reach this particular Target set I hope this makes sense right so now check the path uh check the value of the cell we also need to check which one is the optimal one right so we could take this particular cell as well but this is not going to give optimal right we have taken this particular question which is giving optimal so the main logic in this problem is nothing but this only we have to find the optimal one so that where we can move which can give us the optimal or which is the shortest path right so how we can do this let's see the logic part right so this is Commander logic how we can solve this problem so let me write a logic only and here let's understand this how we can solve this problem so guys just want to ask one thing uh just tell me whenever we need to find the shortest path in a graph which algorithm you get in your mind personal algorithm right I hope guys you are getting a BFS right BF is the only best algorithm we can say which help us to find a shortest path right now so here also we are going to use a BFS only and we are going to see how we can use a BFS to get the shortest path in this particular foreign so that means we could not even start to find a path right they have not given a guarantee that you are always heading to this particular cell they have told that we have to start from here and reach to the right so that means this particular cell can also have a value one so we can make one condition that if the initial cell is having a value one that means you have to get a minus one directly right if this is a value zero then you have to use a BFS so here we are going to say we are going to use a BFS and how BF is going to work let's see that as well right so I'm going to make a first of all Q and here guys I have uh initially I have only zero comma zeros and Light I'm at this particular position and I have 0.0 this particular position and I have 0.0 this particular position and I have 0.0 and I have taken one step I hope this makes sense right now we are going to move to the next we are going to take this particular cell and we are going to see where else we can move from this particular cell so once I hope this particular 0 comma 0 I can see I can move only to the right side right I can't move bottom I can't move this particular diagonal I can't move anywhere except this right cell so I can say from zero comma zero I can move to 0.1 only fine 0.1 only fine 0.1 only fine so now but moving to this one I took a second step right so total step is nothing but two now I can say from 0 comma one let's poke this one as well so I pop this particular cell and before popping I'm making it one right so this CR7 the CR7 right so whenever we are inserting this particular cell we are making it one fine so now once we can say pop this particular zero comma 1 so once I pop this I wanna check it where I can move this direction I can move to this direction but I can't move there I can't move back as well because this is already one if I move to this direction rights Direction so I have to insert 0 comma 2 in my queue if I move to this diagonal so I have to insert one comma two in my right so I have by this I have taken third step which is nothing but I can move to this one or this one sir I hope this makes sense right now uh once I inserted this two cell I am gonna make this one as well right so these are one now because we have visited this particular thing now uh let's pop out this zero comma two so once I put this 0 comma 2 cell so this cell so I'm gonna say uh just see where we can move from zero comma two so from zero comma 2 we can't move this one right this is one we can't move bottom this is one we can't move diagonal this is also one and we can't move the right side which is out of bound so we can see we can't move anywhere from zero comma two right so this is gonna give nothing to us right now let's pop this one comma two from one comma two you can move bottom only so between nothing but two comma 2 right and if you move into this particular version you are taking a fourth step so as you can see we reached to the last cell right whenever we are opening up this particular cell we are going to check it if it is the bottom right cell or no if it is here so return this particular step number of steps right so here you can see once we are going to pop this particular cell so we are going to check it this is this the large self yes this is the last cell of a grid means uh bottom line cell so you can see directly return step so here we are going rate in four so this is how our algorithm work right so you can see the BFS how this PF is going to help in this particular problem now let's move to the implementation part let's implement this logic in Python simpler plus enter all right so here let me move to this one so here guys in Python first of all uh let me tell you first of all we have already solved this one this is my second retake of this video so first of all what we are going to do we are going to first of all check one condition read of zero comma zero we could say if this is a one so this is basically determination directly if it is not say node so we are going to calculate the length first so length of grid collections here we can see DQ and here we can pass our zero comma zero cell right initially we are here zero comma zero fine once this is now we are going to say while Q we are going to find a size which is going to be talking about length of Q and here we can say for I in the of let me write Prime range of size here we can say uh take out the pope or the first element first of all so that is what we can say we're gonna give us row and column so we can secure dot Pope left right and here uh once we spoke about the slope element of Q we are going to move to a dash but before that we have to check this row is equal to n minus 1 let me add n minus 1 and this column also equal to n minus that means this is the bottom right cell so we can see written our step right and we haven't declare a step so let's declare a step right step is going to be nothing but one initially right because we have taken a zero comma zero cell as well once this is done um if this condition two then we are going to return answer but if it is node two so what we are going to do we are going to move eight directions for eight directions we can say direction is nothing but equal to uh zero comma one this is uh one comma because Zero from minus one so this is nothing but we can say right and left and one comma zero bottom zero minus one comma zero down and minus 1 and we can say minus 1 comma 1 and the last one is nothing but minus one comma one right so this is another eight direction we have right once we have got this direction we are going to Traverse over all these directions one by one for a comma B in directions rho plus a current column is p once this is done we are going to check first of all this right so is greater than or equal to n or current column is greater than equal to n or we can say last thing is nothing but if grid of current row and current correct colon is equal to 1 that means we can't take that but itself right if any of this condition true we are gonna simply say continue you don't we can't take this particular direction right if it is not the case that means we can take it right so we can see first of all make this grid current row and current column is equal to 1 which we are marking them visited as well as we can't we don't want to move this particular cell okay right and we are inserting this particular question in our queue so we can say Q dot append this particular set so you can say current row current column what's this done so once this Loop is over we are going to implement our step as well right so we are going to take new Step again so we can calculate return minus 1 here and why it is so why we are not returning here step see guys if there will be a path axis so it will come in this particular condition right but if it node path actually so it's going to come out this particular while loop and we are going to return minus 1. now let's see whether it's working final node let's try to run this code and I hope it should work right now it's not working why syntax error invalid syntax all right so we haven't passed here uh minus one light now let's run this code I hope now it should work right and you're taking a time again still saying invalid syntax too we have done something wrong let's see that's so if you will focus here we have done any mistake or not let's check it so Direction it is a total is So we are doing everything is fine it's fine right okay so we have used common line here now let's send this code it is some syntax mistake I don't want that one as well now you can see all the desk is password selected to submit this code and I hope it will also get submitted right and you can see guys it's successfully submitted now let's move to the next programming language that is nothing but C plus and here first of all we are going to check first condition that is great of 0 comma 0 is nothing but we can say uh one so we can directly data minus 1. but if it is not the case to find land which network gives it or size right and after that you can say uh make a queue which is clear of integer and this Q's name is Lexi q and we can see Q dot uh push this particular we can say uh one uh we can see Zero comma zero right in this system and once you push it you can say step is going to be equal to one now you can stop uh start our while loop which is another y uh Q is empty right Q is empty you can move it so here you can say uh find out the size because s as I plus here what you can do you can say uh pop out the first element right so we can say uh which is right and you can see print also right once you have done this friend you can secure right and here data we are going to check if data DOT first is equal to n minus 1 and data dot second is equal to n minus 1 so you can simply return this particular step right but if it's not the case so you are going to move to a Direction so you are going to again make an array or you can say vector right so uh instead of this if we could make an array it will be easy right so we can say integer our directions array and this direction I will have uh these directions let's make it first we have 0 comma 0 1 then we have zero comma minus 1. and we have um one comma 0 then we have minus one comma 0 then we have one comma 1 and we have a minus 1 comma one uh let me write against the same mistake I was going to do a minus 1 comma minus 1 then we have minus one comma 1 then we have one comma minus one right once this is done we are going to move to this particular direction set it for INT is equal to zero I less than eight I plus thank you all right and because there are eight elements after that we are going to say uh take the correct Row in current row is nothing but gonna be current row is note row here data DOT first plus this directions right direction of I comma 0. hey and after that we are considering current columns network data dot second Plus directions of ie and here we can pass one now we are going to check if it's Automotive so if current row is less than 0 over current column is less than zero or we can say let me have a zero so if it is so let me just make it here and here current uh row is greater than or equal to n current row current column is equal to one so we can't take this right so let's continue There but if it is not the case so we are going to mark it first of all visit current period control current column is equal to one and here we can say let's insert in our queue so Q dot push you can push this particular thing Uh current row and current role in this while loop you can say uh step plus equal to 1. right after that if this you are coming out of this while loop that means you could not able to find a clear path so you are going to write a minus one so I hope this makes sense right so let's run this code and see with X working if I don't know uh it should work right but it's a semicolon error right let's see do we have any more error oh no right I don't think we should get an error right so let's see you can see all the desk is passworded to submit this code as well and by this we have successfully submitted with C plus and here we go X successfully submitted now let's move to the next programming languages Java and here in Java what we are going to do first of all we are going to calculate the length but before that we are going to check is create of 0 and 0 is nothing but equal to we can say here one so directly at minus one but if it's not the case we'll find a length which network length once you have done this you are going to make a q so Q is nothing but going to be a pair and pair size and here you can see Q is going to be earn Its Right Here Q only Q is equal to New Link list so guys let me Define a clear class here because we want to insert 2T row and column so we can see class here and here we can say int first and in second let's make a new line and here pair and gonna take a into B and here we can see first is equal to a let me make it a better syntax and first note first now second is going to network equal to B right once this is done we are going to come here we are going to say this is a new queue we have created and here initially you have to insert Q dot you can say uh what you can do you can say add this new pair of 0 comma 0 right and you can make a step is equal to one here we can say while skew in a while this node equal to Q dot is empty so you can say about nothing but uh you can find the first of all size so which is next one as let's say and Q load size right four Theta is equal to 0 and less than s i plus so you can do nothing but you can say uh you're gonna take out the front element right what you can do you can say uh queue you can make it like pair only right here that is nothing but a q dot remove after that you can say if data DOT first is equal to n minus 1 and data dot second is equal to n minus 1 so you can directly return step but if it is not the case so you're gonna move to eight directions so we can say Let's Get direction first so we can say integer directions and here that made it here only directions which is nothing but we can say uh zero comma one first of all then one zero comma minus one then again minus 1 comma 0 let me write here 1 comma zero let me get one only okay and here we can now move the diagonal one so one comma one minus 1 comma minus 1 and the last is nothing but let me make it above minus one comma right so we have make a direction eight directions we are going to move on this for inter and we can say uh ARR of this directions here we can say uh that row is nothing but control is nothing but rho plus this error of zero the column is nothing but row Plus error of one right once we make this current term and column we are going to check it if this current row is less than zero or current column uh note this one current column is less than zero and one more condition that is Network current row is greater than n or equal to n and current column is greater than or equal to n or grid of current row current column is equal to one right so if this is the case come so we have to directly return we can say continue move to the next style we can't take this type uh particular step right now if it is not the true right if at all these conditions are false so we are going to come to this particular thing and we are going to first of all make this paste it so create current row current column mark this one that means we don't want to move here and next time and after that we are going to insert this particular thing in our queue so we can secure dot add new pair and here we can pass control current right after that we are going to increase this step and here we can return minus one because this will only come when we don't able to find a single clear path let's run this currency but let's work if I don't know or do we have any mistake here yeah there's a lot of mistake ideas so this is row is not there right we have to use data DOT first and data dot second now let's see anything else we have it's taking a time that means you can see all that is passed so let's try to submit this code as well and by this we have successfully submitted with C plus Java and python right and this was the easy problem isn't it I have questions you understood the logic part problem understanding part and implementation part in the three programming language if you still have any kind of doubt we can write in the comment section I'm always there to help you and if you learn something new in this video don't forget to hit the like button subscribe my channel between the next video
Shortest Path in Binary Matrix
maximum-average-subtree
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
Tree,Depth-First Search,Binary Tree
Medium
2126
1,750
Hello everyone welcome to my channel quote sir with me so today we are going to watch the video number of our t pointer technique playlist ok and the lead code is marked medium but actually it is a very easy question a lead code number is 1750 the name of the question is Minimum length of string after delete Similar ends Okay, so what is being said in this is that you will be given a string which will have only three characters a b and c you are asked to apply the following algorithm on the string any number of times this algorithm will give you The first point to be applied is that what is the algorithm that choose a non-MT prefix in that string choose a non-MT prefix in that string choose a non-MT prefix in that string whose all characters should be equal and choose a non-MT suffix in the same string and choose a non-MT suffix in the same string and choose a non-MT suffix in the same string whose all characters should be equal, okay and the prefix and safe suffix should not intersect, meaning like this It should not be that AB is CD, then whatever prefix you chose ABC and suffix CD, you cannot choose like this, no, yes, the character should be equal, let's assume that here it would be A, there would be A here also, you cannot choose like this. A is selected and there should not be an intersection from here, right? What is the last point? This is an important point. The character from the prefix and suffix must be the same, so the character must be the same. The length must be the same. It is not necessary that we assume. Have A Have Y So then here B Let's say see you let's say Prefix You chose this Why did you choose because all the characters are the same You chose this suffix right all the characters are the same Its a is so look the length of both is equal but both The characters should be the same, right? Delete both the prefix and 's', so you can delete both of them. So, the and 's', so you can delete both of them. So, the and 's', so you can delete both of them. So, the most important point is this fourth one, rest everything is very easy, so if you pay attention, what is he saying? When you delete, a little bit of string will be left in the end, its minimum length has to be found, that means you have to delete maximum from maximum, okay, performing the above operation any number of times, okay, like look at this example, try to choose the prefix, let's assume. You chose C and from here you chose A but the first character of both is unequal so you cannot select or delete anything, from here let's say you chose C as prefix and from here suffix you chose A so just characters in both. If it is not equal, then you cannot delete it. Right, look at point number four, it will become invalid. Prefix and suffix should have the same character, it has become invalid, that is why you could not delete anything. So, what is its length left? Only two of two is left. The example is good, see here you have chosen the prefix 'C' see here you have chosen the prefix 'C' see here you have chosen the prefix 'C' and the suffix 'C'. Here you cannot and the suffix 'C'. Here you cannot and the suffix 'C'. Here you cannot choose 'C' because there are different characters in 'C', choose 'C' because there are different characters in 'C', choose 'C' because there are different characters in 'C', you have to choose the prefix and suffix with the same character. Look in both the prefixes also, the character is the same in it. There is only C in this also there is only C so you can delete both of them so you deleted both of them, after that prefix you chose a, here you chose a, character is same in both, you can delete here B Chosen can be deleted here A Chosen can be deleted Everything is deleted Length is zero left Okay look here this is a good example Look here first see the first character should match right Otherwise, if the first character is not matched, then why go ahead now, I mean, if there is A in the prefix here and there was a root here, then there would be no point, you could not have deleted it, right, then the first character should be matched. Should A and A match, let's see how many A's can be taken here. You can take two A's here because both have the same character. Here you can take only one A. Neither is the prefix. You chose the one in which all the characters are A in the suffix. You chose this one from which all the characters are A, then only with the same character in prefix and suffix, you can delete both of them, so what you did is this and deleted it, after that look at the prefix, you chose this B, here you have suffix. I chose BB here because the character is same in both of them, so this is this and this is B, you have blown it, after that look, this is C, this is A, so both of them have been different, they are different characters, so you will not be able to do anything right by deleting them. So stop here, you cannot move ahead, how much of this string is left, what is its length, is it three? If you see, this is a very easy problem, that is, it should not have been medium, but it is fine, it is very good for practice. Isn't it simple for you, if you look at it, what am I doing, I am using two pointers to find out the prefix and suffix. Right, the question itself is asking you to use two pointers, that is why this question falls in the Two pointer technique is not clear cut, I told you the problem clearly hints at delete from two ints, two pointer is the only thing you have to use. Okay, so let's see with this example. If you want to use two pointer, then I have taken two pointer, one is here. But one J is fine here, so I had already told you that when will you be able to move ahead from A here and when will you be able to move ahead from J here, when I and J cutter should be equal, if I and Jth character should be equal in the beginning. If not then you will not be able to progress further, you will never be able to progress further. Right, look here, 'i' character is 'c', 'jet' character is 'c', look here, 'i' character is 'c', 'jet' character is 'c', look here, 'i' character is 'c', 'jet' character is 'c', meaning you can progress further, you can delete it, now I will see here how many such big prefixes I can extract. I have come with C, there is no C next to it, okay, so you can take only this much, right, here C is ahead and if there is no C, then J will remain till this much and we will first delete these two, so both of them will be deleted. I will come here and J will come here. Okay, now let's see here, first see if both the vectors are matching or not. Yes, they are matching. Okay, after that let's see how much more we can take. A is further ahead. That is not there is B next, then only this A can be taken, here also A is next, otherwise you can only take this one, right, so you deleted both of them, then I came next, J came next. Okay, now look here, B and B are equal, meaning you can consider both of them for deletion. Let's see how big a prefix we can make. Here B is there, if B is not there, Aa, make such a big prefix. You will find that J will also be able to make such a big prefix because here there is A, isn't it, and this is B, so you deleted both of them, then I came here, J came here, look here, both are equal characters and yes till when. Have to do a lesson h should be na aa equal to b also h why can't you because it will intersect na here you have deleted these two aa gr sorry g e is done so the value has broken ours ok so now attention Two, here our entire string is deleted, then my answer should be zero. Okay, let's see one more last example, you will write the code easily from that. This example is quite good, isn't it? Let's solve it, so see one. Let's run it once in the example also. First of all, what we have to see is that the I character and the J character should be equal. Only after that you can find the prefix and suffix. So A is equal. Here A is here. A is okay. Meaning. Dishing can be done, now I will see how big a prefix Aa can make, so which character is ours? First of all, let's find out which character is A of Aa, isn't it, and this is equal to s of J, E is equal to E. s is off h, this is the only way we will move ahead, so okay, a off aa si means equal to a, okay, so I moved aa forward, this is also equal to a, so I moved aa forward, I mean, find such a big prefix aa. Given that we can delete, similarly J will also do the same and see how many A's he can find in the suffix, so J found this A, so J came here, but now J did not find A, so J could find only this many suffixes. So we can delete this prefix and this suffix, okay, after that we will check again that the rectangle character is B, so what is the rectangle character, it is B and the jet character is also B, so it can be deleted, now let's find out that How big can we make prefixes and suffixes? So the rectangle character is now equal to B, so Aa will come next. Here, Aa comes next, but now it is equal to C. If a different character comes then we can get only this much prefix. Similarly, J is also J. Look, if J is equal to B, then J will come next. This is also equal to B. J will come next but it is not equal to B now. So J got such a big suffix, so we deleted this prefix and this suffix at once. Okay, now look at the i and zth character, they are not equal because the rectangle character is C and the zth character is A, so now we will break, there is no use of going further, you cannot delete, that is why your length is there, see how much it is. j - aa + 1, will you your length is there, see how much it is. j - aa + 1, will you your length is there, see how much it is. j - aa + 1, will you do indexing? 0 1 2 3 4 5 6 7 8 yes, then how much will j be? 5 - 3, how much is p, the length is yes, then how much will j be? 5 - 3, how much is p, the length is yes, then how much will j be? 5 - 3, how much is p, the length is three, this was the answer, so if you see, it is very easy from here. To derive what will be its code, first of all you had to keep in mind that the i which is there should be less than h and end you move ahead only when s off aa is equal to s off h only then you move ahead g otherwise. There is no use in you going ahead if these two characters become equal, meaning now we will ask I and J to find out their respective prefixes and suffixes, then first of all we will find out the character that is the character which is equal. If s is off aa then it is the same thing, both are equal. Now I will give the opportunity to i to create a bigger prefix as far as v can delete. So let's do the lesson and s of i. As long as this character is equal then Till i plus will continue to happen na similarly pay attention here one thing j is greater than a till this will continue na and a of j till c is equal to the character then we will keep increasing j too till j is made minus Okay, after that when we come out of Y loop, what we have to return is to return j - aa + 1 ok now look pay return j - aa + 1 ok now look pay return j - aa + 1 ok now look pay attention this will give you the answer. Obviously this one will be solved but here I have colored this part in blue. I have marked it with blue, what is its reason, you will be able to understand only after making a mistake, so look here, let us take an example from where it will be clear why I have marked it with blue. Okay, look at this example. Let's assume that this is yours. If it was an example, your I pointer is here. I will say to I that you make your prefix, which character is s of i or it is h then see what i will do I will say that I make your prefix now i &lt; h should be and s of a is now i &lt; h should be and s of a is now i &lt; h should be and s of a is equal to i is equal to As long as the character is equal to i, it will be plus, right, so look here, pay attention, i is equal to a, yes, then i has moved ahead, okay, but now look, if i is not moving, then there is a break here, in which index is i. is at index number one. Okay, now similarly remember the while loop of j used to run as long as j is equal to jth character a then j will keep decreasing but notice what condition you wrote that j should be greater than Till then only this while loop will work, right here, but what will be the problem here, see Aa because Aa could not find so many prefixes, that Ai used to move ahead after this, okay, so here Ja is equal to Aa. What will you do? You will run a while loop on J is equal to I, otherwise this character will be missed. It's okay, so for this you will have to put J is greater than equal to A, not equal to A, that is why I wrote here in blue. So that we can correct it later and it's totally fine, this mistake is released very often only after making a mistake. So here now see, this Y loop will run since it is greater than equal to two, isn't it? We will say, OK, we can delete it, then J will move ahead, right, J has moved ahead, now look, J is the lesson, then this while loop will not work, right, this while loop will not work because J is the lesson. Okay, so j is here, your index number is at zero, okay, now pay attention to one thing, after this, nothing can be deleted because look, lesson j is no more, right, everything is over, now look. Pay attention j - aa + 1 we would have returned attention j - aa + 1 we would have returned attention j - aa + 1 we would have returned otherwise j what is mine is zero aa my one is done pv see the answer zero has come na that means this part is still correct we just had to correct this thing j greater One must be equal to two and equal to has been done just so that it does not get stuck in such cases. See, in this example of yours also the same case comes, the last one had come here, if the character had come here, then both the characters are equal. When you create the prefix 'hai' and 'i', you will equal. When you create the prefix 'hai' and 'i', you will equal. When you create the prefix 'hai' and 'i', you will see 'ha', it is equal to 'a', so 'aa' will come see 'ha', it is equal to 'a', so 'aa' will come see 'ha', it is equal to 'a', so 'aa' will come here, then 'je' should not stop here, then 'je' should not stop here. Then the second loop should run, then j will come here, now j less then come, now the loop will break, right, after this j my a pv, here also the answer will be zero because all of them have been deleted, ok, it was quite simple. So we have almost done the code, let us code quickly and finish it, but yes, time complex. If you see, we are visiting each character only once, then it will seem like a time complex. Okay, and how much is the space complex? It seems to be off because we have not taken any extra space and there is one more suggestion that if we assume that such a question comes in the future and if they say that you have to send the entire string and not the length, it is not a string. If you want to remove it then you can solve it from dex. It is not from dex, what is there in dex that you will be able to insert the character easily and can delete it from the front also, you can delete it from the back also, then the remaining characters will be saved. You have to create a string from it, because if you delete the string in the given input itself, let us assume from the front that you have deleted it, then it will be an o of n operation because when you delete it, all these shifts will happen. If it is done by one then o will be off n, that will not be the correct solution, that means we can give time limit sheet, that will be the best data structure for d, this means that it can be a follow up question. If this problem is correct, then d can also be from k. Solve it and see if you are able to print the remaining string r Not for now just find the length So let's quote it and finish it So let's code it First let's find the length n and i and j Let's define pointed n = add length aa will j Let's define pointed n = add length aa will j Let's define pointed n = add length aa will start from 0 j will start from n-1 start from 0 j will start from n-1 start from 0 j will start from n-1 ok for pointer now look while the length should be j and when will you start when i character will be illu ill tj character If both of them are not equal then there is no point in moving ahead. Like see the first example, aa vector zth vector is not equal then you cannot delete anything. Right, you will be able to move ahead only in such a case when aa and zter are not equal. If it is equal, then which character is it? S = s, isn't it? then which character is it? S = s, isn't it? then which character is it? S = s, isn't it? Then s of j is equal, only then you have moved ahead. Now I will say i as a prefix. Make your i &lt; j. End and s of i should be your i &lt; j. End and s of i should be your i &lt; j. End and s of i should be equal to s. It should be there, only then you will be able to make further prefix i + + you will be able to make further prefix i + + you will be able to make further prefix i + + after this, if j is equal to i, I have explained to you why and s of j should also be equal to this s, then j will be - minus. In the end nothing will be then j will be - minus. In the end nothing will be then j will be - minus. In the end nothing will be returned j - i + 1 returned j - i + 1 returned j - i + 1 Submit and let's see Any doubt raise in the comment section Try to help or out See you Next video Thank you
Minimum Length of String After Deleting Similar Ends
check-if-two-expression-trees-are-equivalent
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Tree,Depth-First Search,Binary Tree
Medium
1736
100
Everyone welcome you my channel ok the name of the question is it has been asked many times ok Google Amazon Meta Adobe Bloomberg mentarax ok I came to college in mental graphics this company then they asked this question ok If there is input problem then understand what is the question? The question is very simple. It is clear from the name also that you have been given two binaries. You have to tell whether they are from both the objects or not, are they replicas from both the objects or not, are they correct to each other. Hey man, let's take this root van, okay man let's take root tu, so you have to tell whether both the trees are exactly the same or not, then it's okay, now you are on root van and root tu, so now find out whether these two What will you do after that and check the one on the left, then go to the left of Route Van and go to the right of Route Tu and after checking them, go to the left of Route 2 also. You will check right only then the exact structure should be correct. Values ​​should also be same. structure should be correct. Values ​​should also be same. structure should be correct. Values ​​should also be same. If the root is left, then root 2 will also go to the left and then match it. Are these two from both? Yes, they are from both, it is very good, this is so. The left is finished, the left is finished, then the route goes to the right of the van. This is one of the human beings. If all of them are done then our answer will be true. Okay, so see, the flow will be like this, the flow will be simple. The question is also very simple. There are not many two, like look here, like I take, both of them are equal, it is very good, it is said, brother, check the left side also, so go to the left side and check, he will also say, okay, I am also on the left side. I will go and check that both of us will have to be exact, structure wise and value Vijay too, so when I extracted it from both of them, then both of them returned true to the route van, brother, it is from the left side, you returned it is right. We also check the sides, extracted from both returned true, okay here, so we are getting to know that both the sides are absolutely true, so we have to do nothing else, how will we do it, the answer will be true, it is from everything. Write anything, it's okay, write anything, right, and just keep comparing, then how will our function be? Tell me, this is a tree, okay, in this both the routes have been passed, root van and root tu are okay. See, first of all, both the routes should be empty. Meaning, Root Van is also my tap and end Root is also my tap, so it is an obvious thing, friend, still both are similar, both are empty trees, so even then my answer will be if it happens that brother, you have become Root Van, okay end And Root Tu is not equal Tu, this is a very good thing, this one is okay, one, this case happened, then brother, it got messed up, it is return false, I mean, I am saying something like Root Van, this is Root Tu, when you go left. So there was a note here and if not on its left then it is the same thing that if it should be then it should be with everything, just the structure, either only the route, you tap, or only the route, don't take, see, or both are tap, then we will return the tour very much. The good thing is that if both the notes are not tapped then either of them or one of the two will tap only and the other one will do . . . So now our code looks something like this that if both the notes are tapped then start the return or else If there is only one tap, only one, then you will do return force, it means it is a toilet, it has a left side, this tree is not on its left side, it is okay, either take its voice and the like, it does not have a left side, it has a left side. Okay, either take it like this, it has a right side, it does n't have a right side, either take it like this, it goes to the right, it doesn't go to the right, okay, then there is a root, either one, if it is only null, then return will be false. This thing is cleared, why is it so, okay, the route has been checked, now we have to move ahead, okay, so what I said, brother, if you have to go from this to this tree, then the left of the root van and the left of the root should also be equal. Okay, why end and end because brother, everything should be left right, everything should be right for the route van and the route you will go right, we will return whatever comes from here, okay, this is ours, this is the way of recovery, is n't it just a request? The method is done, this is fine, what else can happen, write simple BF, everyone knows the BF signal, why will we take it for root route van? Okay, let's take main and we will pop both of them here, if the value of both does not match. So return will be false, if value is not returned then similarly we will check at the same time that if any one of the two notes is not presented, then return will be false. Okay, now when we go to court then it will be fine there. But it will also become clear, but it is basically the same thing, now those who are checking in DFS should also check in BF that if we take main, it is a tree, it is its left child, is it right otherwise it will return false similarly. It has right child and it doesn't have right side, even then we will attend false 22. Okay, so this is the simple check, you are done in BFS also, so let's code from both, CFS and DFS too. If you will understand it well, then let's do this, so let's support, it is a simple question, okay, first of all, what I said is that if P = N people what I said is that if P = N people what I said is that if P = N people means root, van means root, you are right, then just both. It is done by trick, we will return it. After this, what did I say that if there is only one tap then either this tap should be done or it should not be done, if both are there then it is absolutely right, it is a good thing, but there is only one tap. There is null, so there is another condition in the middle, just don't take any one, remember this optimized condition, I told you that there is a long version as well, you can write that too, you are okay, we will return it to the case, okay, and what I said to structure wise. And the value should be from Vijay also, which I probably missed this line in the explanation. Okay, the value is also from If, okay, it should be from Well, which is not equal, the value of is okay, the value is also from, so by the way. P and K will go left, right? If we call this entry return, then why will it ever go right? We should get true on both sides, only then we will accept. Okay, let's say that it has been submitted. Let's solve this question by submitting. Let's reduce this. Let's solve it with DFS. Okay, the first check will be that if both of them have null then we will do it and one more is needed. Okay, we will put P and similarly why will we put it in q2, till now it is clear, after that the old family method. Isn't it cute, till these two become empty, these people will keep going on, then what will happen in these note vans, q1 will come out in the front and why will they pop it, similarly note tu will come out from where q2 has been taken out from q2 and YouTube has been done, okay If you have become equal then it is a very good thing. Now if you have become equal then you will have to see all this below left right. Okay then on the left side of note van if there is no tap Okay then it is a very good thing If you are present then okay And this did not happen, does it mean that only one of the two's left chal is present i.e. one of the two's left chal is present i.e. one of the two's left chal is present i.e. Nude van's left equal tu must have been tapped or Note tu's left equal tu na dooba must have been present. If both were present then it is a very good thing. Okay, so in such a case, the rate of return is fine for Note 2. If both are present then it is very good. We have attached the right side of both of them. It is okay. If both are not present then only one of them will be present like either of the Note Van. Right is present, if note tu ka is not present then note tu ka right is present, if noteban is not present then we will make it false in the case of return and in the last we will start return. If false is not present anywhere then it is ok, what does it mean? If we reached the end, it means we did not return false anywhere, everything was fine, let's see after submitting, this will also be done. Let's see great fair files question using BFS also. Similarly, both are easy questions, I understand. Yes, but there is a process for both to practice, still code, it's ok if you get the hang of it, then you can see the next video, thank you.
Same Tree
same-tree
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. **Example 1:** **Input:** p = \[1,2,3\], q = \[1,2,3\] **Output:** true **Example 2:** **Input:** p = \[1,2\], q = \[1,null,2\] **Output:** false **Example 3:** **Input:** p = \[1,2,1\], q = \[1,1,2\] **Output:** false **Constraints:** * The number of nodes in both trees is in the range `[0, 100]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
1,094
hey everybody this is larry this is day 21 of the leco daily challenge for september uh hit the like button hit the subscribe button join me on discord and let's go get started on today's problem carpooling um you're driving a vehicle that contains capacity of me the vehicle only drives these so going from left to right say give me a list of trips from number passengers starting and contains the number of padding that must be picked up and it'll get bigger give me this okay return troop it was possible to drop them off okay so okay and capacity is given to you uh so yeah this seems like a very so basically because um the car can only go from left to right or you drive these um you basically have this thing where you just go from left to right um and from that this should this motion or this idea this visualization of going from left to right should give you an idea which is uh the sweep line algorithm and that's basically what i'm going to do by converting these into series of events and then let people get offers and stuff like that uh basically very greedy and then see whether we're able to uh and we'll go over the details as i go do this but that's the general idea um it's okay for example at station one you pick up two person two people at station three you pick up three and that's not you know it's not possible right and so stuff like that uh let me know what you think i think this is okay so let's see uh so let's start with defense as you go to a list and then four i'm just looking at the trips format so yeah four passengers oops uh start and in trips let's put it in the events right so we add two events to each one um the first one is getting on so we add the number of passengers on the start event and then this latter one is the end right or negative passengers because that's how many passengers are getting off um the thing that i'm looking for here now is try to figure out whether we get off exactly at a location or end location minus or plus one uh sometimes in the problem context you have to figure it out in this case it is okay and what i mean by that is that if two people get on at the same time well if one gets off uh or people get on and off at the same station how do you hand resolve that right so in this case i think it should be okay um because in this case because the way that we sort if there's a tiebreaker between two locations uh the negative ones will always go first and then varian is that you can you will always have at most passengers on the right you can't go negative because you can't have negative passengers right so we want to greedy on uh so that's why this sorting order is okay because we want to agree on the number of passengers first on the same point but we're still going from left to right so we're sorting under the starting point so yeah so i think that's all we need for this part and then now we have to process each event at a time so for um let's call station yeah let's go to station just trying to find naming um and passengers in uh events right so let's have also uh current passengers current number of passengers maybe it's zero and then here we go okay current passengers we could simulate uh we add the number of passengers and because we set the delt the um the minus explicitly this allow us to get negative passenger so another way you can do this is actually have two events so for example uh for start you can have uh getting on the event and getting off the event right and then in this case you would write maybe something like and then this is positive and then you get something like if getting off you do negative or something like that but uh but that's already baked into how we structure this so that's okay and then now so there are two invariants that we want to keep here right the first one is passengers has to be greater than zero and this one is trivially true because just by the way that we construct this uh there's a symmetry to this and assuming start is always going to be bigger than n which is seems to be the case here um you know you can like the number of negatives can only appear after they're positive so it's always gonna be zero but i'm just putting here for visualization and we um yeah and so this is okay and then the other one is within capacity right uh so that's the other thing that i'm concerned with so this is good so we just continue maybe we could win in another way or maybe another way to write it is if this is not true um then we return force because that means that there's too many people on the train or on the bus or what the car uh or to feel right so if at the rate and we pass everything then we can return true uh and that's pretty much uh i think that's pretty much it we'll go over the complexity in this second let's put these things into the problem are the test cases in here how does this oh what is going on okay maybe i should have just done it a different way i am solving this live so sorry this is uh this part is less interesting but anyway okay so one detec code run it should be good um yeah and then maybe the only thing i would check is like empty or you know maybe just uh too much too soon or same station i don't i think can it be same they get on and off at the same station um no it cannot so okay so let's say the next station uh a thousand i don't know 10. yeah so just a few more test cases and you could add us to oh i guess hmm that's weird where is the list index our range did i have a typo it's a little bit awkward but huh i mean i don't do anything why is that weird those trips would be just empty trips right so this doesn't actually i don't know uh huh did i have a typo or an empty array this index out of range this is not um this is not a standard python ever so maybe it's just something on the other side i don't think uh let's prove me wrong i'm gonna submit it i'm confident enough about this uh and yeah it's accepted they don't tell you that this is this could be greater than zero that's why i added that test but maybe there's something wrong on the service problem uh a solution yeah so what is the complexity of this well we do create um an event for every trip or two events where we trip so it's gonna be linear space and with that result it's gonna be 2 n log 2 n which is n log n uh so n again time uh and space um of n space so yeah that's the problem i have here uh it's pretty straightforward and once you kind of get used to this technique you can see that um it's pretty straightforward right uh and it's very few places to make errors so yeah it's what i prefer anyway um hit the like button hit the subscribe button join me in discord let me know what you think about this farm how did you do you like cardboard uh maybe not doing the pandemic but anyway uh i will see y'all next prom tomorrow bye
Car Pooling
matrix-cells-in-distance-order
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location. Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_. **Example 1:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4 **Output:** false **Example 2:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5 **Output:** true **Constraints:** * `1 <= trips.length <= 1000` * `trips[i].length == 3` * `1 <= numPassengersi <= 100` * `0 <= fromi < toi <= 1000` * `1 <= capacity <= 105`
null
Array,Math,Geometry,Sorting,Matrix
Easy
2304
1,496
hello guys and welcome back to lead Logics this is the path Crossing problem from lead code this is a lead code easy and the number for this is 1496 so in the given problem we are having a string path where path of i signifies uh a letter in from the following n s e w representing uh north south east and west and one unit at a time so we have to start at the origin on a 2d plane and walk on the specified path and we have to return true if it crosses the path crosses itself at any point of time uh while traversing so let's see for this example first we move to the north so suppose uh we move one unit not we reach this point the coordinate for this will be 0 uh 0a 1 and then we move one coordinate East to the coordinate new coordinate now become 1 comma 1 and now we move to the South so the new coordinate becomes the 1 comma 0 so in the process we haven't reached 0a 0 yet again so that means that this uh part doesn't cross itself now let's see the another example now we have n s ww so first we move to the north yes the coordinate becomes 0 1 Now we move to the east the coordinate becomes 1 then we move to the South the coordinate becomes 1 Z and then we move to the West that then the coordinate become 0 this means we have Crossing then at 0 we have a Crossing that means we can return true so the answer is true so uh it is not very important that you uh map the coordinates correctly on like X on the xaxis like X first or the Y first according to the mathematics as you create the pier but it is important that you keep a variable for the vertical displacement and a horizontal displacement and at any point of time if the uh vertical displacement and a horizontal displacement become Zero from the point you can uh definitely uh return true and if at the end of the string after traversing the string if it does not uh reach 0 that means it does not cross the path so you can simply associate a plus with the North and a minus with the South for a variable and you take another variable and plus with the East and minus for the west or vice versa as you like and you we can keep a map and in the map uh that will be a map of pairs and uh we can keep the displacement for per unit like for every move we can save the uh displacement per unit displacement and we can keep a visited array or a visited set of pairs that keeps the uh visited locations at and at any point of time if you get the 0 again or if you get any other visited location in the set already then we can return to now let's come to the code section but before that do like the video share it with your friends and subscribe to the channel so we'll take a map of character and character no that will be a map of uh character with the pair integer and integer let's call this moves and a hash app so let's say for not we move zero and one and I'll copy this and then for South we'll move 0 andus one and then we have a East 0 1 Z and the then we have a West that will be minus one and West n ew all four complete now let's define a set of pairs of integer an integer this will be used to store the visited locations at and at any point of time if we again encounter a visited location we'll say that the path crosses itself but before this I think we need to add the origin in the set visited do add new paer 0 and zero so okay we have added the origin now we have to move in the now we'll take a pair at a time according to the moves so this will be the current move and that comes from the move dot get C so if it will be n the PIR return will be 01 if it will be S the PIR return will be 0 n minus one and similarly for w as well now in DX equal to current dot get so the key value is the X and Dy is the current dot get value right so the current do get value and then we have x + then we have x + then we have x + DX and the y + Dy but we need to define the XY here for this so let's Divine it now we need to define the new pair so the new pair consist of the X and the Y and if visited do contains pair then we return to if at any point of time we see that the pair already exist in the visited array we simply return I think it will be returned through because it is a Boolean function and otherwise we'll add the current pair in the visited so add the pair and if at all after all the loops we do not get a true returned we return a false now let's run for the sample test cases so the sample test cases are passed you can see let's try to run for the hidden test cases as well so hi test cases are also passed with a good time complexity and a fair memory complexity so the time complexity for this solution is O of n because we iterate through the string ones and the space complexity is also o of n because the we keep a map and so this map takes constant space but this set contains the number of uh path pairs so for this actually the uh the space OB becomes ofn you can also check the C++ Python and JavaScript also check the C++ Python and JavaScript also check the C++ Python and JavaScript code by going into the solutions panel and then checking my solution for you it will be available in the H section but it is not available now I think this one is my solution you can go check it out it can of the explanation intuition approach complexity the Java solution C++ Python complexity the Java solution C++ Python complexity the Java solution C++ Python and JavaScript and yes do remember to upot and also tell if you are a cat person or a dog person so I hope you understood the logic thank you for watching the video please like the video share it with your friends and subscribe to the channel if you're new to the channel thank you have a nice day
Path Crossing
lucky-numbers-in-a-matrix
Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`. Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise. **Example 1:** **Input:** path = "NES " **Output:** false **Explanation:** Notice that the path doesn't cross any point more than once. **Example 2:** **Input:** path = "NESWW " **Output:** true **Explanation:** Notice that the path visits the origin twice. **Constraints:** * `1 <= path.length <= 104` * `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`.
Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria.
Array,Matrix
Easy
null
1,636
hey everybody this is larry this is me going over q1 of the buy weekly contest 38 uh sort away by increasing frequency so this is actually a great example of using a key sorting by key instead of comparison so i mean i know that underneath it does comparison but literally um you want to sort by some value which is the frequency of a character and then sort them in decreasing order right so i actually missed the decreasing order part to be honest but basically i put everything in a counter and you could use this on a hash table and just doing a character or a number by number and then incrementing it in the hash table obviously it takes a little bit more coding i saw this during the contest in about 57 seconds and you could watch this afterwards uh live and while i stopped during the contest so i got to got the number uh for each number how many count is there that's what this does uh that's what counter does for me automatically and then i just literally sort by um sort by the frequency of the character which is just 40 named s of x uh but you know at home you have more time you could do this a little better and as a tie breaker we sorted by negative x which is a way to sort by from bigger to this uh smaller in terms of the number right so that's basically it uh a three-liner so that's basically it uh a three-liner so that's basically it uh a three-liner you could maybe just you get done just in one line if you really want uh but you might have to worry about you know efficiency but still two lines of stupid so if you want to play golf but that's basically how i did it and now you can watch me solve it live during the contest next i don't know why i keep pointing that though hey so i'm not getting submit uh yeah thanks for watching thanks for hanging out let me know what you think about this explanation um doing a little bit live so yeah hit the like button into subscriber and join me on discord and i will see y'all next uh problem bye
Sort Array by Increasing Frequency
number-of-substrings-with-only-1s
Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order. Return the _sorted array_. **Example 1:** **Input:** nums = \[1,1,2,2,2,3\] **Output:** \[3,1,1,2,2,2\] **Explanation:** '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3. **Example 2:** **Input:** nums = \[2,3,1,3,2\] **Output:** \[1,3,3,2,2\] **Explanation:** '2' and '3' both have a frequency of 2, so they are sorted in decreasing order. **Example 3:** **Input:** nums = \[-1,1,-6,4,5,-6,1,4,1\] **Output:** \[5,-1,4,4,-6,-6,1,1,1\] **Constraints:** * `1 <= nums.length <= 100` * `-100 <= nums[i] <= 100`
Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2.
Math,String
Medium
1885,2186
96
hello everyone welcome to a Cohiba in this video student solve the problem binary search tree before we start the channel how many unique values and is equal to 1 only one unique tree that can be built that is with 1 if n is equal to 2 we can build one as a root and 2 or 2 as a root and 1 2 unique binary trees if n is equal to 2 and if L n is equal to 3 we can build one as a root and 2 and 3 and these 2 can be performed in two different ways so this can be built 1 3 &amp; 2 if you take 2 as a root it can be &amp; 2 if you take 2 as a root it can be &amp; 2 if you take 2 as a root it can be built in one way and if you take 3 as a root that also can be built in 2 different ways these two can be built with 2 different ways to tell it will be 2 plus 1 for each if root is equal to 3 root is equal to 1 and Rho T is equal to 2 is equal to 5 but if you look into the pattern here so if you look into the pattern here if there is one nor it can build one if there is two nodes it can be built in two different ways now we calculated with three it can be built in five different ways so what we can do is let's say if n is equal to 7 we can start by the root node and then go from there so we need to do a multiplication of n minus 1 let's see and is equal to four once we place the root we need to distribute three different nodes two three and four and as we saw two three and four can be distributed in five different ways so we need to have the product of the previous functions so if we can store in some array like how many nodes can be filled like if there are zero nodes it can be one if there is one node and we can build one unique binary tree if there are two nodes we can build two unique binary three trees and if there are three nodes we found out that we can build five unique binary trees so similarly when four comes once we place two one as a root we know how many can we build with four different nodes so we can get this and add it to that similarly we will replace with node two and we will again add it to that so it's a multiplication of the previous nodes so we will use dynamic programming approach where we will take an array of n plus 1 and we will calculate with each node how many unique binary trees can be generated and we will place in the array and go all we need to do is we need to calculate from 0 to n and we will return the nth element once we are done with it let's go ahead and look into how we can actually code this out so let's define an array count with the size and plus 1 now we know two things if the nodes are 0 we would return one unique binary tree so the count of 0 would be 1 and if we have only one node we will we can only generate one unique binary tree binary search tree so we got both of this now we can go from - well it's tan and we need to start from zero it and count let's say we place one in the root we are left with one node and we need to find out how many unique binary search trees can be built with one node since we already have count of one is equal to one we would add that to the current one so let's go from this is i-4 and J is so let's go from this is i-4 and J is so let's go from this is i-4 and J is equal to 0 J less than or equal to 2 all we need to fill up the current index if there are two nodes given if n is equal to 2 how many nodes how many unique binary search trees can be built that is the sum of count of 2 plus count of so element is j counter Phi star count off J minus I minus 1 so that will give us the count and all we need to do is return count of 10 this is equal to I - J my bad this is equal to I - J my bad this is equal to I - J my bad this is J my bad it should be minus one yeah it went so let's look into what happened here so what we are doing is let's say if the nor is one we will have one unique binary search tree so let's take the array and +1 4 0 1 and so let's take the array and +1 4 0 1 and so let's take the array and +1 4 0 1 and 1 now let's say if the N is equal to 2 we come here and count of I which is count of 2 should be count of 2 initially its 0 plus count of say J 0 which is this one plus count of say 0 star count of I minus J minus 1 which is 0 which is 2 so we got it right so we will have 2 here now we increment say would be 1 and J should be less than or equal to minus 1 which in this case is true so we will come down again and so it's 0 plus 1 this is 1 at this point now again we are doing 1 plus count of I is 1 plus say is count of 1 which is 1 star count of I minus J minus 1 which is 1 so it becomes 2 so now we got 3 what happens here is now we are here we need to fill count of 2 which we will fill that's right and count of 3 what happens is count of 3 initially 0 plus 1 star hi minus J minus 1 which is 2 which gives us - so the count of three would be two - so the count of three would be two - so the count of three would be two initially then we increase the J index now it becomes 2 plus 1 star count of hi minus J minus 1 3 minus 1 which results in 1 count of 1 is again 1 which is which becomes 3 now this will become 3 again the loop continues and jet index will be this so we come here with 1 plus jet index to star I minus Z minus 1 0 1 we will end up with 5 this one we will update this with 5 that's how we know we can create why do you need one with search trees I hope it's clear please to like and subscribe this channel thank you
Unique Binary Search Trees
unique-binary-search-trees
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. **Example 1:** **Input:** n = 3 **Output:** 5 **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 19`
null
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
95
225
hello and welcome to another video today we're going to be working on Implement stack using cues and this problem is I'd say not quite an easy problem and depends on your implementation as well um so I'd say it's closer to a medium problem but in this problem you're asked to implement a lasting first out stack so normal stack using two cues the implementation should support all the functions of a normal stack push top pop and empty and then you want to implement it you want to have a push pop top and empty and you can only use standard operations of a queue which means push to back Peak from front size and is empty and so depending on your language the Q may not be supported natively you may simulate it using a list or deck as long as you're using a standard like Q operation so we cannot use pop from the back we can't use we can't look at like the last element we can only look at the first element and we can only pop from the left and here's this example so essentially let's take a look at what it would look like so you start a stack and you push one so like what a stack would look like is you push one then you push two and then you do top which gives you the last element so we're going to turn two then you would pop which would pop this to return it and get rid of it and then you checking for empty and it should return false because there's something in your key so we're going to do is we're going to show the way to do this with two cues and then the way to do this with one cue and the easiest thing honestly I found for this problem or these types of problems where you're doing stack with cues or cues with Stacks is try a few numbers and like make sure it makes sense and so what we're going to try is we're just going to try putting in the numbers one two and three and kind of just trying to figure out like okay like is there Q okay basically and so there's a few ways to do this so I'm going to show you the two Q ways so let's just call this q1 it's going to be a deck call this Q2 it's going to be a deck and in this first example it's going to be pretty straightforward so we're going to go through these one by one so essentially q1 will be our main like q and you can do this one you can do this a few ways essentially it's either your push or your pop is going to be open and then the other one will be over one in my case I decided to make the push of one and then the pulp o of n but either one's fine like you can ask you know like which operation should I prefer maybe in an interview and then if they said like they're all equal then you could do whatever but if they said like oh we're going to be doing more well I guess you can't really do more pops but let's say you like maybe if you have equal amounts of tops pops and pushes um top and pop here would be o of n so maybe you could swap it around to make push oven and then Tov and pop open so those are some things to think about but essentially so what we're going to do is pretty easy we're just going to insert one two and three and we're going to show what that looks like so when we push in one we're just going to push always into this first Q and that's pretty much it for the push we're just gonna do like a normal append and then so we're gonna push in one two three and we're going to show what it looks like to get rid of an element so we're gonna push in one we're gonna pushing two we're gonna push in three and so this is like so nor so our first Q is really like a stack but we're not going to be using any stack operation so now if we call Pop what we are going to do is we're going to be so we want to pop this last element but we can't like plot from the right so what we're actually going to do is we're going to pop from the left and insert into this first cue so we're going to pop from here and push to this which is allowed right pop we're using a pop left and an append so that's going to look like as we pop one we push it in gets rid of the one then we pop two because that's our first element now we push it in and now our Q is length one and now we could say like okay when the Q is length one then pop that last element save it in a variable right so we're going to pop this save it in some results variable and then that's what we're going to be returning and our for our second cue now we do the same thing again so we can just say like while we have our second cue let's pop and add back to the first key so we pull up the one we add it over here then we pull off the two and we add it over here and so now our Q is or our one is you know this and our three is popped and top is basically the same thing except instead of returning this three you're literally doing the exact same process except instead of returning here you save the variable and then you push it in at the very end over here so literally pull up and push are or sorry pulp and top are like a one line difference with two cues and so we can write this down here's our steps so pop or sorry push would just be append of one like a normal append pop when we pop left from q1 until one element left or so pop up from one and append to two until one element left in one then Pop That element save it then pop left from two and append to one until nothing left in two and then top same as Pop but at the end append the saved element 2y that's pretty much it um pretty straightforward right so that's the approach for this and then for our Big O complexity so our push would be o of one because we're just doing a normal append but for the pop we have to take all of our elements from here put them in here and then put them back and so that is going to be of n and top same thing is open so that's one way to do it and empty obviously is like really straightforward we are allowed to use the size so we can just check for the length of it right and if the length is zero then or were you if they say we can even use it as empty so if we can use this empty I don't know if like a deck has is empty but you can just check for the length and then if the length is zero then it's empty pretty straightforward okay so now we're going to focus on the other approach which is going to be the one key approach so we're going to go back delete some of this and we are going to do the one key approach and the one key approach you're going to see is pretty straightforward but there's going to be a difference so I decided for the 1q approach maybe you could do it both ways as well but just for me I decided I want my 1q to be a reverse stack and what that means is let's say if in a stack you would push one two three and it would look like this I want my Q to look like this that way when I pop the pops and tops are really easy right we're just going to pop left and that would be the same as this so essentially I want my elements to be inserted backwards now the way to do this is also pretty straightforward and so now our pushes are going to be o of N and our Pops and tops are going to be of one and let's just go through the same thing with like a few elements let's maybe do four elements so essentially for the first element so we're going to have only one Q now so for the first element it's pretty straightforward there's nothing there for the second element what I'm going to do is I'm going to do a normal append but then I will have a loop that says for the length of the Q minus one right we are allowed to get the length here over the Q um yeah so they let you size which is like the length so for the length of the Q minus one in this case it would be one we are going to pop left and append which means we're going to take our element delete it and put it back here and so once we do that our key will look like this and now if we want to insert a three let's see what that would look like so we would have two one three and then we're going to say okay for the length of the Q minus 1 Let's pop from the left and a pen to the right both valid operations let's look what that's going to look like we have to do that twice so we're going to pop the 2 add it to the back so then we will have one three two and then we do that one more time so we're going to pop the one added to the back and we'll have three two one so you can see like you keep doing this like we're gonna do one more maybe so if you want to add a four you do the same thing you would say okay well actually I guess like a slight optimization I mean I guess it doesn't really matter um let me think about that no actually no you do need to insert the element first yeah you do need to insert the new amount first because we're not allowed to insert out the front so you do have to insert the new element first and then rotate everything around but yeah so you would for a four you would add a four you would do a normal append and then you would do this like Loop thing three times so after one iteration you'd have two one four three you would get pushed out and pop back in and you would do it two more times so then you would have this then one more time so four three two one so essentially your Q is a reverse stack and then a pop is really easy because we just pop left and a top is really easy because we are allowed to look at the zeroth element and that's going to be that and then for the empty it's the same thing like you just check for the size so that's the one Q implementation I don't think you can make it more efficient I think you do have to make one of them o of N and then the other one o one but in this case I kind of swapped it around to show you what that would look like with a 1q and we are going to code up the one key now so for a knit we're gonna have one Q so we're gonna call stack but we're going to represent it with a deck for push remember we need to push the element we're going to do a normal appends so self.stack dot push appends so self.stack dot push appends so self.stack dot push we're sorry no we can't do click here pen x and now we need to do that Loop the length of the Q minus one times because for every element that was in there before that X we need to rotate it around so we could do this we could say for this value that we're not going to be using length self dot stack it's one so essentially like if this was like three we would do this twice and so on and if you want to use it if you want to have a full Range Loop but you don't want to like actually use this high value you can just do this underscore and that's that'll essentially say like I don't want to use this value in my actual for Loop but I do need to Loop you know whatever amount of times this is that's how you do that so we're going to say self dot stack dot append and then we're going to have that pull we're going to have that popped value you could do also do this in two lines if you want to save the variable so dot stack dot pop left which is a allowed operation so essentially we're going to pop left and then we're going to append what we popped left so if we had something like say we had one two we put on a three we would pop the one and then we would append it over here and we're going to do that twice um yeah now for the pop and the top it's really straightforward because we can just say return self.stack.pop left because now our self.stack.pop left because now our self.stack.pop left because now our remember our stack is set up in a way where it's very easy to pop because the item that would be bought from a stack is now on the left like our cue is a reverse stack essentially then here we could say return cell dot stack zero also really easy because we are allowed to look at the zeroth element um there might be like a top uh method in deck I didn't really look into deck too often I just use the basic stuff in deck like Pulp left push a pen and so on but we are allowed to use a uh Q standards operations including uh Peak pop from front so if there's a peak fall from front that's basically that okay and then for empty also straightforward so we need to return true if it's empty so we can say return true if not self.stack meaning the size of it is self.stack meaning the size of it is self.stack meaning the size of it is zero else false so what this will do is it'll just say like if the stack is like zero that this will evaluate the true and then we will return true otherwise it will be false oh yeah but that's pretty much it so pretty straightforward once you like recognize what you're doing and I would say for these problems I think it's pretty important to just like write out your steps and make sure it's kind of correct because it's very easy to it's hard to visualize it so I would try and try if you know if you do two cues two stacks whatever it is try to draw them out and see like okay here's like a sample operation here would be a cue with like three elements let's try to like put in the fourth element and so on so let's try to run this work yeah and you can see it's pretty efficient and yeah I don't believe I used anything that was not allowed so a pen was allowed let me just double check real quick though yeah so push to back which is append Peak from front which is Pub left and then Peak from or I guess this is the peak this is the pop so we didn't use anything that wasn't allowed and now let's go through the time and space and we can do this for uh every single methods obviously and it doesn't really matter so for push it's going to be o of n because we have to essentially reverse our stuff then for pop and top and empty it's going to be o of one because we are just doing one pop this as well and pop left in a deck is o1 um and you can actually if you want to and I did do this in JavaScript for example so the way you can make a queue or an array using an object and then if you are if your like front is deleted like normally in an array you have to shift everything over but if you use an object with keys all you have to do is just shift your starting key and your last key and then your index can just be in your keys uh maybe I'll do the problem on that like later on but essentially like if you're starting key was one and your last key was six and you were accessing like element zero then element zero would be your first key and if you're acting something like element at index two or something you just take whatever your first key is and add two so it would actually be at like key three and so on so you don't actually have to shift if you do this doing an object and I did actually make like a deck-like structure in um like a deck-like structure in um like a deck-like structure in um JavaScript that was I actually tested it against like a JavaScript deck that you could uh import and it was about the same speed so I was kind of happy with that one because in JavaScript uh it doesn't have a queue either it has an array and if you want to use a queue you have to do like shifts which are o of n but anyway that's uh too long about that okay so yeah so this time is oven this is of one and for this so we do have like our actual deck right so that's o of n because we are like storing all our numbers um but we aren't using any other data structures so it is over and with two cues so pretty much with two cues or one it will be the same thing like either way one of your things will be oven two of them will be o1 or reverse right pop and top are the same top and top are the same uh time complexity because they're basically the same thing and uh your space would also be oven because you'd have two cues which is still then it would be total n elements so you're not really saving anything it's more just kind of like a cool solution to look at but yeah um so it's gonna be for this Pro I hope you liked it and if you did please like the video and subscribe to the channel and I'll see in the next one thanks for watching
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack. * `int pop()` Removes the element on the top of the stack and returns it. * `int top()` Returns the element on the top of the stack. * `boolean empty()` Returns `true` if the stack is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. **Example 1:** **Input** \[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 2, 2, false\] **Explanation** MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `top`, and `empty`. * All the calls to `pop` and `top` are valid. **Follow-up:** Can you implement the stack using only one queue?
null
Stack,Design,Queue
Easy
232
949
Hello hello everyone welcome to difficult challenge today's question is the largest time from giving details should give in any with after land for india to generate maximum time button video politician id am id for the time 4 minutes ago 220 this simple question is innovation award recruitment of All your activities thought and day laddu solution and think of doing and administrative reforms and subscribe Thursday subscribed bigg boss 102 views one time in two variables maximum time fix - 110 test max time fix - 110 test max time fix - 110 test max player max and time fix - path of player max and time fix - path of player max and time fix - path of freedom created This is real and similar night minute media 20 minutes ago then serial se new year stitch do i will it dropped from i10 i20 resident length i plus that pointers her thrust length and g plus e want another law intern k10 k20 2010 k plus Plus To Keep In Mind As Always Looks Forward To Feel Right For Its Time That Is And The Other Is Necessary I Is Suggested And The Induction Same Script Is On WWW Subscribe Simply Continue Otherwise What You Want To Is Cute Calculate Using The Dual Dhule The Same Time In This Form And The Time With Your Dreams Are Not For The Spot Inter Arts Subject 205 The Signing Different Indices Different Bollywood Stars Pallu Aaj Minutes Of Units Part Hua Ki Peoples To Ki Mujhe Yeh Baje Mujhe School At Times That Sense Patil Unification 10 Vegetables Done With R Universe And Support Nodal Officer For The Minute Spot Minute Science Paper E Want Arvind Singh Minutes Units Particular To 9 6 - Is - 2 - K Particular To 9 6 - Is - 2 - K Particular To 9 6 - Is - 2 - K Notification With Logic 6 - - - For 123 Notification With Logic 6 - - - For 123 Notification With Logic 6 - - - For 123 456 Element To Maximum Possible You For The Different 6 plus one - - - Subscribe to Different 6 plus one - - - Subscribe to Different 6 plus one - - - Subscribe to Hello friends the fourth part will automatically with two 6 - - - K What automatically with two 6 - - - K What automatically with two 6 - - - K What means is maximum wave that i plus k in the equations 512 Calculator for the next speaker used this value and calculate The Soldiers Call Airtel 102 That Album Equals 12 Alex Reed Axel Exactly 6 - Came - From - 12 Alex Reed Axel Exactly 6 - Came - From - 12 Alex Reed Axel Exactly 6 - Came - From - Decade A Positive A Writing Turbo and Unlimited Calculate The Art Center Art What Is The Hotspot Ki Khushboo That Art Times In 0 Plus 808 I Laugh Similarly calculating 2 minutes spot a minute food also in the same logic R * 6 aplus 8 minutes means unit record the hotspot turn now spot is aa this election 2014 the course of per limit i only minutes equal school day 60th job limit for 2 minutes part Ki End Time Fix Total Time Sadhe Loot-Loot Ki End Time Fix Total Time Sadhe Loot-Loot Ki End Time Fix Total Time Sadhe Loot-Loot Conversion From 8 Minutes Total Time Exactly To Ki Aaj * 6 10 Foot Mathematics Yasmin And Ki Aaj * 6 10 Foot Mathematics Yasmin And Ki Aaj * 6 10 Foot Mathematics Yasmin And Defeated Total Time To Be Greater Than Next Time Ki School Image Divya Shringaar Time Next Time The Bank Will Update The Next Time to Total Time With Total Time That I Will Reduce Information Maths of Badr Current Affair Scene A Hard Max Minutes of Badot 2 Minute Spot That Pandey Almost All Have 220m to Take Another Corner How into Consideration The Facts That Sequence Se Minus One The Boys dance and nails her skin from school minus one simple tone mp tenth court case details unit when you for the number you for the time using this and twelfth result return i maths and cumbersome's half mic search plus fluid plus minus the most prior To adjust dusu president fateh nagar contact cassette unit collected for pimples infections kmsraj51 to 180 and not supported sites 935 se bindh part form of two digits of the earth and of minutes with to update whose something like video 945 and easy connection maximo latest qualities of A grand salute and creating another method private reduce friend drafting password enter number that tomorrow cant board 10 number to spring spr i anil check for sbi dot length ki kursi one in that case close up and brot at first year ki when bus i anil simply A written S P R O that institute of mess and all this method that parking a dark successful method Mridul Padak country wise eight phoolan 8 minutes show chhod bhi 808 note 800 cutting third semester system is on and test top were high court in a grant Her one blind research and one to one that Chaupasni time Indological hair observed mathematical and exploited by 60 updated on that maybe sorry for that order updates Pradhan Sube Singh B
Largest Time for Given Digits
cat-and-mouse
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
1727
1,424
Everyone welcome to my channel code sari with mike so today we are going to do video number 70 of our playlist lead code number 1424 is a very easy question and already we have made another question which is exact same diagonal traverse one on that. You will also get the video on my playlist, you will get it in the same playlist, today its part two is ok, this has also been added by google3 since names are given, return all elements of names in diagonal order as shown in the below images. This one is diagonal, you are looking at the direction of the diagonal, see how it is it like this? Look, the first diagonal that you see is the one in which element number is one, this one has only one in it, so see, first one is written, after that see, it is 42, okay. If it is 4 2, after that 753, after that 8 6, after that no, this is the answer, see how simple it is, let's see how we can traverse, the most important thing, let me tell you, we will understand this from the example, but before that Always remember that whenever we talk about diagonal traversal, whether it is a tree or a D- whether it is a tree or a D- whether it is a tree or a D- matrix, always think about the map. In diagonal traversal part one also we used the map. Okay, we will use the map in diagonal traversal part two also. So we will understand it from two approaches, the first approach is the most trivia, using map is fine and the second approach is quite unique, the second approach is but simple, there is nothing tough in it allows us to figure out things, the rest of the code is very simple. So first let's learn from approach one and finish it. Okay, so let's follow the values. This is your example, so I told you that in Diagonal Russell Part One, I told you that either now I told you or not. Whenever we talk about diagonals, we will use a map, then understand what we do in the map, like the elements of diagonal, like look at this, then look at this, elements of diagonal, like look at this, then before the diagonal element, I write, one is the diagonal element. This is mine, let's see what its index is: 0 is the diagonal see what its index is: 0 is the diagonal see what its index is: 0 is the diagonal element and which one is brother 4 2, one is fine, this is the second diagonal, let's see its index, what is the index of four? 1 is 0 and what is the value of two? W is 0 1 okay after that 753 is 753 what is the sen let's see what is the 2 0 f 1 what is the coordinate of 1 and 3 see so 1 is 2 not one 0 2 is not 0 2 is okay so I if You will write all the diagonal elements. Okay, if you write all the diagonal elements, then look at this diagonal carefully. Its row is zero. If the column is zero, then the row plus column will not be a constant. For this, the row will be zero. Look for this. Let's add more columns. Are there any more 0 Is there not 1 P 0 One has come let's see its 0 P 1 This also one has come so see For this its row plus column is constant Let's see its What is the value of row plus column? 2 p 0 2 1 p 1 2 0 p 2. You are seeing that this also has a column constant. Sorry, row plus column is a constant, so every time we know what we do which is row plus column. There are rows plus columns in the map, let's take the value of that and plus rows plus columns in the map, let's take the value of that and what values ​​are there in that row plus column, what values ​​are there in that row plus column, what values ​​are there in that row plus column, store it in a vector. Okay, so as the values ​​go by, let's in a vector. Okay, so as the values ​​go by, let's in a vector. Okay, so as the values ​​go by, let's assume that you are here. Okay, let's remove the diagonal, just assume that you are standing at 0. If you are standing here, what is its row and column, what is row plus column, what will come, zero will come, row plus column will come, zero, who is beyond that? I have inserted Sa element, who is 0 P is one, I have put one. Now let's assume that you come here, let's look at its rows and columns. Row plus column 0 When P and W came, look at one. This is element number two. Okay, now let's look at this. P 2 isn't its row zero and column T 0 P 2 will come so two on one has come 3 Okay now pay attention there are more things to focus on here don't miss now watch the video here come to this Now you are fine, its row is one, column is zero, 1 is 0 and if it comes then there is already one in the map, so we will add it there, which one is 0, four is four, we have put it, we are seeing the benefit of the map. Look, the advantage is that the row plus column is a constant, right, so put 0 and 4 in it, both were members of the same diagonal, okay, let's move ahead now, Abhay, you have come to F, but what is its row plus column, so it is two. But look, one more element has come, along with 3, 5 has come, okay, let's look at it. 1 P 2 is 3, so there was no t, there was no plus column, so we have put th here, put six, now let's come here 2. P 0 is its row plus column i.e. one more element has come in two so two is column i.e. one more element has come in two so two is column i.e. one more element has come in two so two is 7 ok now come here one more 8 has come in 2 P 1 3 ok now let's come to the last element what is its row? One last element has come on 2 p 2 4 four. That's right, so now pay attention. If you traverse this map, you will get diagonal elements. Look, which is the first element? So one. Have put one, let's see the second one. 2 fo is ok but see the problem. Now you must be seeing something like 2 4. Do you understand the meaning, every diagonal element is coming upside down? 2 fo has come upside down, whereas you have traversed. How did it have to be done, did n't it have to be done like this, so instead of doing 2 fo's, you have to do 4's, either you reverse it is here only or it is torn, either reverse it and get it printed, okay, either get it printed from here in this hey. Two, first write four, then write two. It's okay, so first we will write four. It's okay and after that we will write two. Okay, after that see 357, we will also write it in reverse. 753, see 753, so why write it in reverse, why was it necessary, you saw it here. It will be 753. Okay, after that, see 8 6. After that, see, our answer has come. Okay, what you had to pay attention to is that here you will have to traverse upside down. You will have to traverse upside down. When you came here, you did one. If you came here, you did 42 753. 86 9 On the contrary, you just have to print the values, so the solution has come here, it is okay for you, then one more thing you can do is that when you are storing in the map, then at that time you should store it in such a way that already It should be stored directly in it, meaning there should be 42 stores here instead of 2, 4. How can you do that, I will show you right now, see immediately, anyway you can do it, so see, before starting, I will tell you. Many people may question that brother, how can this brain be used? How will it come to someone's mind that if it has to be printed in reverse in the map then it will have to be done like this? How can it come to someone's mind? So I say, come on, understand it. Think for yourself, what was the problem, last time you started your traversal like this, then again like this, it is obvious that you must have started from row number zero, that is why first two came and then row number one. You must have done this, then four would have come, then you are moving upside down. You are moving upside down, that is why it will be printed upside down for you, how in which order you wanted it in the map, it was wanted in this order, because of the value, look at this diagonal. If you wanted this order, then why don't you start the row from here? If you are starting from here, that is why it was printing upside down, that is why I say start the row from the end, because see, printing starts from here. It is the same for everyone, this is the correct order, from bottom to top, look at the arrow here too, look here, the arrow is going from bottom to top, so let's start from the bottom arrow, let's see if we can find our solution, otherwise I will tell you. I am going to start from here, okay, we will start from Sen, what is its row, two is the column, zero is 2, 0, that is, zero has come in it, 7, now let's come to this, what is its row, what is the two column, one, okay, so 2. P has come on 3rd 8 Its row is 2 4 It has come on four Okay, after that again we will come here Row on my side Okay now print has come Four row is one column G0 1 P 0 Four on one has come Four has come on 1, okay, now look here, there is no profit, that is, on 1 P, 2, F will come. Look, on T, now F has come. Now see, the order is coming right. First Sen has come, now F is coming, isn't it now 1 P? 2 means that 1 will come on th, see, the order of this is also correct. First A came, then six came, now Ro will go up. On doing Ro minus, one went to zero, Ro came to one and 0 came to 1, T came i.e. and 0 came to 1, T came i.e. and 0 came to 1, T came i.e. One more element has arrived at 1 See this also It is being printed in the order 0 P 2 Another element has arrived at 2 3 See this also It is printed exactly in the order This time all the elements have been printed exactly like this Map Pay attention 753 8 6 753 421 9 Look 421 986 753 Okay, it is clear till now that we have corrected the order, yours is correct, now look, pay attention, how should your answer have come, it should have come from here, right? There should be one print first, after that 42, after that 753. Okay, so look at the diagonal number zero 0 p 0, this one is getting printed first, so let's start from row, that is, I am saying diagonal or row plus. The value of the column starts from the row. Okay, let's print the row first, so whoever comes to the row, who is brother, one is one, has printed it. After that, do plus on the diagonal, that is, you have reached the second diagonal. Brother, who is on the one diagonal? Print 4 2 directly on it. There is no need to reverse it. We had printed it in the correct order and stored it in the map. It is ok in the map. Plus the diagonal on the diagonal number two. Okay, diagonal number two has come, look, this is it, isn't it? Look, this is 753. This is 753. You are looking at 753. After that diagonal will be called plus. Then diagonal number three has come. This is diagonal number 8. After that, diagonal plus. If you did plus then diagonal number four came, isn't it okay? After that, if you did diagonal plus then F came, there is no F. That was all from zero till diagonal number four. So my story ends here, my answer came okay, that's enough. It was simple, good thing you came to know here that if you had started the traversal from here in the map, then look in the map, the elements stored in the correct order are 75 386, so let's finish it by coding it quickly and then After that we will come to approach two. Okay, so let's code it quickly. Okay, everything from my first approach, what I said is that we should always need a map, whenever what we are doing is doing diagonal traversal and comma vector. Of int m where what is int means what is my row plus column and what are the elements in the diagonal of that row plus column corresponding to it, they will store in the vector okay let's start and what I said is that Why did I start the row from numbers dot size -1? Why did I start the row from numbers dot size -1? I told you why I started from the bottom row, so that the elements are stored in the map in the correct order so that you do not have to reverse it. &gt; you do not have to reverse it. &gt; you do not have to reverse it. &gt; = 0 = 0 = 0 row was doing minus. The columns will go in the same order for int column equal to 0 column e lesson names of row dot size means as many columns as there are in that row will go because row because look the column can also be different look in the last row there are four columns right. Look here and there are only three columns in the second last row, so the columns can be changed, so each row has different column size, so look at the numbers of rows, dot size is ok, column plus is ok, now let's find the value of diagonal int diagonal. Equal to row plus column and push in the value of the same diagonal in the map, which one will be pushed, the numbers of row, whatever value is there in the comma call, it was very simple, everything must be clear till now let's move ahead, form our result. Vector result int diagonal starts from zero, remember for and keep adding plus to the diagonal till how long will you keep doing it until mp5 is the value of the diagonal found is not equal to mp.in If is not equal to mp.in If is not equal to mp.in If found then the value of the diagonal. Will keep printing the elements of OK for int and nam app, print it from as many elements as possible in this diagonal of the app, ok result dr push and back, ok, here nam is printed, save means stored in the result, ok and In the last I had said that keep doing plus on the diagonal, as soon as the value of diagonal comes to the value which is not present in the map, then the while loop will break our and return result in the last, ok, let's see after submitting. Fully we should be able to pass all the cases its time total number of elements because we are visiting all the elements only once maximum is ok so off and time complex is t and its space also if you see it is off a This is because we have stored all the elements in the map. Okay, so I hope this approach is clear. Now quickly let's go to approach two. Indeed yes, this approach of ours has been accepted. Quickly now if we understand approach two, then look at the approach. Let's try to understand, see, I will not tell directly that yes it is BFS, then do it like this, I never make it in videos, I always tell the thought process, so I want to tell you that it is very strange, how? Some people will think that this can be done with BFS, okay then I am presenting you Intu and its thought process in my own way. Now try to understand. See if you remember what is the purpose of BFS. Let us assume that this is some source. Okay, so what BFS does is that you can traverse through this source level by level. Let's assume this is a source, then the next level is this. The number of elements we visit there, after that the next level is this. All those elements are visited at once, isn't it, then the next level is this, the next level is y, and the meaning of the whole level can be understood like this, meaning it does level by level traversal, that is correct, so this level number has become zero, level number. Level one is done, level number two is done and so on, okay, that is the purpose of BFS, isn't it? Print all the levels at once, so do you know what is its thought process, if we assume that you have accepted this as the source? Okay, if you consider this as a source, then look, what is the next level of this source, look, it is this one, the next level after that is this one, what is the next level after that, it is this one, so pay attention to one thing. This is the source starting from 0 co 0 its next level look this is its next level then this is the next level this is this so what is actually happening in BFS Yes, it is happening level by level, we have to traverse it, we just have to pay attention in the towsal that the printing should be like this, from bottom to top, okay, here I understood that okay, someone can think that yes, this is the problem of BFS. Okay, so as soon as it is understood that a good BFS can be installed, then again the question comes that okay, BFS can be installed, now let's see how to install it. Okay, so now look, pay attention here I told you. He said, who have I considered as the source? Have I considered 0 as the source? What did you always do in BFS? Do you remember that you used to put the source in q first? It is obvious that things are starting from there. Okay, this is my q. We will approach it directly like a thought process, I will not tell you to push it like this, not in q, you should understand the reason, what is the nature of q, that is, what we used to do in BFS, first put the source in q, then our source. What we assume is that the source is my So for this, who are its neighbours? One is this one and one is this one and first I will put this one, why this one because first I will put one 0, so yes, it is like that, first that element will be printed and then this element. It will be printed and the order should also be the same, so I print its neighbors, so its neighbor one is this one, let's see who is the one below, let's assume that look, row ji was popped, so if this is row and this column. So what will happen at the bottom, look at it will be 'Psv', that is, the 'Pv' happen at the bottom, look at it will be 'Psv', that is, the 'Pv' happen at the bottom, look at it will be 'Psv', that is, the 'Pv' column is the same, neither is the 'Pv' column or 'V', column is the same, neither is the 'Pv' column or 'V', column is the same, neither is the 'Pv' column or 'V', I have put '0', that is, it I have put '0', that is, it I have put '0', that is, it is in my queue right now. Okay, after that, which is its next neighbor? Its second neighbor is this, its row is the same but the column is + and, its row is the same but the column is + and, its row is the same but the column is + and, right, that means I am saying that if this is r c then r is + 1, this is and this is r + 1 c. So far it is r c then r is + 1, this is and this is r + 1 c. So far it is r c then r is + 1, this is and this is r + 1 c. So far it is clear, then what else? Hey brother, 0 1, okay, I have put it, now you see what we will do, then we will tell this guy, we will remove him first, see, all his neighbors are covered 0, now one more level has been printed, okay 1 0 Let's pop this, okay, 1 0 has been popped, okay now you will say 1 0, if you put your neighbor, then 1 0 will be said, brother, my neighbor is one below and this one is below, okay now Look, paying attention is a very important part, here see who is this one of your neighbours, see if the one below is 2 0, then put that one is fine and look at the other neighbor, who is Wow, this one is fine, put Wow, Nav is fine, 0. These were the two neighbors, he printed it, now the next element at this level is Row, I popped 0 and now look, pay attention, zero earning means this one, see who are its neighbors, one is this one, so first. Let's print the one below only so that it gets printed in such order. Okay, so first look at the one below, what is its index. What is its index? Just pay attention, Nav, we have already printed it and have added it. There will be duplicate elements once. And Vanav is coming, okay, so either you can do it like this, take a map or make a visit, okay and write there that if we have put it in Nav, then mark Vanav Kaam as white. If you mark it as true, then you will not put it in the queue again because this guy, look, let me tell you again, this guy has put 0 and he has put this and he has tell you again, this guy has put 0 and he has put this, so this guy is also in this level, in the level that was going on, he has put this. If you put it in then see that it has been inserted twice, otherwise if you had marked the vegetable, it would not have been inserted twice, that is fine, then you can take the vegetable separately and mark it as true, but it should be there even without the visitor. It is possible if you put a simple cheque, that check can also be done, let me explain to you, first of all understand that yes, we will mark it as visited, then after that, if it is wasted, then it is not put in the queue, it is okay and so on. After this, his next neighbor was Nana Rotu, so that's the thing, he has not visited yet, so if I put two, then this is my next level also got printed. Look, there were three elements, yes, this, 20, 21, and no, 0 and 02. Look, the diagonal elements are being printed correctly. As you keep on popping, you will keep on printing the same elements. Remember which one was popped first, 0 was popped, so whatever element is there in 0, it has been printed. Then the element which was in 'V' was it has been printed. Then the element which was in 'V' was it has been printed. Then the element which was in 'V' was added to the result. This was also added to the result. Now the turn will come for the next level. So look at the next level and see who is the first one. We will pop 0. Okay, see which 0 it is. This is it, we will say that brother, okay, so add this and add this, add 0 to 0 and add tv to tv, add tv to it, okay this is popped, who is the next guy, what will he do, look at his neighbor. Who is this and this is this, do, look at his neighbor. Who is this and this is going to be added again, so we will mark it as a visit so that we will not be able to come again, okay then this and this will be added again, so now you understand what we are doing, right? Then we will print th as soon as we pop the element, like 0 is printed, the element which was in forest is printed, then 0 is popped, then its element is printed, so it is being printed in the same order, is n't it BFS? I have understood how to do it, I just want to explain one extra thing to you that I want to avoid the separate preparation that has to be taken, so I will show you how I will avoid it, okay see. Understand that what we are trying to take is to mark the data structure as wasted and want to avoid it, so look here, pay attention, in the beginning I had said that 0 k is my source, so put it in q. Given r c, I am taking it as 0, so I popped it, okay, 0, I am taking this as r c, okay, so its neighbor is this, isn't this and this, so okay, meaning row plus and comma. Why do we have to put these two column and row comma column plus now i.e. aa psv comma now i.e. aa psv comma now i.e. aa psv comma column and first put this and after that column sorry row comma col plus and ok we have put both of these so now pay attention to one thing, put this Gave it and inserted it, now pay attention, it is okay, see, now its turn will come, next time this guy will say that I have to insert this and after that I have to insert this, okay this guy will say that I have to insert this, but this has already been inserted. I will not put this one and this one, if you have to put this one, then you are looking at this, if you have not put it again, it is okay, then why not put it again, because this guy had put it and eaten it is okay, now let's observe the same thing here in this one, it is okay. Now, pay attention, what will this guy say that I have to put this neighbor and I have to put this neighbor, okay because yes, the diagonal element is going like this, so first this will come, then this will come, okay, so he said that I will put this first. After that, I will put it, okay, then what will he do? Will he say, no, I will not put it because it has already been put, that's it, I will put it, okay, I will not put it, he said, I will not put it has already been put, just I will put it, okay, I have seen it. Have seen this, now let's look at this diagonal element, this guy will also say the same thing that I will not put the one below because it has already been inserted, here I will just put this one, so one thing you are paying attention to is that only the elements with column zero are column zero. Only the bottom element and the right one are able to be inserted. Look at the rest. Pay attention. The rest of the diagonal elements are able to insert only the one on the right side. Okay, what does this mean, like look anywhere, it will be applicable everywhere, look at this. He is the guy with column zero. No matter what. Column is zero. Look, he had put this one too. After that, he had put this one. After that, this guy had not put the one below because he had already put this one. It's fine, he just wrote it. If we put it on the side or then we will do the same thing that if the column which is there is zero then it is okay then only who will we put in it means dot push, who is the guy at the bottom brother, the row plus and comma column is clear till here, this was a very important thing. That's why I told you separately here that if the column is zero then it is right then only the one below will be inserted, look at the column row comma, it will be clear from here, again let me tell you why the source has inserted these two. Had these and these, now it is their turn, so first this guy will pop up, he will say, brother, I am column zero, so I will put this one too, and I will put this one too, look, I will put the one below too, see, this one below is the one below, so call it, so that one. So it has been inserted and I will put this also, so both of them have been visited, okay, so I will write v here for now that both are printed, now it is its turn, it will say that brother, I am not column zero, right? That's why I will not put the bottom one, I will just put the right one, so if it has been visited, then look, this diagonal one has been completely visited, okay, that's why I have put a check here that the one with column zero should not only put the element at the bottom. If you find it is ok, then each element has two neighbors, one below and one on the right side, so what about the one on the right side, the row is the same, the column is plus and it will be ok, so there is no check in it, the element on the right, so put all of them. The row is the same and the column is plus and these are the two things we have to push, one this and one this, it's okay, just check one thing that if you are putting the row float, then check that the row float is out of bounds. If not, then put here also that row psv which is less than those numbers, dot size should be there, should not be out of bounds. If you are putting column plv here also, then put a check here also if column pv is. Lesson: whatever row is there, it column pv is. Lesson: whatever row is there, it column pv is. Lesson: whatever row is there, it should be less than the column size, it should not be out of bounds, otherwise you will have to put a check anyway because if you are putting row plus one, if you are putting column plus one, then you will have to put a check for out of bounds. The most important check was that only those elements in the column which has zero are able to insert the elements below, I am not allowing the rest to be inserted because it will be duplicated, then that is there, see, we need to maintain the wasted here. If you don't have to see the dry run then try it, I will do a simple dry run for you 1 2 3 4 5 6 789 ok index number 012 ok let's start with K first put 0 ok this one It has been visited. Let's pop it. visited. It has been visited. Let's pop it. 0 has been printed. Let's look at its element zero's neighbor of zero, who is four and two, so since its column is zero, this is as, so this is the one below. So he has put 0 and who has to put 0 and 0? Okay, these are the elements of the next level. Now the first element in the next level is 1 0. Its row is r and its column is zero. So, since its column is zero, what will we do, we will put its bottom element also, look, we will put this also, two comma 0 and its right element, we will put one comma, vav and so on, you can complete it easily, but I think you will have to Main important point is understood let's code quickly and just finish it ok let's make it from approach two i.e. using BFS i.e. using BFS i.e. using BFS In BFS what we always take first is q of int k but since this time we have If we want to store the coordinates then we take pair of int comma int so that we can store the row comma call. Okay first of all push the source two sources remember who we killed 0 is okay and take a vector named result. In which as soon as the elements are popped, they will be added to the result, while not off cud MT, the same old code of our BFS, first of all, take out the a, row comma, call is taken out, q is fine from the front, q, the dot is popped, now look, pay attention. As soon as it has been popped, put it in the push under back. You will put this in the numbers of row comma call because you have just popped it. Now look, pay attention. I told you that why do we have to push two people, one is my neighbor below. And one is on the right side, then who has to do row plus one, that is, this guy is below, the column is the same, but I had said, for whom will we insert the element below, only if the column is zero, otherwise duplicate elements will come. Okay, and since row. If you are entering 'Pv' then Okay, and since row. If you are entering 'Pv' then Okay, and since row. If you are entering 'Pv' then check for 'Row' whether it is 'Row' or not 'Row plus one', what you are check for 'Row' whether it is 'Row' or not 'Row plus one', what you are check for 'Row' whether it is 'Row' or not 'Row plus one', what you are entering should be less than the numbers dot size on the right so that it does not go out of bounds, okay after that the neighbor on the right side is mine. Which row will be the same? Column will change but since row plus column is P then check the out of bounds of column P1. It should be smaller than the numbers of row dot size. Till here it is clear and in the last return result to us. What a simple code it was but it was one of the most beautiful use of BFS I have ever seen when I did its time completion and pay a little attention to the space complexity. What could be the largest size of q which would be the largest diagonal of this number? Okay, so I can say like this, the maximum diagonal size is not diagonal, meaning the maximum diagonal is the largest diagonal which will have the maximum number of elements. The size of q will be maximum only so much, otherwise it will be smaller than that. Okay, so the maximum diagonal size can be calculated mathematically in any way you want. If you want, you can find it, okay, if we assume that in the year case, n is the cross of n, if you have got it, then you can find the diagonal from the Pythagoras theorem, okay datchi.
Diagonal Traverse II
maximum-candies-you-can-get-from-boxes
Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_. **Example 1:** **Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,4,2,7,5,3,8,6,9\] **Example 2:** **Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\] **Output:** \[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16\] **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i].length <= 105` * `1 <= sum(nums[i].length) <= 105` * `1 <= nums[i][j] <= 105`
Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys.
Array,Breadth-First Search
Hard
null
459
hello everyone this is cpedit and in this video we'll be solving this problem repeated substring pattern so in this problem we have to tell whether we can create this original string using multiple copies of its substring so let's get started so for example the input is abab so the example is a b so if we choose this sub string and we use this substring two times then the substring will be the string will become a b so yes we can create the original string using this substring so the answer is true in this case now let's see what happens in this example abc so you can see that we can create the original string using substring of length 3 that is abc so one thing that we can readily observe is that zeroth character must be part of that substring which we are choosing it doesn't make any sense to find the substring in between the string so we can find the substring in the prefix of the string itself so the second thing we want to observe is how many patterns that we can choose so if let's say the length of substring is n and let's say we have the character as a 1 a 2 a 3 so let's say n is 6 in the first case so a1 a2 a3 a4 a5 and a6 so in this case we can choose the substring of true length because we can create this plus this we can also choose the substring of 3 length so the pattern can be this but we cannot choose a substring of length 4 because if we do so we'll end up with only two elements and we won't be able to complete the original string so let's see what happens in n equals to seven so it is a b c d e f and g so we have seven characters in this string so if we choose one we can do so we can choose one but now we cannot choose any other substring because if we choose even two we won't be able to we'll be left with one extra character at the end and if we choose three we will still be left with one extra character at the end so this gives us an idea that we can only choose the pattern length which is a divisor of m so i am writing it here pattern length must be a divisor of n so we need not check every prefix so we won't be checking every prefix like this prefix this and then three length then four length and so on and so forth we just need all the lengths which are divisor of n so that gives us a very good starting point and let's see what are the constraints so they are saying that the constraints will be 10 raised to power 4 so length of input will never exceed 10 raised to r4 so if we see how many factors how many maximum factors a number of this size can have we find that no number will be having factors more than 64. so let's see how we can do that so what we can do is for every divisor of n check if the prefix of that length is a pattern if yes then return true else we can say that no pattern was found so we can simply return false so let's see how we can code this problem so for i equals to 2 to square root of n we are finding all the factors of m so for every factor we are checking if this is a valid pattern so we have send two arguments the pattern and the string text itself and then we'll be checking if it is up if it can form the original text so if it can will return true so one thing to note is that this for loop will be called only at most 64 times so this for loop will not be called more than 64 times so yes this is accepted so that's all for this video see you in the next one i hope you like this one please like share and subscribe our channel thank you
Repeated Substring Pattern
repeated-substring-pattern
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. **Example 1:** **Input:** s = "abab " **Output:** true **Explanation:** It is the substring "ab " twice. **Example 2:** **Input:** s = "aba " **Output:** false **Example 3:** **Input:** s = "abcabcabcabc " **Output:** true **Explanation:** It is the substring "abc " four times or the substring "abcabc " twice. **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters.
null
String,String Matching
Easy
28,686
392
hey everyone so we are looking at leak code 392 is subsequence and this is going to be building off of that work that we've been talking about previously in this data structures and algorithms series so hopefully you've seen the last video where you have a solid understanding of some of the logic and how to approach these coding interview questions so let's jump into this one we're given two strings s and t right and we would just want to return true if it's a subsequence else we're going to return false so what is a subsequence the leak code explanation is here but i think it's a little bit convoluted and we can simplify that by just checking out an example so if we look at example one that we're given here s is equal to a b and c and t is equal to a h b g d and c right so essentially a subsequence will be if all of these characters that we're seeing here in a if all these characters exist somewhere in t in the same order that they are in s right so if there's letters in between like you can see a is here and b is here but we've got an h in between that doesn't matter we can just ignore that h right and then we can see here we have a c but g and d are in the way that doesn't matter we can just ignore g and d and so we can see that yes a is here right b is here and c is here so yes s is a subsequence of t because a b and c exists t in that order and we just ignore the characters in between so that's essentially what a subsequence is so knowing that we can break down this problem and try and tackle okay how do we actually solve this problem right how do we actually implement this problem into code so what we'll end up doing is we'll be using a counter that's kind of the common naming convention for it in python of course like always you could call it whatever you want um but we'll call it um i call it tracker let's say right let's call it a tracker so essentially what we would do is we'd have our tracker value here and we'd start with it set equal to zero so essentially the way that we're going to iterate through t and compare the characters in s and find out if our characters in s are in t is we're going to utilize this tracker and the way that's going to work is we're going to leverage the fact that if we set tracker equal to zero right and then we were to say s tracker right let's say we said s tracker what would that be equal to well that would be equal to a right if we were to call up that s tracker value right because in a b c a is at the zeroth position b is at the first and c is at the second right so knowing that what we can do is we can do a for loop right very easy we would do a for loop right and we would say something like four chars in t right so we would be looking at all of the characters in t we'd be stepping through them through t and we'd basically be saying is the position at s tracker is that equal to chars right is s tracker equal to chars and so basically what we're saying here is so in this case we would be we'd be iterating through the chars would be representing the various values in t as we're stepping through them and so we'd be comparing their value and so we'd be saying is a equal to chars right in this case so and so we will step through and so we would say okay yes like in this example in example one that leco gives us we'd start by looking at a and then we'd be saying okay now we're going to compare is s tracker in this case a is that equal to chars and so we could say yes char is here and chars and t looking at the characters in t we have a and so yes a is equal to a so what we will then do is we will take our tracker and if that's the case we're gonna take our tracker right and we're gonna set it to plus equal one we're gonna increment one so tracker in this case would now be um b would be the letter b right because tracker is now equal to two right tracker now equals two and so this would be if we called s tracker now this would be um equal to the letter b right and so now we're iterating through chars and we're looking for the uh we're looking for the letter b in t and so once we find it of course we would then tracker would then be updated to plus equals one and then we would look for c and so on and so forth until we've iterated through all the characters and we've either found a match or we haven't right so hopefully that makes sense i think once you see it in the code it will kind of clarify everything for you the explanation can be a little bit strange and make it seem a lot more complicated than it actually is so we'll just jump over to lee code now and we'll see what that solution looks like and we're going to code up that solution based on that example and those notes that we took earlier so what's step number one right we want to define our tracker that we talked about so that we can keep track of those values that we've seen in t and make sure that they're equal to the values that we have in our string s so we can confirm it's a subsequence right so our tracker is set equal to zero to start off with because we want to start with the first character and s and then we want to look at all the characters in t so that we can do our comparisons and check the subsequence right and then we're going to say if s tracker like we talked about if s tracker is equal to chars then we want to update the value of tracker to be plus equal one right so that we can check the next letter and then check the next letter so on and so forth right and then we're going to do our return and we're going to say return tracker equal to the length of s right because if tracker is equal to the length of s then that would be then if that's true then we would you know we would return true this is just basically um this is doing uh sort of like a logical operation so it's going to say if basically when we call this return tracker equals length if that's true it'll return true if it's not true it'll return false so that way we don't have to say return true or false that function will just do it here by default and so the only other thing that we need to do here is we need to make sure that we can actually break out of our form we don't want to end up in a sort of infinite for loop here so we need to just have a condition that'll say that if our tracker is equal to the length of s we want to break right we want to break out of that uh that for loops that we don't just keep going through it infinitely right so if our tracker is equal to our length similar to what we have down here then we want to break out of it so that means that we've seen all of our characters and we're good to go we're good to take off and get out of our for loop so let's run this and just make sure that it works and it does so you can see here that it's really efficient i didn't mention it in the notes but this is working in o of n time and i can write it here it's o of n time and it is o of one space and that's where n is the um the length of our strings all right so this is going to be done at all oven time over one space and yeah you can see here that it's very efficient and the code is probably easier than you thought it was that explanation could have been a little bit more confusing making the problem seem tougher than it is but essentially it's just levitating this tracker and you can see here iterating through our loops so code is very simple so thank you so much for watching and we'll see you in the next video
Is Subsequence
is-subsequence
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not). **Example 1:** **Input:** s = "abc", t = "ahbgdc" **Output:** true **Example 2:** **Input:** s = "axc", t = "ahbgdc" **Output:** false **Constraints:** * `0 <= s.length <= 100` * `0 <= t.length <= 104` * `s` and `t` consist only of lowercase English letters. **Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
null
Two Pointers,String,Dynamic Programming
Easy
808,1051
1,689
hey everybody this is larry this is me going over weekly contest 219 q2 partitioning into minimum number of deci binary numbers uh hit the like button hit the subscribe button join me in this card let me know what you think about this problem so for this problem to be honest i was a little bit thrown up by it because i wasn't it felt and i don't mean this to be bragging or you know whatever but um but i'm just going for my thought process when i was solving the problem and you could watch me afterwards solve it during the contest and the thing that surprised me about this problem was whether um i felt too easy almost uh and i like i said i don't mean to say that to brag it's more that i wasn't like i had doubts because it's a medium i was like okay this fuse a little bit too easy for medium and the reason why that is that well this is pretty much it um so the idea is that okay so you have a number like this you know we take a big number the ideas that have a number we can always break it down to uh in a way it's greedy right you always construct a number if you can if this is not zero so here it's a two okay this is really long so maybe i'll just take a slightly shorter one for example um okay so that means that the first number will be one the second number will be one so this is greedy um and then we have one but we already right now so the two goes to zero so we could go to zero and then one um and then so forth right and from that i'm trying to be really careful not myself but uh from that dot here i think this is okay which is that if you do this in a greedy way no matter what the digit that has the highest number that is to your choke point right that is the number that gives you the most repetition and of course at most that's gonna be nine because you have nine digits so you can actually even simulate the greedy algorithm if you like but during the contest what i did was i just go for each digit in the string and for each digit i just take the max of those digits and i return it that's pretty much it uh this is why i was very surprised because i actually solved this during the contest in about one minute and some of that was just me second guessing and not sure whether i was right um because it was just a little bit yeezy because recently also there's been a harder problem so um anyway that's all i have for this prom uh it's linear in terms of uh the time and in space we do not use any extra space it's name because we look at each digit once uh that's all i have watch me stop this live during the contest and ah what oh hmm so yeah thanks for watching uh let me know what you think about today's prom and just let me know what you think hit the like button smash that subscribe button join my discord more uh so you can chat with me and people and ask questions and i will see y'all next contest next farm whatever bye-bye
Partitioning Into Minimum Number Of Deci-Binary Numbers
detect-pattern-of-length-m-repeated-k-or-more-times
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._ **Example 1:** **Input:** n = "32 " **Output:** 3 **Explanation:** 10 + 11 + 11 = 32 **Example 2:** **Input:** n = "82734 " **Output:** 8 **Example 3:** **Input:** n = "27346209830709182346 " **Output:** 9 **Constraints:** * `1 <= n.length <= 105` * `n` consists of only digits. * `n` does not contain any leading zeros and represents a positive integer.
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Array,Enumeration
Easy
1764
1,808
hey everybody this is larry this is day what q4 delete code uh weekly contest 224 maximize number of nice divisors um hit the like button to subscribe and join me on discord let me know what you think about today's prom so this one it's um you look at this answer and it's weird uh it's actually a very ad hoc one-off problem hoc one-off problem hoc one-off problem the short answer is that um well the one thing that's misleading is that um given here right um let's say we look at the prime factor five and you have these dividers right um it actually doesn't matter that um that you know you don't need fives that's what i'm saying it could have been three so you always just take the minimum devices and then the question is um well how do you figure out how many nice divisors are there right and while the number of nice divisors will just be um the com the um the multiple the product of the frequency table of this right um for example there's three twos times two fives or in this case it'll be three times two which is six and you can kind of see why that is the case because um you can use that many um you know because this the product of this is 200 and you can use some subset of uh twos and you use some subset of fives but you have to use at least one two and one five so that means that you use either one two or three two okay one five or two five so then three times two um so yeah so that's basically it and then one thing to note is that if you put that down by if by the frequency table then um that means that you have this you know in this case 3 and 2 has to equal to 5. i think that's obvious because that's just the nature of the thing so then you have the idea of okay you have x sub i or x of 0 maybe plus x sub 1 plus x sub 2 um dot plus dot you know plus x sub uh k is equal to n right so that's how you break it down and then you want to maximize x sub 0 times x sub 1 times x sub 2 dot right i want to maximize this um and from that there's actually um whoops sorry got a little bit confused um got five wrong answers on this because i'll talk about it um but yeah so you want to maximize this um yeah and then the idea is okay well how do you maximize this um it turns out that and for me i actually have solved this problem before now that you've broken down the problem into like this i have solved uh a variation of this problem before um well i've solved this exact problem before just not you know with this formulation where you have to kind of convert that this form this problem into this problem and now basically you have a sum of k numbers um for some number of k and yeah and it turns out that the answer is that it's always going to be um you know you could play around some powers and you could play around some stuff um and the answer turns out that it's just uh it's going to be all as many degrees as you can um and the last one would just be whatever is left over so then the answer is for example you have three plus dot plus three plus dot uh plus well n minus three or at mod 3 is equal to n right so that's basically um going to be your maximized answer i'm not going to go over this part too much um you can kind of do the proofs or maybe google that i don't know internet a little bit but that's the basic idea and once you kind of you know figure that out then it's just three mod uh three to the you know and dotted by three roughly speaking uh plus you know uh yeah and that and two to the whatever right two to the and my three roughly um yeah and that's basically the idea here um yeah uh yeah i'm a little bit sick today so my apologies but this is my implementation and um yeah the hardest part is just you know converting this problem into kind of this problem um and for me actually because i knew i had this code somewhere um but i think the formulation or the so it's a little bit different so the base case is a little bit different but honestly i also got um i was just very careless because i knew that by the time i even started this problem uh this is a little bit better contest speaking um there's a lot of maps so for interviews i probably wouldn't worry about it because this is just a ridiculous problem for an interview but um but yeah because i just messed up on mods i have basically uh i have five wrong answers on this one is a little bit sad i basically um yeah i basically forgot about the i don't know i'm a little sick today so i'm not even explaining this well my apologies uh leave a comment in the below but basically yeah this is just uh what i said um oh this is actually this is a little bit off this is what it takes to get to three so um but basically that's the idea um yeah uh yeah i had three wrong answers or two wrong answers because or three wrong answers maybe i just forgot about the mod here um i forgot this mod and i was like as soon as i saw it i was like oh i forgot this one but then i also actually forgot about modding the nz times two and also the answer times four because i am just silly and then i just forgot about the base case because um the other problem that i saw it had different base cases so i was basically copying and pasting mentally um but and that's why sometimes i need to slow down but there was a lot of time pressure because i was like oh i got to get this quickly um but it turns out um yeah i was uh i was a little bit bad on this one uh cool uh yeah you could watch me sell it during the contest next um you could i think it's kind of funny especially if you fast forward to the parts where i am struggling with the wrong answers and just kind of i don't know mental i think i had the idea and i had to promise something i even used a little piece of paper to kind of write this out um but i think i just lost discipline near the end where i was just like oh like if i had just spent an extra two minutes or whatever slowing it down and getting it right i would have saved myself 25 minutes of wrong answers but i was just rushing it because i saw so many people got this one so fast that i was like oh i have to do it quickly yeah well um hopefully that's uh you know um you know stay with your plan and uh and yeah um yeah stay with your plan and you know i mean because my plan for this contest was to slow down but i still rushed it anyway you can watch me sub it live next this i'm gonna be asking for hmm number five so so hmm but nine hmm so let's see so my so smart so okay oh no uh two watched it because it was okay that's unfortunate 64. i have a typo well that's awkward 64. this one i messed up oh man i am just careless i found it and then i got killed this huh did i forget no wow i mean i got uh this is the silliest um this is the silliest way to get all the wrong answers did i miss fighters and because wow i am just really bad right now oh my god i got dwight yeah uh let me know what you think about this farm and explanations this isn't in my final ranking there's way more penalties because i just i don't know i ate too many wrong answer attempts but yeah let me know what you think uh hit the like button and subscribe and join me on discord i hope y'all have a good day have a good night solve more problems if you like or you know too many acs and yeah it's a good mental health i'll see you later bye
Maximize Number of Nice Divisors
stone-game-vii
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is **nice** if it is divisible by every prime factor of `n`. For example, if `n = 12`, then its prime factors are `[2,2,3]`, then `6` and `12` are nice divisors, while `3` and `4` are not. Return _the number of nice divisors of_ `n`. Since that number can be too large, return it **modulo** `109 + 7`. Note that a prime number is a natural number greater than `1` that is not a product of two smaller natural numbers. The prime factors of a number `n` is a list of prime numbers such that their product equals `n`. **Example 1:** **Input:** primeFactors = 5 **Output:** 6 **Explanation:** 200 is a valid value of n. It has 5 prime factors: \[2,2,2,5,5\], and it has 6 nice divisors: \[10,20,40,50,100,200\]. There is not other value of n that has at most 5 prime factors and more nice divisors. **Example 2:** **Input:** primeFactors = 8 **Output:** 18 **Constraints:** * `1 <= primeFactors <= 109`
The constraints are small enough for an N^2 solution. Try using dynamic programming.
Array,Math,Dynamic Programming,Game Theory
Medium
909,1240,1522,1617,1685,1788,1896,2002,2156
1,658
Which Hybrid Today's Problems Minimum Operations to Reduce First Year Considering The Right Vyati St Anselms 512 Must Subscribe Now To The Numbers - To The Numbers - To The Numbers - Gabbar Samay Students - 110 Questions Of Make Sure Let's See What This Gabbar Samay Students - 110 Questions Of Make Sure Let's See What This Gabbar Samay Students - 110 Questions Of Make Sure Let's See What This Logic Of Inner Wear Limit Subscribe Now To The Numbers Are Hey O Mera Favorite Song Degi Sister Sambhal Four Submersible Total - Total This is equal to two plus five elements Total Subscribe Hai To Hai Next Roots In Arrange December That Way Toot Total Come - And Find The That Way Toot Total Come - And Find The That Way Toot Total Come - And Find The Longest Subscribe To Main Itni Senior Research Have yes easily tower goals to find the longest sub bhare avaghat bhare na pustham total six feet under 142 coal and solution hai that duke 390 consider dec-11 shift that duke 390 consider dec-11 shift that duke 390 consider dec-11 shift remove 14213 dirtiest operations on dec 14 2012 now sleep number operation songs free Need to find minimum number of operations in solving maths subject maximum do me rs 0 sequel total sub - k maximum do me rs 0 sequel total sub - k Knowledge in gr and he has taken example point on to find assam bhrigu submersible target and complete other text pin code off so what are going to where going to check sifixime logic to find the length c220 2010 2011 2012 protected team 1063 - research team white protected team 1063 - research team white protected team 1063 - research team white sportive 100 hear considered equal to forget to subscribe to that assam from its previous induces that space example hair tips 707 what is means affecting were that further placement in liquid plus forces acid subscribe to that hair dresser photog and hair dresser 170 soft phone From its benefit from 7 office - 07 which means the distance from office - 07 which means the distance from office - 07 which means the distance from filled in between truth on 27 - 3 support and plus to class for this 27 - 3 support and plus to class for this 27 - 3 support and plus to class for this site again from another day that what cutting is pleasant point to that point to me on Monday August and not journey Which central beauties have consumed indices Bihar Bengaluru sum 123 hands free - Android subject 4043 hands free - Android subject 4043 hands free - Android subject 4043 subscribe 159 want two minus one differences on Uttar Pradesh up subtle coast seventh class seventh 400 check a specific to front this inside differences can again just For oo aur sunao 3 - 09 - 6a aur sunao 3 - 09 - 6a aur sunao 3 - 09 - 6a 251 plated new sab bhare tak test theek hai beta WhatsApp to 7 minutes check manly from index one subscribe to are yes thank you calculate dictionary 520 and shyam pandey new sab kuch limit for and subscribe button subscribe to It happened from this Khusro quantity station, internal in this loot, seeing Salman proved that till 228 Sarpanch of Portion 7 - Ronit Roy Dictionary Sarpanch of Portion 7 - Ronit Roy Dictionary Sarpanch of Portion 7 - Ronit Roy Dictionary Video Subscribe Length is that Subhash has to share it and welcome 209 It is inappropriate to do was the latest wallpaper going to result clip sirvi su bluetooth requested specific person Ronit [ Ronit [ Ronit hai tu ab se ki sab kuch normal hai the states minor dheer wa 12345 ko subscribe how to do 22 - - 1000 positions - subscribe aa 22 - - 1000 positions - subscribe aa 22 - - 1000 positions - subscribe aa for now all the Number Zara Tractor Sauveer 1234 No Recent Episode 368 Subscribe To Is Vrat Ko De Solution Loot Computer Total Ka Hai Kar Do Hua Hai Jhaal On Karo Aur Suna Aur Samay Khel Ke Latest Current Affair Going To Find Work At Hotel - 2 Going To Find Work At Hotel - 2 Going To Find Work At Hotel - 2 Hua Hai That Computing To Brothers Lions Month in English Ki Noida Relax Now Ajay Ko Hua Hai Temple Run Khelo Cash Now Navsari Hai Previous Song Phir Calculate Par Song Tatti Trainee Every Time She Enters Rupse The Pratikshaan Hai And Anshu 113 You Are The Contents Of Hua Tha Ke Samne Na Aa A Target Tak Hai Net Video Song Hafte Mein Result A Lootere Car Music System This Independence Day Loot Is Ghat E Want To Know Kar Do Loot Ajay Ko And Sunao Jhaal Stripping Anil Kapoor Website Gas Hua Song Mister Small Condition President Sea Road and Extension - Subscribe to Sea Road and Extension - Subscribe to Sea Road and Extension - Subscribe to Shopping in Recent Speech 30.25 This is Shopping in Recent Speech 30.25 This is Shopping in Recent Speech 30.25 This is how - Not Trust People Jhal Path combined
Minimum Operations to Reduce X to Zero
minimum-swaps-to-arrange-a-binary-grid
You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations. Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`. **Example 1:** **Input:** nums = \[1,1,4,2,3\], x = 5 **Output:** 2 **Explanation:** The optimal solution is to remove the last two elements to reduce x to zero. **Example 2:** **Input:** nums = \[5,6,7,8,9\], x = 4 **Output:** -1 **Example 3:** **Input:** nums = \[3,2,20,1,1,3\], x = 10 **Output:** 5 **Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104` * `1 <= x <= 109`
For each row of the grid calculate the most right 1 in the grid in the array maxRight. To check if there exist answer, sort maxRight and check if maxRight[i] ≤ i for all possible i's. If there exist an answer, simulate the swaps.
Array,Greedy,Matrix
Medium
null
368
Hello Guys Welcome Back To Back Door And This Video Will See The Largest Divisible Most Problem Wishes From List To Date 18th June Challenge So Let's Follow Problem Statement Problem Years And Give Winners Of Distinct Possibilities For The Largest Subscribe My Of Elements In This Subscribe Mode on more solution fog subscribe center problem no latest do the giver 467 on Thursday and with oo hai so in this case your feet ek sadhe sab always latest take off but istri most it because the largest williams second notification latest 110 012 sleep * notification latest 110 012 sleep * notification latest 110 012 sleep * divisible by Sudhir Vve Nov 14 2012 Subsidy Avoid The Center And Subscribe My Channel Must Subscribe Now To Receive New That Within Border Is Not Important So You Can Transform 2512 Less And Policies And This To Deposit 126 And Center Problem Life Even Today What Is The subscribe will start from every element which is the largest subscribe now to options with only in the subscribe this Video subscribe Video to play list between options and will make all possible developed calls on there will be to take off and possible pass and ensure optimal is This check that is checking and give element can be included in this now half hour mode on two and off one burst fuse brute force in this will also be mode off and show your time complexity will be order of uninterrupted power and water from device this Inclusion Award Winners Will Be More Raw To Three Four And So Even Easier To Make Decorative Approach Will Take Explanation Time Complexity The For This Is Not Feasible Approach To Solve This Problem Variant Of Increasing Subscribe Solitaire Zoom This Increasing Order Midding Midning Change And Subscribe Do divisible by numbers on few days West Indies in subsequent will come out with 126 ok indicate they want to 610 will be your subjects where is element Balbir 126 no problem will again be having subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page Alarm of Birth 208 Otherwise Straight Should Be Equal To Zero No One Will This Later This Mode 2009 2013 Otherwise Beat Only Desire To Be Divided Into This Element In Short A Flu Say This point six pieces a lips element so let's check BTC-2004 middling in the sense subscribe free mode of birth place 200 gram sambse hai but they need to manipulate the condition of the sub always 2nd position is not included in the same subject ko dabocha dividing This will be much more clear when I explain with example as per the question they request to short tor records they have been sorted should not require 200 test wickets in this can see your feet from this tournament 0.2 60 feet from this tournament 0.2 60 feet from this tournament 0.2 60 and mode Switch doing this you will ply between truth can be present in the same condition after applying a quote that so you can only apply mode also 2015 virva is divisible and 98100 only one who are you doing so let's unite in these directions from morbi to write in the Middle of the limits of water will have to the number of the mission and mother but you will only one mode of operation in Delhi and saw this time to boys 210 Main Hanskar is obscene very-very lal chandan is obscene very-very lal chandan is obscene very-very lal chandan and long and you can take hamla reservation Compare So I Thing This is Better Life Gives and Another Day Used in This Little But It's Not Solved This Problem in subscribe The Video then subscribe to the Page if you liked The Video then subscribe to Liye Bill Computer Literate For Each And Every Element From Left To Listen Or Current Element Services Only One Element Yudh Left One Can Divide To And Also For The Length Of This Most Including One Is Equal To 2 And Defeat Can Divide To When They Can Actually Increase The Subject Science By One Swift One plus one is better than this one will increase the size of this to you in this case one plus one is better than one-dayer between two cigarettes improved this one-dayer between two cigarettes improved this one-dayer between two cigarettes improved this one and to in and subject the longest increasing subject according to and giving constraint will be Equal two of size two do not want to connect with sister in law will start from the first divide share dividend with oo is this one plus one who does one plus one will be twitter message vansh will update nov12 next point which is this two 9 10 Two Can Not Divide Free Software Not Possible To Be Converted To Know All This Element Search 120 Move To The 6 Will Start From This One So One Can Divide 60000000 Increase The Giver 2.22 Channel Ko subscribe to the The Giver 2.22 Channel Ko subscribe to the The Giver 2.22 Channel Ko subscribe to the Page if you liked The Video then subscribe to the Page West Indies And Inter Duetable Which Same To The Longest River In Subsequent So In This Case Will Keep Updating Max Value What Is The Maximum Value For Long-Distance Relationship Sequence In This Is It Long-Distance Relationship Sequence In This Is It Long-Distance Relationship Sequence In This Is It Is Equal To Three Love You Want To Practice Max Value Because Will Help You Find Out The In Adhadhund The Longest Subscribe Like and Subscribe This is Not Computing with All the Best Meaning This is the Subscribe Created from This Value 223 But Not Computing with All the Element Subscribe 159 This and When Counter So That The House Were Just Checking With Three Candidates Should Not Were Not Setting Where One Can Also Be Divided And Would Not Do This Because While Including This Would Make Them Check With Its Previous Element And Fair Award Winner Previous Element In This Element With This Element This Elementary Level Divisible By Its Previous Element And Divide Next Element This Is The Next Element Will Avoid Simple Mathematics In Relationship Element ABC Latest Noida Land Acquisition Element Is Divide Development Will See Mode Of Birth 2018 Airplane Mode They Will Be Equal To Zero Swadeshi Nothing But A Relationship Is Not You Might Get Confused Years Who Is Explained That No One In Your Language Increasing Sequence They Want To Find The Exact Subscribe Suvichar This Is Not Find A Way Are One Two Three Four Table Spoon 123 Likes And Subscribe Now To Subscribe My Channel Subscribe Our Channel Like This Is The Question Clearly Mentioned It May Be Possible subscribe and subscribe the Page Clement Sex Novel Decrement The Value Of This Max 2 And Will Stop This Previous Element Devils To The Servi 699 Will Move To The Previous Song This Is To 9 IF You see the way to subscribe this Video subscribe Video then subscribe to the Page if you liked The Video then subscribe to the Big Apne One Okay so this is equal to and max value no will see its element as per previous Element 300 divided over this one is this true wealth will push one and subject and all elements 910 to rs 600 in case you can clearly see basically the first subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Complexity and Dynamic Programming And Over Again First Your Finding 10 Subject Which Saw And Because I Was Doing A Single Traversal Member Total Time Complexity This Fans Ko Arnav Latest Look At The Code Swift Code Where Giver And Us Loud Twist Number One After Shopping Viewers Mining Longest Increasing Subscribe Number Two And After Doing All Subscribe What They Are Doing On Thursday A Person Data Is That Is The Current Element subscribe The Video then subscribe to The Amazing And They Will Be Able To Understand When The Solution approach in different languages ​​subscribe in different languages ​​subscribe in different languages ​​subscribe hours benefit from it like share and video subscribe our channel involved in this program in videos 0
Largest Divisible Subset
largest-divisible-subset
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: * `answer[i] % answer[j] == 0`, or * `answer[j] % answer[i] == 0` If there are multiple solutions, return any of them. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,2\] **Explanation:** \[1,3\] is also accepted. **Example 2:** **Input:** nums = \[1,2,4,8\] **Output:** \[1,2,4,8\] **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 2 * 109` * All the integers in `nums` are **unique**.
null
Array,Math,Dynamic Programming,Sorting
Medium
null
906
Hello everyone welcome to our channel question and you want to talk about one of the heart problems soft code no problem you support super first entrance end 1.06 ok so support super first entrance end 1.06 ok so support super first entrance end 1.06 ok so iss rule se reduce problem shubh related sampan roaming type ok so let's unite for street problem and together Will definitely idea solve this problem in the best solution and friends mukesh so let's move this positive integer uninstall super follow rom don't take tension is the number is it white room other this all subscribe ok kha condition set up vriksha repeat oneself in day test one like Share Number And Determine The Number Super Talent From Cities In The Inclusive Range Electrolyte OK Software To Basically Account The Total Amrit Superpower In This Can Reach OK Review By You Sam And Subscribe For Example Sun Need To Worry About So Let's Talk About Not Contributed Actually See The Left Front Android Mountain Very Up To That Is The Length Of The Artist In Various Tools Pet Means Earth Can Have Liked And Party's Value Addition Medical Value Distance Left And Right The Present In Teachers Indore Range One 210 Positive Incident First Prize Software Is Not Wish To Aware of this type of question is stressed under it Delhi World 1 Inch Its Speed Acidity COD Solve This Problem Like If Two Time Limit Exceeded The Gruesome Act Bigg Boss Modifying Something Okay Then Adjust Or Six Planning What Is The Point Of Mistake Also That Main Course To * In This Question OK So Let's Try To Understand This Problem * In This Question OK So Let's Try To Understand This Problem * In This Question OK So Let's Try To Understand This Problem In Point The Best Solution Of This Problem In The Best Possible Way Let's Move Further On The Latest Top Of The Help Of Strathearn Example Life In Giving Android In Various Stuart Postal Code 820 Roots Approach Will Not Be Able To Quit His Approach Will Not Work Will Have Two Of Three And Subscribe The Channel Please Subscribe And Subscirbe Not He Did Not Even Length And Width I First Rome Relation Between Equals Two Subscribe First Ok Maximum The Malik Ko Buildings Palan Romantic A Building Sampann Low Medium Just Doing The Same Time To Is Like Subscribe Now To Receive New Updates Tree Not To Withdraw From 01-02-2014 Paas Ki Hai Ok 01-02-2014 Paas Ki Hai Ok 01-02-2014 Paas Ki Hai Ok So And Strive To Build A Sainik Lower C Maximum Benefit And Boys Will Also Give Palan Room And Also People And Destroy To Build And Ok How Can They Reduce And Hidden Under The Con Is On Call Center Time Limit And Under The Hydration 15.12 Field Ok Latest Tattoo Photos For The 15.12 Field Ok Latest Tattoo Photos For The 15.12 Field Ok Latest Tattoo Photos For The Latest From This Dynasty Before In Rome Consisting of a point to ponder over evil and acted s plus of address correct random screen latest edition more subscribe only belongs to side 1st id porn 68 mode 10.4 hydration if possible then 68 mode 10.4 hydration if possible then 68 mode 10.4 hydration if possible then straight point is equal to 9 advertisement distic coordinator that default Toys School Distic In A Sworn In S You Can Very Apt Like F-18 Sworn In S You Can Very Apt Like F-18 Sworn In S You Can Very Apt Like F-18 Vikram Who Times Know A Plus Revert Subscribe Expert That Ali Khan So Proven Shadowlands And Distances Itself From Characters Paint Wishes For 9 And Destroy To Build A To The Worst Thing Tattoo Difference One More Night Come Hair And Can Go Up To Like Practice Make Some Places Left Can't Job Doctor Strange Okay So Tips Media Something To Check Investigate Android Condition Was Not Based Splendor Pro Follow His Actual Key String Consisting Of Vegetable Hotspot Sight Jack Nikunj Settings Where Hotspot of District OK So Let's Get Suvidha And Rather Than Is Waiting For Insta Per Tempo 93 Strobe Light Off Sports Mode Interiors And This Will Have Committed To Avoid Jad To Build Beam Consisting Of Price Follow Up This Point Chhappay Verse Spotless Maximum Articles Key principal and this interesting to maximum link to no witch hunter distance trends and if any special android easily square this and to point porn point to your Rome give back gear pig rearing draw and add text to be included in foreign soil in the next absolutely nickel To and is next many writers help one message to ethical like and share key points from president starting from extra to start from this and point and widespread and wish to follow and service and find x n x to printer not included under the given time limit Suffering 21018 Maximum Icon Decided To Vote And Support That Time Stands For Volunteers Turned From One Hundred Words Related To Every I Don't Points And Which Were 15.91 Is This Is Black 15.91 Is This Is Black 15.91 Is This Is Black Questions And Squares And Fixtures Follow Up On Rome Bite Object Rome He Guys Give In Access Line and picture give absolutely maintenance ok so latest to implementation health coding for it's ok so your seal testis of fast 100 second patience function in this chakra is mighty before trump and not talk and akshay different balance long spree continues it's ok you zinc style Slice row and electronic trading in the form of fertile land that can easily see live news stone function it is not aware of this unknown is previous converting strings * enter particular data is strings * enter particular data is strings * enter particular data is active user login more religious can go up to think positive a waste oil aspect 10.21 think positive a waste oil aspect 10.21 think positive a waste oil aspect 10.21 210 Power Foods And Reduce The Come Electricity Bill Is That Store Tractor 35 Fix Total Posts Product Range Of Pilot Rooms Of Clans Dynasty Is Decade Just Tweet And Previous Storing String Events And Just Avoid Further Told I Can Easily See All Ditties In President Mike Fennell Please Like This Is One of the Greatest Splendor Plus Time When School to 9 End Subscribe Quality Award Uniform Distic* Maze Quality Award Uniform Distic* Maze Quality Award Uniform Distic* Maze Store Twitter Up to 110 Stores Previous Install The Con Is On To My Channel Subscribe Button More subscribe and subscribe the Channel subscribe kare subscribe and subscribe the Channel Please subscribe and subscribe check date number isko 21 up first introvert and under give in the name of improvement my answer is nuskhe ko blacklisted in this is like a special staff withdrawal and misfortune After Maternal End Tak Hum Ise Palat Room Din Thi Next9 Otherwise Distic Witch Ke Play To Finally Data On The Answer Will Give You All The Test Cases For Most Frequent Ult Milna Jo Comment Section Of The Video Bana Mila Suicide Due Share This Video At Do Subscribe My YouTube Channel Latest Updates Thank You For Watching This Video
Super Palindromes
walking-robot-simulation
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. **Example 1:** **Input:** left = "4 ", right = "1000 " **Output:** 4 **Explanation**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. **Example 2:** **Input:** left = "1 ", right = "2 " **Output:** 1 **Constraints:** * `1 <= left.length, right.length <= 18` * `left` and `right` consist of only digits. * `left` and `right` cannot have leading zeros. * `left` and `right` represent integers in the range `[1, 1018 - 1]`. * `left` is less than or equal to `right`.
null
Array,Simulation
Medium
2178
787
hello everyone today's question cheapest flights within K stops so there are in cities connected by implied each flight starts from CTU and arrives at B with a price W so now given all the cities and flights together with starting city s RC and destination DST so your task is to find the cheapest price from is her source that is SRC to destination DST with up to K stops so if there is no such route output minus one okay so now I will move to pen and paper and understand this problem statement what we have to do basically we have to find the cheapest price from source to destination and taking up to K stop okay and if there is no route between our source to destination then we will simply written minus one so now our source is zero and this nation is our three now we will calculate our source to destination minimum cost okay we'll calculate source to destination minimum cost so first we will take a dictionary to store we check from our source point okay so our source point is zero so from zero it can go you can go one with the cost hundred bucks from zero to 1 so we'll take zero as a key inside this 0t we will take a nested key that is 1 and this cost is suppose this is a dictionary zero and then one that is cost hundred and from zero to there's another path from zero to we directly go three go to see three so this is cost three cost four hundred bucks so from zero we can directly go to CT one and say T 3 CT one will cost hundred works and CT 3 will cost 400 bucks ok and now we will move to next point so that is point 1 so from point 1 you can easily go from point 1 to we go only one city that is CT - so this one - we can city that is CT - so this one - we can city that is CT - so this one - we can go to cost hundred bucks and same point - - we can go three and it will cost one - - we can go three and it will cost one - - we can go three and it will cost one 150 bucks okay so that's our dictionary so we will store this information inside our dictionary now what I will do now I will take a hip QQ and inside the CPU of the store the number of stop to reach this position and cost and the current destination current cost current destination and number of stop ok so I will take IQ and first at the store suppose if I go from 0 to 0 from 0 will cost zero cause we're already in this position so first is cost and next is our current destination is zero and initially we store our number up stop K is zero and here we would take k plus one and when we will we'll store it again and then we will reduce this one k plus one first understood and then pop this will take a while loop and pop this element one by one and then we will check we are in our current destination is our final destination or not so our current destination is our final destination then we will return this value suppose if we have zero two zero and now we will move to this point so if we go to zero to 1 then our heap Lu you know L will be our current destination is 1 and cause this hundred cost is hundred how we calculate this cost which is check our current cost plus zero to one cost will pick this cost from here and add it in our hip and our destination point is this one that is our number of stop is K minus one so k is now 1 minus that is zero so without taking any stop we can directly reach zero so but here we have to visit we have to go our destination without taking any stop cause our K is zero so here if we go to taking to stop then we have to pay 350 bucks but if we directly go to city three then we have to pay 400 bucks but here we cannot take any stop so our answer will be 400 bucks okay so now I mention but in our implementation part first input hip queue now import from collections input default Dix will represent our crop using default dictionary so I will take a default dictionary type Dix and now I will Travis the flights value start in a flight hold the three will start end and cost so I will take start as a key the source point and end is another key under start and value is cost now I will take a hip cue to store current cost and current destination current cost is zero and current destination is SRC and number of stock is k plus one now I will just take a visited dictionary to check our current destination is previously visited or not so now I will take while loop and check our cube is H cube is null or not so now pop this value current cost current destination and k4 mower hip Q with Q dot it's Q and now I store this current destination inside our visited dictionary and now current destination is equal to our final destination then simple return the current cost if current destination is not equal structural destination then we will take our K is greater equal to 0 then I will check our next stop that we can go for more current destination so next or next destination is Jay I will check our next destination is already present in our visited this is dick scenario or not so J is our destination so now I just check K minus 1 get the wrinkles to visited cell so now just continue otherwise our J is our next destination and now I put it you know HQ so our cost is current cost plus our source to a current destination cost that is current cost plus scrap correct destination current destination key and next destination that is J and now our current we now we push as our current destination and stop minus 1 so now I just returned - if there is no route just returned - if there is no route just returned - if there is no route between source to destination so now we check our code is working or not it's running successfully and submit it if you have any doubts or suggestion leave a comment below if you like this video please give me a thumbs up and thank you for watching this video please consider subscribe if you are new to the channel and don't forget to hit the bell icon
Cheapest Flights Within K Stops
sliding-puzzle
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _to_ `dst` _with at most_ `k` _stops._ If there is no such route, return `-1`. **Example 1:** **Input:** n = 4, flights = \[\[0,1,100\],\[1,2,100\],\[2,0,100\],\[1,3,600\],\[2,3,200\]\], src = 0, dst = 3, k = 1 **Output:** 700 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700. Note that the path through cities \[0,1,2,3\] is cheaper but is invalid because it uses 2 stops. **Example 2:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 1 **Output:** 200 **Explanation:** The graph is shown above. The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200. **Example 3:** **Input:** n = 3, flights = \[\[0,1,100\],\[1,2,100\],\[0,2,500\]\], src = 0, dst = 2, k = 0 **Output:** 500 **Explanation:** The graph is shown above. The optimal path with no stops from city 0 to 2 is marked in red and has cost 500. **Constraints:** * `1 <= n <= 100` * `0 <= flights.length <= (n * (n - 1) / 2)` * `flights[i].length == 3` * `0 <= fromi, toi < n` * `fromi != toi` * `1 <= pricei <= 104` * There will not be any multiple flights between two cities. * `0 <= src, dst, k < n` * `src != dst`
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.
Array,Breadth-First Search,Matrix
Hard
null
139
in this video we're going to take a look at a legal problem called word break so given a non-empty string s and a so given a non-empty string s and a so given a non-empty string s and a dictionary um containing a list of non-empty words um containing a list of non-empty words um containing a list of non-empty words determine if string s can be segmented into a space separate sequence of one or more dictionary words so in this case the same word in a dictionary might reuse multiple times in the segmentation you might assume that dictionary uh does not contain duplicate words so here you can see we have a string right this case this lead code the dictionary you can see we have elite and code and then here you can see it's true because we can basically split a because we can segment lead code to lead code which all contains in the dictionary right in this case lead contains in dictionary code is also contained in the dictionary if we have e like this and we have a space here and then we have t c o d that's not going to work because this does not contain a dictionary and this does not contain the dictionary right we want to segment the string so that all the um all the words in the string um contains in this uh in the word uh in the dictionary in this case right so here you can see we have another string and then we have a word dictionary we have apple and pin in this case we will return true because we can be able to reuse apple right we in this case here you can see we can be able to reuse multiple times in some segmentation so here you can see we can have apple pin apple so in this case we can split apple pen apple in this case right so in this case we're going to return true and here you can see we have another string in this case cats and a dog or whatever but basically here you can see we have a dictionary which has cats dog sand and cat in this case it won't work because send in this case um sorry yeah n in this case um contains that in the dictionary cast also contain dictionary but og does not contain a dictionary so we're just going to return false okay so how can we solve this problem so to solve this problem the naive solution or the brute force approach will be to check each and every single element in the string and have a pointer and for each pointer for the current pointer that the um that is pointing to we're going to have a left substring in the right substring and then for the left substring we're going to check to see if this left sub string is contained inside the dictionary and for the right sub string we're going to see if it is a valid uh word break right so in this case we're starting at index one uh we're basically splitting you can see we're splitting a um we have a left sub drink left substring which is l and the right sub string which is e t c o d e and then we want to see if it's a valid um valid word break on the right substring in this case the right side and the left side both returns false and you can see there's an or operator the reason why is that if one of those statements true we can just return true for this entire condition for this entire method so in this case we have we keep iterating we now at the index two in this case we split we see elite in this case lee and e t c o d e right we see if those are if those two conditions are true in this case we don't we continue until we have this point where we have lead right and code and i think it's in 0 1 2 3 4 in this case index 4 right so what we're going to do then is we're going to now we know this condition is true right we know elite is inside the dictionary and we're passing the code which is the right sub string then we're going to do is we're going to see if code we do the same procedure we're starting at the um index one right we split we have a left substring which is c we have a right substring which is ode and what we're going to do is we're going to continue to do this until we get to here right in this case because those statements are false those conditions are false what we're going to do is we're going to pass in code and now the right substring is empty if right substring is empty where if any string we pass into wb is empty we can just return true because we want to re because we want to see if the left substring is actually contained in the dictionary right we want to see if the left sub string is can d to contain the dictionary that's why we have we want to make sure that this condition is true if this is true and this is true then this is true right this whole method will return true so you will notice that if we were to really do this the time complexity will be big o of 2 to the power of n which means is an exponential so if we because in this case you can see that this right here computed twice um not this one sorry my bad um wb ode is computed twice here if and you can see de also computed twice e also computed twice right not only those for each of those method that we call it recursively we will have repeated computation so what can do is that is we can use a um a hash map or a table to memoize the data the um the computer solution right so in that way what we can do is we can save the computed result onto this hash map and then we can retrieve the data in a in um in constant time right so in this case what's gonna happen is if we were to really implement them uh dynamic programming using sorry this problem using a memoization what we're going to do is we're going to bring the time complexity down to big o of n to the power 3. the reason why it's imp to the power of 3 instead of n square is because of the um the substring method because for java this dot substring method it will give us a linear time complex so in that case the time complexity will be n to the power of three so let's try to do this problem in code so our first step will be to use a hash set uh convert this word dictionary to a hash set because this will give us a easier way to access elements to see if it exists in the list right so we're going to use a global variable which is a type string we're going to use we're going to call it dictionary we're going to do is we're going to assign dictionary is equal to a new hash set we're going to pass in word dictionary and then we also have a string what we're going to do is we're going to use a hash map to memoize which the key is string and the value in this case is going to boolean okay basically we're going to do is we're going to cache the result right so in this case hash map and then we're going to do is we're going to return we're going to use a helper method which basically picks a string and we're going to recursively um recursively splitting the string right just like i would mention here we're going to split the string which we have a left string at the left substring we're going to see if it's in the dictionary and the right substring we're going to see if it's a valid word break so we're going to do this recursively so we're going to have a private boolean which returns boolean and we're going to call a helper and takes a string okay first of all we want to make sure that because when we're splitting right there could be a situation where the string is empty just like this one then we're going to do is we want to make sure that the string is if it's null we're going to return true okay because we want to make sure that we are focusing on the right sub the left substring in this case we're focusing on the left substring to see if it's actually inside the dictionary if it is then we want to make sure this is also true right otherwise if this is true and this is not true that won't that will not make sense so in this case we want to make sure this is true then we want to make sure that we also don't have the string computed in the like we basically want to make sure that we did compute this string in the cache in this case it contains this string we want to make sure that if cache.contains this key we sure that if cache.contains this key we sure that if cache.contains this key we want to return this element right inside the cache dot git s okay because we don't want to compute this thing another time so what we're going to do then is we're going to iterate so we're going to traverse starting from index um starting from the next one okay what we're going to do is we're going to traverse and is equal to s dot length while i is less than equal to n because we want to include the last element when we split in okay because when we say substring we want to pass in the star index the n index including the last element right so in this case we all we will also um iterate the last element as well so we're going to do is we're going to get the substring the left substring is basically equal to that's the substring okay we passed the substring starts and i right so in this case we the left is basically the left side of the current pointer and the right substring okay is equal to as the substring high at all the way to the end right in this case we're all the way to the last element in this in the string so in this case the current pointer all the way to the very right or the last element um including the last element in the string then we're going to do is we're going to see just like what we talked about here right we want to see if the left sub string is actually in the dictionary so in this case dictionary dot contains i'm going to see if this contains the left substring and we want to make sure that if helper contains the right substring if that's the case then we're going to do is we don't want to compute this again of course we're going to return true but we don't want to compute this again so we're going to do is we're going to use cache.put going to use cache.put going to use cache.put we're going to put right sorry we're going to put s as the current string right so this current string the current this current string we already computed so we don't want to compute this again so this s is going to be the key the value is going to be true because we already checked that the current string is true it is a valid word break okay so we can just return true and we will make sure that we save this result in the cache then what we're going to do is after we've done iterating we know that this is going to be false because there it didn't really satisfy this condition so we're going to do is we're going to say cache.put say cache.put say cache.put s is going to be false okay because we know that this is nothing really happens we're going to return false another thing we have to do is there could be a empty string in this case so what we're going to do is we're going to say if s the length is equal to 0 then we can also return true okay so now let's try to run the code and let's try to submit so now you know how to solve this problem and as you can see the substring method takes a linear time complexity so therefore our time complexity is not going to be big o of n and square instead we're having a big o of n to the power 3 for time complexity okay and um basically for space complexity is going to be big o of n where n is number of characters in the string right um yeah basically here you can see we have cash right so you can see every time when we save an element computer result we save the result onto the cache hash map right so therefore we have n elements in the cache so there you have it right so basically i know it takes it is a very hard problem um to digest but i believe that um the more you do dynamic programming problems the more you get good at them and as long as you know how you can do them like the core idea behind solve solving this word break problem you should be able to solve this problem easily there you have it and thank you for watching
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
289
hey everyone uh in this video i'm going to explain the solution for a lead code question called game of life which is by some big tech companies and also at the same time i'm going to go through the steps we should follow in the real code interview so let's get started so in the real coding interview the first step is always try to understand the question and uh if there is any there if there is any ambiguous part feel free to bring out the question and at the same time think about some ash cases that can potentially break the general solution in the next step so let's go through this question briefly so according to the wikipedia the game of life also known simply as life is a cellular automat automaton device by the british mass medicine whatever so the board is made up of an m by n grade of cells where cell where each cell has an initial state life which is represented by one and that represented by zero so each cell interacts with its eight neighbors and there are four connections so for lifestyle if there are fewer than two neighbors uh fewer than two life neighbors it will die if there are more than three left neighbor it will die if there are two or three left neighbors then it will continue to live for the dead cell uh when there are exactly three life neighbors then it will become a live cell so this is a uh example like a transition example so the question is the next date so the next date is created by applying the above rule simultaneously to every cell in the current state so we are going to try to figure out the next step and the next state for the grade given the current grade so this is an example so let's see some constraints so it says that the given uh board is not going to be empty so we don't need to worry about that kind of ash case and also there will not there won't be any illegal inputs because each of the cell is going to be either 0 or 1. so and there is some follow-up question so and there is some follow-up question so and there is some follow-up question asking is it possible to do it in place the answer is yes so this is exactly what our solution is about so the solution is a m by the runtime is om by n and there is no extra space used in this solution so the solution is in general uh we use two additional integers to represent a new states so uh integer two means in the next day in the next state it is going to turn from that to live and for integer three it means currently it is live but next state for it is that so um this so in when we find so after we find the solution then we do some coding work on top of the ideas about the solution so it is quite simple after we figure out how we do it in place by introducing extra state so in here we introduce an helper function which is uh to count how many left neighbors are there for given a corresponding cell so there are three parameters passed into it the board the row and the column so we are going to return how many life neighbors are there for the given the current state given the current row and the current column so within the major function um every time we just call the helper function to count the left neighbors and follow the rules to update the corresponding board to the new state if possible and after that we have a new board we need to turn the intermediate states which are 2 and 3 into 0 and 1 and translated after the translation the board is going to be the next state so that's essentially how we solve this problem so after you find the solution and you discuss with your interior about the solution you will do some coding work take care about the correctness readability and also uh don't be too slow in the coding part and after you're done with coding it's not a time to call it succeed you still need to do some uh testing uh to introduce some test cases twice to uh to inspect if there is any bug within the code so that's it for uh this uh question so if you have any questions about the puzzle or about the code feel free to leave some comments below if you like this video please help subscribe to this channel i'll see you next time thanks for watching
Game of Life
game-of-life
According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. " The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its [eight neighbors](https://en.wikipedia.org/wiki/Moore_neighborhood) (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): 1. Any live cell with fewer than two live neighbors dies as if caused by under-population. 2. Any live cell with two or three live neighbors lives on to the next generation. 3. Any live cell with more than three live neighbors dies, as if by over-population. 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return _the next state_. **Example 1:** **Input:** board = \[\[0,1,0\],\[0,0,1\],\[1,1,1\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[1,0,1\],\[0,1,1\],\[0,1,0\]\] **Example 2:** **Input:** board = \[\[1,1\],\[1,0\]\] **Output:** \[\[1,1\],\[1,1\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 25` * `board[i][j]` is `0` or `1`. **Follow up:** * Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. * In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
null
Array,Matrix,Simulation
Medium
73
236
Hello hello everyone welcome to our channel audition in this video will be discussing the lowest comment and sister for * I am very famous comment and sister for * I am very famous comment and sister for * I am very famous problem that is present and internet code where it's nx is 236 setting categorized medium problem dalit and right for this problem meanwhile Problem Famous Problem and Deception Interesting Problems Can See the Number Flights Where is Very Huge Amount and This Problem Which College Teachers The Concept of Military Adventures of But Can Write Down the Scene Subscribe Button Records in Café Subscribe to a Point Cut to Length West End Sister Mother To Give It's Okay subscribe The Channel Eyes And The Giver Notes In The Present In The Giver That Me To Find The Best Method Best Results Method Where We Can Do The Thing So The Definition Of Alsi Battery Saving Events &amp; Subscribe Details Water Events &amp; Subscribe Details Water Events &amp; Subscribe Details Water Retention How We Can Find A Solution For This Problem So Let's Do The Definition Of The Lowest Comments Subscribe Notes PM Nov 29 2013 By Both His Descendants Were Not Appear Different Topics Like It Is Pe That Notification our YouTube subscribe Channel and press the Video then subscribe to the Hai To Happy Is Adhed Review Me Times Discussed About Okay So Let's Look At The Constraints Number Of Units Industries Co * * * * * 10.51 To Write In Industries Co * * * * * 10.51 To Write In Industries Co * * * * * 10.51 To Write In Edition Solution Edition After And Solution Every Notice To Withdraw It's Executive Who Can See The Maximum Number Of Votes Standard To The Power 5325 Turn Off An Object Solutions Chapter Notes Values Like And Toys Is Going To Liquid Water Not Valid Notes Will You Must Bring To Front NFC Of Units .in PM Front NFC Of Units .in PM Front NFC Of Units .in PM Must Be Due To No Weather Or Not The Complexity Like Sid Difficulty Problem Increase Pairs Aby Samaddar Ki Sampoorna And Let's Celebrate And Soapy Thank You Will Exist In The Tree Shodhak Hain Yes A Helping Others Charity Organization Peace Not Able To Give And Not For Distic And Click On subscribe difficulty this problem subscribe so let's check the definition of subscribe the Channel please subscribe and subscribe the Channel subscribe so you can just for the definition of the different between both presidents loot ok sorry darshan point to definition we will consider the best definition of SCS Life and apart from the cone is not where is a p and q to the root node and white apart from the no data is the tree why not broken find the first common intersection of the notes present in the past few can see the first woman intersection is Coming Reduce Note Member LC Of The Two Not Let Me Take Another To Said Black Much More Clear To Understand And Definition Of Subscribe 99264 Okay What Is The Part Of From Today No Differences 65 Sui And What Is The Part Of The 232 The Five Have Entry Vacancy What is the first not where is like comment It is intercepting in 12th part That is the first not starting from this They release after days Apache 160 258 125 Lowest comment on this and sister of the two Note 6 Pro K Sauce How To Build Up The Record Solution To Find The Lowest Comment And Sister Of Do Not Speak When You Were Painted Notes Address Okay Yashodhara To Possible K Cystitis K So Let Me Just Take A Basic Sham Pal Yes Okay So We Are Talking Word Verification Pal Sapoch bed onenote p.m. This Is The Not Give Ok So onenote p.m. This Is The Not Give Ok So onenote p.m. This Is The Not Give Ok So Subscribe To This Channel Must Subscribe The Subscribe Skimming No David Doraemon PM Why Light To Keval Se Alsi That Belongs To Is The Chappi And Why Tota Darad Possible How Time Stock Investors Very First Day Test Ke Swa The Not Like this one can see the first international and national president of the lord will stop at another ki subscribe the case me ka haq so sapoch agar is rumor note speed andar siddha note ki vacancy celsius coming about water shortage cs5 loot celsius coming soon test live ka Hakeem Saud RCA So How To Figure Out How To Write An Application To Record Just Solution Improve To Write To Catchup The LCA Interest Test In Just One Record Se Twist Ok 100 Withdraw It's Ok Is Basically Pappu Safed Just Talking About This Close Its Clear 2009 Dec And no difference with us office let me down clearly don't know the spirit to ride on record saying step in the country were always just trying to fetch daru left the work on me myself writing down route left and points to * base route ok sir No the points to * base route ok sir No the points to * base route ok sir No the thing is like you can see and just kidding may top right now in tamil explain it acetic acid something has been written in the record seat function in see free mode start ok so let's have been stored in a valuable student's so let's something is King returned with equal roots love and something is king and twinkle fruits right ok 9 after writing 20 two steps with daily up-to-date with no one thing what with daily up-to-date with no one thing what with daily up-to-date with no one thing what is that one thing ok so in this current notice form note from this here equal to speed And this mic content note this inch width equal to do not disturb time current notice to you can easily set s e can we have that is my route not match with national scene compromise this current node ok so effect matches with appear key vacancy dot sm Going To Be Town Root Okay Dear Not Understanding Enmity Stuart Broad Pendant Music Play List With The Help Of Diagram Withdrawal Will Just Fee No Dinner Activist I Will Be Town Root Which Can Be A Shadow Over Arvind Fee No I Will Return Root In This Can Be And Such Incident Which Does Not This Is Not Regret And Again And Destructive Values ​​And Again And Destructive Values ​​And Again And Destructive Values ​​And Again And Deposit And Withdrawal See Now Not Withdrawal It's Not Considered This It's Something In Return From Left And Something In Return For Not Considered Thing But Also Let Me Do Something Take web note 5 day wear note 6 and they have something that note does not sit that note 4 ok not considered a sin and talking about this is the giver not and disappeared and you can see the alsi apn thing coming out with vishnu ok that is The note 5 ok happy because just how to this determine from here root of baroda se nazar matching with speech e not matching with you work with her boobs and so before writing this point to write down one thing in what is that one thing ok so let's Move to the best speech and I don't think so ifin e-mail yes not equal to null e-mail yes not equal to null e-mail yes not equal to null ki and are you should not equal to null ka hak re kyun is i lash not na lene and is nodal every town mic current route dushmane pilot my This Is My Lazy Dhak Hai Not Understanding Is No Need To Worry About Sports In This Is Like Profile Route Notice Under Certain Developed Step That Is My Route Maz Pay You Can See I Will Return In This Route With Its Node Raat Dushman Naagin More Steps Will Win Matches Will Give You Will Return Key Okay No One Comes With His Position But I Will Have Developed As Not And Will Have The Right To Airtel Dish Not Okay So Let's Not Nil Return On Equity Will Return Dushman Truth And Family Subscribe Must Subscribe 9 This Is Not Sufficient I Need To Include One More Condition And Digests Sexual Tourist Complete The System Of The Lines On This Code To Feel You Much Better Ok So Button Ko Incident This Statement Of Root Fruit Is Not Subscribe This Video Not Loot Channel It's Something Is The Definition Subscribe In A Reader And Will Do Not Disturb Me Less Will Do The Thing And You Cannot Be Tried To Celebrate Its Roots And There's Something On That Narmada Ashtak In Copy Down Photo Copy Dentist In Varied Them Just Root To Right End Avinash Seth Okay So Let's Build Up Something More Interesting Than What Is That Something Interesting Facts About My Root Mez Pe Mod Root Subscribe Must Try That Now Before Doing Something They Remind Me Possibilities Day Celebrate And 8 Reasons But This Is Not Null And is not valid means loot descendant of migrant mode of but on pc in mid term node in left difficult to pc in and construction odd node in r independent medium to p and q here and there can be anything ok tribes and reduced now electronics route this Is My Difficult Type-2 Egg Subscribe To My Difficult Type-2 Egg Subscribe To My Difficult Type-2 Egg Subscribe To I Your Show Writing This Is Patient And Want To Win A Tourist Include Everything Okay What Is The Thing You Can See What Will Happen In The Certain Record Acid This Point Distinguish Rich Person This Point Is Point To You can directly share the left hand side is returning nothing android 24900 hair pack to 9 subscribe this Video not withdrawal voice having no develop it's not only imteez patient i think this 209 hai submit dispute ki awardee submitted isko driver vacancy dasharan times and very much good runtime vitamin superintendent missions hakeem time when best and typing yes ok 151 do it means the comment section yadav video and don't forget to ask any five single Bilas for Doubts the Best Like this Video Status Video with subscribe our YouTube Channel Par Latest Updates Thank You for Watching this Video
Lowest Common Ancestor of a Binary Tree
lowest-common-ancestor-of-a-binary-tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the tree.
null
Tree,Depth-First Search,Binary Tree
Medium
235,1190,1354,1780,1790,1816,2217
983
hi everyone it's Cen today we have a problem when we are planning a travel one year in advance and for example let's take this scenario we are traveling let's say that on the 1st 4th 6 7 8 and the 20th day of the year and we need to calculate the how the minimum number of dollars so minimum amount that we can pay for our travel so minimum number and for one day pass we are paying cost zero we are also given the costs so for a 7 day we are paying for example in this case $7 are paying for example in this case $7 are paying for example in this case $7 and for the 30-day we are paying $15 and for the 30-day we are paying $15 and for the 30-day we are paying $15 and we need to calculate what's the minimum number of what's the minimum amount we can pay for our travel so for example let's take this case in this case we have for the first day we can pay $2 have for the first day we can pay $2 have for the first day we can pay $2 right for one day pass for the next four days we can pay $7 because it will cover days we can pay $7 because it will cover days we can pay $7 because it will cover all these days right it will cover fourth 6 7 and eight and for the last day we can pay $2 and 2 + 7 day we can pay $2 and 2 + 7 day we can pay $2 and 2 + 7 + 2 gives us $11 which we are returning + 2 gives us $11 which we are returning + 2 gives us $11 which we are returning so the way we are going to solve this problem we are going to use a dynamic programming bottomup approach let's take the example that we had earlier 4 6 7 8 and 20 so what's the idea behind dynamic programming bottom up approach the idea is that we are solving a sub problems of the problem that helps us to build up to our solution so for example in this case we are creating an array with the same size as of our array and we are also adding here zero I'm going to explain why in a second so we are so it's the same size of our as our array and um and also we have we are going to put here in our case two pointers I and the J right so let's say that we are just paying for the one day pass and we are for example for the first one day pass we are paying for the first day right we are paying $2 for the first day right we are paying $2 for the first day right we are paying $2 for the next day so we here we are adding that the total number of total amount that we are paying for our travel right so for the first day we are paying $2 for the first day we are paying $2 for the first day we are paying $2 for the next day we are paying also $2 right so next day we are paying also $2 right so next day we are paying also $2 right so 2 +2 is $4 so and for the next for the 2 +2 is $4 so and for the next for the 2 +2 is $4 so and for the next for the six again we are using so we have one day which is in our case $2 for the day which is in our case $2 for the day which is in our case $2 for the second for the seven days we are paying $7 and for Theif for the 30 $7 and for Theif for the 30 $7 and for Theif for the 30 days we can pay $15 days for the 30 days we can pay $15 days for the 30 days we can pay $15 right so now we are using only one day pass for now just we are paying for $4 pass for now just we are paying for $4 pass for now just we are paying for $4 and here we are paying for we are paying our also for one day pass so 4 + 2 is 6 here also for one day pass so 4 + 2 is 6 here also for one day pass so 4 + 2 is 6 here we are paying for the seventh day of the year we are paying all for one day we are buying one day pass so it's $8 and are buying one day pass so it's $8 and are buying one day pass so it's $8 and now we moved our I and the J pointer here so the idea is in our case that we are let's solve this sub problem right let's say that for only these four days can we do better than that can we pay for the for these days right for 176 uh 4 6 7 can we pay less than $7 yes we uh 4 6 7 can we pay less than $7 yes we uh 4 6 7 can we pay less than $7 yes we can the way we are going to do that the way we are our approaches we are going to move our JP pointer backwards as far as we can and uh let's say that as far as we can until it's for example first we are checking for the 15 then we are checking for the 30 days right so first we are going to check for the 7 day so we are moving our J pointer until the difference of the I and the J so basically this days I right minus days J so this difference is less than or equal to 7 so it's less than or equal to 7 so for example we can move our J until this point right until the beginning of the array right until we can move our J pointer here so it means that the this port portion right this portion of the array we can replace with the cost I with the 7 Days right we can replace that with the cost I cost one actually in our case we can replace with the cost one and now we are checking now we are comparing so at each step we are taking the minimum value of whatever the value is here DPI right whatever the value is here or we are taking either eight in our case it's eight right or we are taking that whatever our dpj wherever we moved because up to this point we have calculated our total sum right now we want to replace this part with the with our cost one so with the seven days so now we are taking we are doing exactly that one here so we are doing the PJ right the PJ so this part plus this part right this part plus this part Plus whatever the value of the cost I cost one right whatever the value of cost one it's our costs right so whatever the value is so for example in this case this value is zero let me put that in another color so this value is eight right this value is eight from here and this value is 0 + 7 eight from here and this value is 0 + 7 eight from here and this value is 0 + 7 right so yes we can do better than that we are replacing eight with this with the seven here so right we are setting seven here so that is the our approach so basically at each step we are we have two pointers right I and J at each step we are moving our J pointer as far as we can move for example in the first case we are doing that for the seven days so we are moving seven we are moving until this value is less than or equal this equation is less than or equals to 7 so we are moving our J and in the second case we are moving our J until this equation is less than or equal to 30 and we are replacing that part of the array right that part of the array whatever the cost is either cost one or cost two plus whatever the sum is up to that uh first thing to do let's take the size of our array let's call it n and because we are going to use that a lot so let's take the days length Okay and now let's create our array where we are going to store our total amount DP right which we are going to return at the end so what's the what's going to be the size of it we are going to take int and we are going to take that n + one right we are going to take that n + one right we are going to take that n + one right because we are also using the zero index so and also at the end we are going to return the P let's just return it right away we are going to return whatever the last element is whatever the value of last element is okay now we can go over our array and we can populate our DP uh array of integers so for that let's start we are going to start from the one right we're going to start I is equals to 1 I is less than or equal to n and uh I ++ ++ ++ so what we are going to do here first let's add just a direct cost for the for one pass right and then we are going to see that the can we improve that so that's what exactly we are going to do here we are adding DPI so we are adding so whatever the previous value is right whatever the previous value is we are adding our current cost so we are adding our cost for one day pass which is zero okay so now what we are going to do we are going to check that can we replace that with the seven or 15 so now let's check for first for the four so now let's check for first for um now let's check for first for seven days so for that we are going to do inj is equals to we are setting our J that is equals to one but not one but the uh not I but the IUS one right IUS one and now we are starting to move our J point as far as possible so to do that we are going to move that until it's equals or more than one right equals or more than one actually vice versa and also the another condition is that it should be less than the difference should be less than 7 days so then the i - one i - one minus days then the i - one i - one minus days then the i - one i - one minus days J minus one it should be less than S so we are moving as far as possible and we are decrementing our J so at the next step what we are going to do we are going to then take the minimum so now for the DPI for each step we are going to repeat the same so we are going to check that the okay what is the can we replace that portion of the array right so min minimum we are going to take the PI right the value that we have at this point for example in our case it was eight right or the PJ so we moved our J now we are taking J plus the cost that we have at one right so we are trying to replace it whatever is the minimum we if let's say this value right we moved our J so let's say that the Value at0 Plus 7even if that is less than that then we are going to set to our DPI we are going to set this value all right so now exactly the same we are going to do for 15 for 30 days right so exactly the same we are going to do for 30 days here and uh it's going to be cost of two yeah that's it let's run it okay we forgot to add the return statement here also it should be costs here's run it one more time yeah here we already did defined J okay it works as expected now let's calculate the time and space complexity what's the time complexity of this solution we are solving this problem in one pass right but we are moving our J point ERS at each step so but they are constant right we are moving seven at most we can move seven and the 15 so our we that we are not taking that into equation so our time complexity is of n how about the space complexity it's defined by the size of our DP array and in our case it's n let's just go over it one more time so idea is that we are using dynamic programming bottom up approach so at first what we do we are first calculating the direct cost here right we are calculating the direct cost meaning that for one day pass and then we are at each step we are checking that can we do better than that so we are moving our J pointer until it's either until it's uh less than until the difference is less than 7 days so which means that the for all days that is that we can include in the in those seven days and we are taking that okay the day so whatever the sum was the before that right before those seven days that and the plus the cost one which means that for seven days is it less than that the current amount that we have if it's less than we are updating that exactly the same we are doing for 15 days okay I hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
Minimum Cost For Tickets
validate-stack-sequences
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
Array,Stack,Simulation
Medium
null
451
what's up guys episode is here with another lead code question and today we're solving leak code 451 sort characters by frequency once again if you want to solve this problem please take the time to solve it and come back to this video once you've solved the problem awesome so for this problem we're given a string and we need to sort it in decreasing order based on the frequency of the characters and as you can see the constraints are as follows our string only consists of uppercase and lowercase English letters and digits so that means we're not going to get any characters that are not letters in digits so let's go ahead and get into our examples and our examples are pretty much self-explanatory for the first one we self-explanatory for the first one we self-explanatory for the first one we have our input tree and we return this as our output and that's very self-explanatory and similarly for self-explanatory and similarly for self-explanatory and similarly for example two we have this is our input and we return this as our output and you can see by our explanation we could either have our A's appear first or we could have our C's appear first and they're interchangeable because they pair with the same amount of frequency and example three is really when we actually get into some form of an edge case and the reason why is because we have two occurrences of a one uppercase and one lowercase and by the explanation you can see that this problem is case sensitive so we count these two letters differently so now let's actually talk about how we would solve this problem and solving this problem in code is very similar to how we would solve it when writing it down or how we would solve it as a human so let's get into that let's solve this problem using example three since it's our most comprehensive case so basically what we would do as a human is we would look at our string and see which characters appear within our string so we have uppercase a lowercase a and lowercase b and then we would count how many times each of those characters appear within our string so uppercase a pairs one time lowercase a also appears one time and lowercase b occurs two times now that we know the frequency of each character now let's sort them by their frequency in descending order so we know that b occurs first and then a lowercase and a uppercase occur second or third because they're interchangeable and then now when we want to construct our string we can just construct our string by going through our sorted list and then inputting each character the amount of times it occurs within our original string so for example B occurs two times so we would have B in our result string two times lowercase a occurs once so it comes in there one time and similarly uppercase a occurs once and this is our result stream and as explanation for example three shows lowercase a and uppercase a can be switched in the order of our result string because they are interchangeable and that's pretty much it for the idea behind the code now let's get into the code and the code for this kind of makes this a sort of easier medium problem so let's go ahead and get into the code so the first thing that we actually need is a dictionary and this dictionary is going to keep track of the frequency of each character that appears in our string and then we also need our result string which we are going to return and the first thing we're going to do is we're going to Loop through each character in our string and we're going to count its frequency within the string and we do that with the following line frequency let's see get r0 plus one and basically when basically what this piece of code right here does is that if our character isn't in our dictionary it's going to fill that value with 0 and then add one if it is in our dictionary then it's just going to return the value that we already had for frequency so this is our first pass over our string and then what we want to do now that we have the frequency of each character within our string we want to sort those frequencies in descending order and we can just do that with the built-in python function sorted built-in python function sorted built-in python function sorted and we want to sort our frequencies based on the values in our dictionary so we just use some Lambda calculus and then since we want it to be descending we want to set reverse to true okay so now this is our frequency dictionary sorted in descending order and it's now a list and now what we want to do is we want to go through that list and go ahead and create our result string so for card count and our descending list what we want to do is you want to set result equal to or this is pretty much just adding the car the character uh the amount of times it appears within our original string and then we just want to go ahead and return that result and this should be all the code for this problem and we can go ahead and submit that and see if this works so we see that this works and the percentages are pretty low but on other tries the percentages will be high for the memory and the runtimes that we beat so the actual run time for this problem is o n plus log n because we have two linear operations this is this first linear operation and this is our second linear operation and then our logarithmic operation is actually sorting our frequency dictionary and sorted takes log and time in Python so this is an oath n plus log n solution in terms of runtime so yeah that's all for this problem and please make sure to like And subscribe it helps a lot with the channel and I hope to see you again soon on my channel thank you
Sort Characters By Frequency
sort-characters-by-frequency
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. Return _the sorted string_. If there are multiple answers, return _any of them_. **Example 1:** **Input:** s = "tree " **Output:** "eert " **Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer. **Example 2:** **Input:** s = "cccaaa " **Output:** "aaaccc " **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers. Note that "cacaca " is incorrect, as the same characters must be together. **Example 3:** **Input:** s = "Aabb " **Output:** "bbAa " **Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect. Note that 'A' and 'a' are treated as two different characters. **Constraints:** * `1 <= s.length <= 5 * 105` * `s` consists of uppercase and lowercase English letters and digits.
null
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,387,1741
1,760
hello uh today i'm gonna solve the problem a minimum limit of volts in the back this problem is quite hard for me for the first time but once you got the way of thinking it will be pretty simple and arrogant so let's get started so first of all we are given noms array and also max operations integers and we need to divide uh each number into two parts by one operation for example if you have nine and we can divide it into one and eight or we can choose uh any number four and five like that sorry and one thing to note is like we cannot choose 0 i mean 0 and negative numbers we just need to choose positive numbers more than one bigger than zero right and we have two operations so we can divide it once more like one nine and let's say two four two three like this and after the operation we need to find the maximum number in the array in this case maximum number is seven right and in this case maximum number is four so we i we want we need to return uh the division way of minimizing uh the maximum number in the result array we don't need to operate all the time i mean if max operations for example if we have a lot of operations for let's say we have 100 operations he's allowed it but the best scenario is one right so in this case we don't need all of operations we just need 9 operations in this case sorry 8 maybe 8 operations so in this case once the answer is one let's think about our operation is to we if we have two operations so as example said the best scenario is three so the maximum number of disarray is three so we need to return three not seven not four the answer is three so the first i mean in my intuition i thought we just need to pick a most largest value i sold i will choose largest value so in this case oops in this case 8 is the largest right so we i want to minimize 8 into some smaller parts so x and y right so generally we want to minimize x and y i mean both x and y so i thought oh we just need to divide by two in this case so wonderful is a best approach and we will uh loop this operation so for i range operations we will uh first of all they already choose max value in array and divide max value by 2 right and we just iterate all the time and first of all we need to return max value in array but as you know this doesn't work let's think about simple example 9 in this case so in the previous approach we will divide it into 4 and five and we will choose five in this case right so we create two and three so we answer will be four but it's wrong right because the answer is three so i was stuck there oh what should i do so second thought is like we can think about the best case scenario best scenario and what scenario the last scenario is simple if max operations is zero we just need to return the maximum value right so it means the answer is between 1 and 9 in this case so it means if we have answer will be let's say max value is between one and max right so how can we know that for example in this case if you the best case scenario is one right but how can we know one is feasible in this case let's think about this array and some operation i mean after some operations we can get one right but at least how many operations do we need it's simple because in order to get one at least we need to deconstruct two in this case so in order to combat 2 into 1 we need 2 operations at least same as 4 we need four operations right so it means at least we need 6 14 16 operations in this case the minimum version should be uh oh i'm sorry that's my miss and we need minus one here minus one and sorry i don't want to write or so let's skip it but the total number should be 12 operations so how about 2 4 8 2 somehow we will have two and one like that i don't know so in this case we need to have two divided by two minus one plus four divided two minus one blah right so before three plus one four operations because in order to combat eight to two we will create two six and two four and two say at least we need three operations about four about eight so what happened if we have two three it means we don't need to set it one we wish we don't need to know what actually number is in the array so in this case we don't need to operate two so we just need to add to divide it by three plus four divided by three actually we don't need to subtract one in this case so we need to substract one if we don't have any mode two so it is three operations right okay let's think about it simple so we will create this operation to maximum value right so for each number we will create operations we need to calculate operations and we need to find the point when we cannot i mean when operation is lower i mean for example if max operation is 4 we need to return 2 in this case so if we cannot meet requirement we need to return this i mean this value so for each number we need let's think about if we set it as already will be n and maximum number i don't know maximum number but let's think let's call it as fm we need n squared mn right so one thing to note is operation is purely decreasing in this case i mean minimum required operations is purely decreasing it might be same but it's decreasing right so it means we can use binary search to reduce the calculation cost so if we use binary search it will be o and rogen emerald and rogan right so let's write the code now so first of all we need to create helper function to calculate minimum required operations and we will do binary search so let's say card hops we need to take noms array and also target value so response is 0 for each number if not more target we don't need to return now divide it by target else it means model is zero in this case uh we need to substract by one let me write a simple test so if nums is three two one like this and target is two in this case what will happen so three cannot be divided by two i mean completely divided by two so it means we need to return numbers divided by target so this is one minus one it means we don't need any operations zero so return number is one and this is correct okay it seems to work no sorry else not to return let's press and we will return rest so max will be maximum numbs so we will do by research in this case l is equal one and max and for why is draw as than now we need to calculate mid now plus uh minus 1 minus l divided by 2. so if middle so if serve dot corrupts noms and middle is bigger than max operations in this case this mid is too small for the answer so we need to search for new value else we will move r and red done hmm l not well we need to return r in this case maybe no it's very hard to consider edge cases every time in binary search program so anyway so if we have one two three four five six seven first of all we have what middle should be here are here and middle should be zero one two three four five six so it means 0 plus 3 is here so 4 is valid foreign and next middle is here because zero press uh one is here right so if 2 is not valid let's say 2 is not valid we will have l is here now m will be here right so l is not stereopartic so we will have next will be l and r here so answers should be current i mean they're in the last statement l equals to r so we can return each one i mean e either one so i believe it works well so in the last statement if it's not valid we will yeah sorry if it's valid we will move r to here so yeah i think it works well let's avoid it to be honest this is my first submit and i'm very glad to pass it okay so this problem is i mean the implementation is pretty simple but uh the way of thinking is pretty complicated and also in order to implement binary search correctly we need a little bit talk we need to have template so you can refer to this great post as a buyer such template you need to uh understand the core logic of wine research and you can easily make back so let's please i mean take care of it yeah so if we didn't met if didn't we if the condition isn't met we need to this is a basic template and it's very applicable to our problem using mine research so thank you for watching
Minimum Limit of Balls in a Bag
check-array-formation-through-concatenation
You are given an integer array `nums` where the `ith` bag contains `nums[i]` balls. You are also given an integer `maxOperations`. You can perform the following operation at most `maxOperations` times: * Take any bag of balls and divide it into two new bags with a **positive** number of balls. * For example, a bag of `5` balls can become two new bags of `1` and `4` balls, or two new bags of `2` and `3` balls. Your penalty is the **maximum** number of balls in a bag. You want to **minimize** your penalty after the operations. Return _the minimum possible penalty after performing the operations_. **Example 1:** **Input:** nums = \[9\], maxOperations = 2 **Output:** 3 **Explanation:** - Divide the bag with 9 balls into two bags of sizes 6 and 3. \[**9**\] -> \[6,3\]. - Divide the bag with 6 balls into two bags of sizes 3 and 3. \[**6**,3\] -> \[3,3,3\]. The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3. **Example 2:** **Input:** nums = \[2,4,8,2\], maxOperations = 4 **Output:** 2 **Explanation:** - Divide the bag with 8 balls into two bags of sizes 4 and 4. \[2,4,**8**,2\] -> \[2,4,4,4,2\]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,**4**,4,4,2\] -> \[2,2,2,4,4,2\]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,2,2,**4**,4,2\] -> \[2,2,2,2,2,4,2\]. - Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,2,2,2,2,**4**,2\] -> \[2,2,2,2,2,2,2,2\]. The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2. **Constraints:** * `1 <= nums.length <= 105` * `1 <= maxOperations, nums[i] <= 109`
Note that the distinct part means that every position in the array belongs to only one piece Note that you can get the piece every position belongs to naively
Array,Hash Table
Easy
null
152
what is up everybody welcome back to my channel this is tony aka one lead code one day if you're new here this channel does one lead code per day following the pattern of topics or series that is i'm going to be solving with you together on a lead code problem i have never attempted before you heard that right there is no prescribed hit enter we are on the same page here but don't you worry i got your back and i promise that i will submit at least one average code average performance code at the end of each video so here's a little bit about myself i come from a non-computer science i come from a non-computer science i come from a non-computer science background so i am no better off than most if not all of you guys in terms of coding knowledge but that is okay if i can do it you can do it is all about learning on the go and you can think of this video as a first person game play of cracking lead codes and who doesn't like first person gameplays so without a do let's start today's code problem um today we continue on series one everything about dynamic programming and the problem is one five two maximum product sub array also i would like to announce a change of strategy taking from lessons uh yesterday so yesterday if you watched my yesterday's video um i did problem 918 maximum sum circular sub-array and i maximum sum circular sub-array and i maximum sum circular sub-array and i took about 12 hours to actually finish and manage to submit that problem um it was a heck of a day and i went through a lot to actually get something right but here's the lesson if you're just taking lead code for code practice towards a skill set maybe for a job or for your career path um optimizations then do not like spend all day long on just one problem because that's not what lead code is intended for um so rather you would just try experiment the problem on your own for a bit maybe an hour maybe or two um depending on your pace and then if you don't get it that's fine just take a look at the solution or some other people's code submitted and then try to learn the structure the algorithm that people are using and then just try to implement that on your own um so there's no shame in uh not finishing one lead code completely by your own because nobody does every lead code on their own eventually someday some problem will get you i promise you that although i've only done like about 10 lead codes up to now but i think that is going to happen for almost everybody um like don't really don't i hate to say this but don't treat yourself special okay you're not you're probably not that you know 0.01 you're probably not that you know 0.01 you're probably not that you know 0.01 coding genius that is born to do this without you know the proper education background in algorithms so i'm pretty sure i'm not that guy so um i did the wrong choice yesterday to you know spend all day long on one problem and so i'm going to change my strategy today and i'm going to work on this um you know problems from today on uh on a time limit so uh for the first hour i'm going to try to come up with something that works and if i don't find any uh hope of finishing it um uh within the next 30 minutes after one hour or so i'm going to look at a problem solution and i'm trying to learn from it and then i'm trying to implement that on my own after reading the solution or some other people's code so this is going to be the change of strategy uh and let's see how it goes all right that being said let's get into the problem okay maximum product sub array medium given integer array find a contiguous non-empty subarray contiguous means it's non-empty subarray contiguous means it's non-empty subarray contiguous means it's like a continuous right um within the array that has the largest product what is what does it mean by product or return the product the test cases are generated so that the answer will fit a 32-bit integer a sub-array is a contiguous subsequence a sub-array is a contiguous subsequence a sub-array is a contiguous subsequence of the array okay example 2 3 minus 2 4 the largest product is 6 right because you don't want to multiply odd numbers of negative numbers right example two uh for this one actually it's going to be zero got it and then we have some constraints length is between one and a large number uh actually this is good like the um the values of each uh values of each number in the list is just between minus 10 to 10 so uh relatively small but if you think about you know this is because this is like a product so these things better be small right the product of any prefix or suffix of nums uh it's guaranteed to fit a 32-bit uh it's guaranteed to fit a 32-bit uh it's guaranteed to fit a 32-bit integer well that's good we don't have to talk about you know uh data type overflows in this case so anyway we're going to work on it for a bit uh let's start a python notebook first and rename that with today's lead code problem number 152 and whoops where's it here 152. now we're going to just put a mark down here with the problem description and some examples so example one there right example one also we want to copy the constraints just right now copy the constraints in there to remind us what constraints maybe we can exploit on our own uh there we go yes there you go and then we're going to copy the solution template there right and now we're going to go back to think about the problem how to solve it so it is a maximum product problem so and it's within like a list or an array and we want to find a sub array uh so this naturally can be solved by dynamic programming because we're looking for a maximum of something right and uh and it's sub array so looking for a subarray it could be maybe generalized into sub problems and we solve we can do the bottom-up approach and we can do the bottom-up approach and we can do the bottom-up approach and solve sub-problems and then you know solve sub-problems and then you know solve sub-problems and then you know solve eventually the big problem let's you know without hesitation get into uh prototyping right so here is our first example here and um how do we do that i mean we can iterate but that's probably not the best thing to do um or we can try to be more strategic and think about what's the special thing about product right um so instead of sum when we talk about products you want to first make sure that you know the signs matter right signs matter that's the first thing that probably you should take into account like you don't want your final product to be negative so um only take so only take uh negative values in pairs right in pairs and never singles yeah only take them in pairs right yeah or let's say a multiple of two or not you know or not take them or don't take them at all or don't take them yeah so this is just the first lesson here um i think it's important and then of course aside from you know the negatives maybe well we can just split the list into maybe two sub lists right one is like positive one is negative and then you pick and then of course you um but because their position matters too so a negative number is kind of like a door or like a barrier that you have to consider whether you're going to cross that or not because just like a door but then you want to cross two doors at the same time like you don't want to just cross one door right and for multiplication you want really as many factors as you can because even because the absolute values are like between minus between 1 and 10 and they're all integers so nothing hurts the only thing that can hurt you is the minus sign here right basically the only thing hurt the value is the minus sign if sine is not a concern just take all as many numbers as possible in subarray right in fact you want to take them all if you can and you only stop right so just write that in fact you want to take them all if possible you only stop uh you only stop expanding when you know uh um when there is like one when there's one negative value left uh up in front of you and you know and maybe some positive values behind it there's only one eight value left okay so picture this right i think this is a good thinking picture this uh in the end of the day after you picked your picture maximum subarray you are you're left with the you know what's left in the array is either one nothing two one negative value and maybe some seductive values on one side of it one side of the negative value the only negative value right so this is a really good picture right yeah that's a really good relevation for example just for this problem right so after you've picked your after you've taken your pick of your optimal subarray you're always left with um one negative value either one negative value and some remainders here write some remainder we're going to just use this bracket to indicate the remainder so this is the you know the one negative value that we're talking about the one negative valley left yeah uh and then you're gonna have maybe some positive remaining yeah this is some kind of like yeah the sum positive remaining values on one side yeah so this is like optionally this and this is optional as well but this is you know optional based on you know existence of one negative value left yeah so this is like the optional of the optional right so in some cases you're just left with nothing right for example you could have an even easier case if you just have you know a plus two right then you're left with nothing right in this case left with nothing so in this case we're left with nothing um what about let's say another case where you have you know uh a minus somewhere here right if this case then um you know you're left with just a negative one negative value and that's it so in this case you know in this case you just take them all in this case you just take this right so yeah these are like the only three types of possible ending of the story uh right so these are like possible endings you know leftovers you know possible leftovers are just like these three i think that covers at all you're either left with nothing or you're left with one uh negative value or you're left with uh one negative value and the trailing uh set of positive values it could be on the left hand side it could be on the right hand side doesn't matter because you know yeah let me just be more specific i guess to explain this you know a fact um if you have you know 2k plus 1 negative values in nums you'll always use 2k of you always take yeah i always take 2k of them and leave one unpicked that makes sense right i mean as long as you take as long as you can take you know um as long as you take um a multiple of two of uh negative numbers you can just treat them as one for the effect you can just treat negative numbers as if they are positive as long as you take uh multiple i should take them in pairs right a multiple of two right this is like a further for the fact that you uh that you're going to have to accept right yes but the fact you can just treat negative numbers as if they're positive as long as you take them in models of two right and uh um and that's a really powerful thing so you can ignore the signs partially right and just treat the array as like a positive array and then if it's a positive way you're going to take them all right so you really just want to um search from the both ends to find the first negative value right so here's going to be my strategy count the total number of negative values right that's the first step and if the number is uh even just return the full list right if the number is odd just determine which uh which just you know just yeah just pick the um uh the one or two you know most sideway yeah most sideway most sideways are negative numbers you know n1 uh numbers and decide which uh which one and the trailing you know positive numbers uh with them uh to remove you know to uh to give up right to give up yeah that's the strategy so i'm going to just say that right uh let me just demonstrate what i mean by saying that i think i just found the solution at this time hopefully it'll be quick but uh let's just draw what i mean okay yeah what i mean is that um right you're gonna have a list of numbers right a list of numbers uh in the case one if like number is even you just multiply all of them and in the case that you know the number of negative numbers is odd then maybe like one is here right like this is like uh n1 this is like negative right negative then maybe you have an n2 somewhere here it's a negative so you're going to take you're of course going to take all of them all of these inside right all of these in between you're just going to take them because you have um an even number of um negative numbers in between you can take them all and then you're going to decide whether you're going to ditch these or you're gonna ditch these right for this part it's positive this part is positive right and this is like you know yeah this is like money in the bank i'm just again gonna say it's money in the bank and mitb for money in the bank so it's something you're definitely going to take and then you're going to determine um whether to throw up uh to you know give up which right this is a question um to decide you know and this could be decided by uh by calculating let me just you know um right let's just see let's just say that if you multiply them all this is gonna be uh the union right is it union uh what you know it's not sum right like sigma means sums um what is the what is this i guess what is the uh um sign for like all the products i'm just going to say p right this is p1 and this is p2 right the product of all of those if i calculate um uh well sorry i mean if the total number is odd that means we have you know uh odd number of negatives within this right that means this within this part so we just need one more negative number which is to you know choose which one to take and choose and also take the uh the positives um you know just the trailing positives behind it uh so which one to ditch which one to give up we're gonna calculate um which one's larger right like calculate p1 times uh minus n1 and then versus p2 times minus n2 and then you know it'll give up let give up the lesser right just keep the larger yep oops that's uh yep that's about it and uh it's uh i guess a simple enough solution to implement so now let's try to implement this and see if it works so now the first step is we're just going to count the total number of negative values right all right step one count the negatives um right for loop for k in range uh or let's say just k in um for num and nums right uh um if num is less than zero count plus uh count plus equal to one right we're gonna just uh say net count right net count equal to zero let's just say net count uh let's just say end neck right an egg right so this is how you're going to count the number of negatives and we're going to decide all right if an egg yeah if an egg is even just return the full um full list right just return the product with the full list uh do we really want to return the product yes so if uh neg uh divided by two equal to y equal to zero is that how you do it like python mod modulo right the percentage operator by the modulo operator basics so 15 modulo 4 becomes 3 which makes sense 17 modulo 12 is 5 makes sense so yeah that's what we wanted if the modular is 0 right then we're just going to return um how do you say you know python product of list how do you do that multiply all numbers in the list four different ways um wow we need a for loop maybe right yeah something like that for loop result that's one way of doing it numpy prod well we don't have numpy um there's a lambda function way of doing it okay i think we're not gonna do anything fancy so we're just gonna use the for loop and also um and also maybe uh maybe we can just also accumulate the product and let's not do that let's just say um for num in numbs product equals uh product times uh let's say initialize product as one right initialize that product initialize that's one well maybe we should initialize it uh here if that and we're going to do this for loop now we're going to return the product um right else meaning if the number of negative is odd right then we're gonna decide um and we're gonna decide if right pick the one or two most sideways negative numbers and decide which one to give up right so right you're gonna have a left most negative right so let me just call them right n1 leftmost negative number and n2 is the rightmost negative number in the list in the original list um they could be the same value if we only have right we're gonna say that okay and one and two could be the same value if we have only one negative value in the list which is okay because we're still gonna just give up uh um give up um you know either that or that right so it's not a special case it's generalizable so else find the left most negative and one and the right most negative and two i think we could have done that in this first for loop as well right so um right if and neg equal to zero right so that means if it's like the first one we're finding then you know n1 is going to be uh num but hey we also want the uh the index number right so yes so actually we would like to you know k plus equal to one we also want to you know find the indices right k go to zero this is like index of index in the array in the list right um so this will happen whatsoever right and one let's say k1 equals to k yeah k1 equals to k right and then of course for the last uh negative number in it for the next for the last yeah no just uh mark the first negative index and then um we're gonna do this um k2 equals to k as well you know this k2 will eventually be will eventually mark the last negative index right we're just going to use one for loop well don't you think that it's going to be easier if you just go for a loop and backwards yeah inefficient i know it's inefficient but let's just work out a solution here right so we already found them so it's k1 and k2 here uh and so once we found them decide which one to give up right by comparing right so the leftmost negative and one is our index by k1 k2 so fine um compare the product of p1 times n1 negative n1 right and you know n2 negative n2 times p2 right let's say prod 1 is this uh prod 2 is this and um leave the lesser one yeah or just say take larger one so prod one equals to uh what is p1 so because n1 is uh um so it's going to be a for loop for k in range of k1 right so k1 is like the index before on the index before um yeah the index of the first uh negative so this these case will stand for all the positive values in p1 so um product right prop 1. i'm going to initialize prop 1 with 1 plot 2 equal to 1 as well we're gonna just initialize those plot one uh equals to prod one times uh nums of k right so that is going to be you know multiply all positive in p1 and then of course you're gonna have to uh take into account you know n1 so this is n1 right multiply by n minus n1 right you're going to do the same for um for p2 so now this is going to be k2 actually um wait um that is if we still have anything after k after k2 right so range k2 plus 1 um if it exists at all like if they exist at all right uh k2 plus one uh um or let's say in nums k2 plus one all the way to the end but maybe k2 is the last index possible it's possible right so maybe this is out of the uh um you know yeah i could how do we express this like right maybe we just use an if condition if uh if k2 is less than um lengths of nums minus 1 meaning there's still some positive values left there's still positive numbers in p2 then um we're going to do range k k2 plus 1 r2 yeah so let's say n equals to length of nums and this is going to be n minus 1 then it's going to be that to n right the range of that and then we're gonna just multiply all possible values in p2 and then of course we're going to multiply it by minus n2 right that's it well if there's an if right we only actually multiply them in p2 um if there is actually a p2 if not it'll just be one like we initialized yeah if there are still values in there we'll multiply all of them otherwise we don't and then product two is like that and then um now we have plot one and plot two right so we're going to compare uh if prod one is greater than plot two right then we're going to take um we're going to compute the rest you know um mitb money in the bank right we're going to compute money in the bank uh compute money in the bank actually what that means is that then we're going to take all um you know take the product between num zero and nums uh let's say it'll be k2 right 0 and k2 minus 1 yeah k2 minus 1. so we're gonna do a for loop for num in nums uh the beginning to k2 minus one product equals to product times num right and we're going to return product else we're going to take the product between nums um if the if n2 times p2 wins we're going to ditch p1n1 we're going to take values from k1 plus 1 all the way to the end yeah siren going on outside um k1 plus 1 and nums uh you know the last and minus one so um we're gonna do uh nums in um uh k1 plus 1 all the way to the end right and return product so i think we got it but maybe we have not taken into account like the small um the special cases like just one value in there so we may have to find some test cases like that but now for now let me just copy paste and start to use the syntax for the solution template input this we want to expect six right what is the function name max product all right so let's just run it and see what we've got whoops um we only got six why is that well in this case we're going to put a debugger on because in this case you know n1 and n2 are the same thing k1 and k2 are supposed to be the same thing and we're going to see if that's the case okay k1 and k2 should all be like one but uh we'll find out if that's the case now let's see k1 is 2 k2 is 2 right they're both 2 right that's correct so if they're both too the next break point we're going to place and the number of negative values a neg is one right so because neg is uh is odd so we're going to go into the else condition and then we're going to compute prod 1 and plot 2 and what do you think is plot 1 well plot 1 is going to be all of these multiplied together it'll be 6 by 2 so it's going to be plus 2 is going to be 2 by 4 it's 8 right plot 1 should be 12 plus 2 should be uh let's just put the yeah put this big point at line 36 and see if plot 1 is 12 and plot 2 is indeed 8 that's what i want to see prod 1 12 part 2 8 that's exactly right and that's what we want to see right and therefore we should uh take the product uh oh hold on we should take the product um in this case this part is larger right then we're gonna take all of these and multiply by the money in the bank or you know um this number all the way up to b4 and two right so it'll be uh zero all the way to k2 minus one all right and k2 minus one because k2 is 2 so k2 minus 1 is going to be 1 right so for nums and nums uh k2 minus 1 um product equals to product times num so the first one is going to oh sh i think it should be num instead of numbs anyway so that's a typo there um num and nums right so that's a quick fix that we should oh we should get hey but why is it two because now we're getting less um let's just uh yes product return product yeah we're still going to need let's just try you know maybe this simple you know a simple syntax right i think maybe let's say four five six right and four you know there's ace now numbers for number and numbers right print number yeah it is going to print everything all right what about let's say numbers in numbers all of that till two oh right you know for these kind of like indexing you really need to um add one always add one to the last right so you add one to the last so this becomes that right because you need to add one and this one here i think this one is fine now yep that's correct the next test case uh this one should return zero it's kind of like a special test case right so this is gonna be some kind of a special test case right it should give you zero yep all right so how about let's just test ourselves the special case when there's only just one value in there if there's just one zero in there we should also expect zero right let's see if it actually gets zero yep um what if we only have like a one value of like minus two and we should expect minus two right well that's the thing like if we have a minus value there largest product yeah this is going to be a problem because you have to take into account if there's only just one negative value right what if there's just one negative value what do you do um so now we have counted that there's like odd numbers of negative because there's only one well the easiest way you know to do everything is if you can just calculate this n here and then if n equal to one you just outright return nums zero and that's it right that way yep i think this is a more complete answer now and let's submit it for evaluation test examples correct let's submit okay whoa zero two and we're expecting two wow okay new test case to be looked at right i see 0 shouldn't be treated as positives right so we need to take a lesson here yeah take a listen zeros shouldn't be treated as positive it ain't that you know ain't that obvious so zeros are like resetters right i wasn't actually you know i wasn't actually taking into account zeros in any of these right so we were just counting negatives we weren't counting zeros yeah so negative and zeros they play a very different role um in multiplication so uh do i want zeros i mean we want positive numbers so we don't want zeros we're going to avoid zeros at all costs right so this is gonna be our um our strategy you know avoid uh hitting zeros at all costs the only time when we actually take a zero is if everything else are negative values everything else are negatives is negative everything else is negative yeah the only chance the only time when we actually take a zero use of everything else is negative so then what do we do well so zeros are like resetters if you find like a zero uh somewhere in the array you don't run across it you your heart stop right so yeah when we run into zeros in the array in the list um we are stopped so they're like spacers that you know or they're like you know those um compartment doors right uh that shuts the whole array into different uh compartments yeah zeros are like compartment doors that isolates the full list into um compartments right inner compartments that yeah the isolate um the full list into compartments that's true and any number i'm just a braid the largest product right so i think we have not really worried about zeros right so let's just go ahead and you know let's say you know everything here uh you know zero was not considered in this page zeros were not considered in this page on this page so we're gonna dedicate a new page for zeros right this page address the zeros yeah and the zeros are like compartment doors they're like isolators right compartment doors we're going to just take them you know zeros the compartment doors right so if you want to you know just kind of like draw a comic to show what they are whoops yeah if you want to just draw a comic to show what they are and use three pixels right so if you have oh what is going on wow my pen is again throwing a tantrum at me so in this case i'm just going to use my mouse to draw so for example if this is your list right and you're gonna have like zeros at these locations like zero uh zero and zero then they're like compartment doors and you know this is like compartment one compartment two compartment three compartment four so these are your sub problems right c1 c2 c3 c4 uh it shuts them into compartments and then you're going to have to worry about that you know right so actually know what we can still reuse this but this is like this is not max product this is like max product without zeros and zero free right but we're still gonna have to um define a function you know that address this general zero um problem so what we're gonna do is we're gonna find all the zeros you know doors compartment doors ryan wagner and our strategy is like so yeah we're going to just basically say our strategy here okay strategy find all zeros i'll identify um you know and then separate then split the full array full list into a separate compartment sub-list then um then calculate the max uh max product array within each compartment sub list and take the max yeah so this is my strategy here uh first we find all zeros then we can split them into separate compartment sub-lists sub-lists sub-lists yeah split the original list into uh sub-lists divided by the zeros sub-lists divided by the zeros sub-lists divided by the zeros right and then compute the maximum of the sub list product sub list max products right so that's how you do it um final the zeros well how do you do that you're just going to use a for loop search right um for num and nums right or actually just to k for k in um let's say n equals to length of nums right for k in range of n we're going to um see if nums of k well actually this is not gonna be very efficient you know why because if you look up lists you're gonna have to scan the list and it's gonna be slow um so but it's okay i mean we're going to optimize it later if num list k equal to zero if we found a zero right equal to zero uh we're going to add that to um we're gonna split how about let's split them in here uh now um can we do that well we can append a list right um zero list i'm gonna do that and uh zero list append um okay yeah so i found we found all the zeros here in the zeros list right but if you know how to check if it's empty uh python check list empty how to check um if list is empty length okay makes sense if length of zeros list equals to zero we're just going to return um self dot max product zero free of nums because we know it's zero free else um we're gonna divide or else we're going to split the original list into sub lists divided by the zero so for each um for each zero in zeros list right for each of the zero and zeros list um it is going to be how do we chop it how do we chop this uh list so let's just draw that so this is like the first one right we're going to have a zeros list let's say it contains what here k1 k2 k3 uh that's the case here right because this is gonna be k1 well no let's forget it um this is k1 this is k2 and this is k3 okay and these are our zeros and so the way we're gonna split all these lists the first list you know the first list sub um sublist one of course is going to be uh from the original nums of uh from zero from you know the beginning all the way to k1 minus 1 right but we're gonna just use k1 because that's how this column works uh it's only going to count up to k1 minus one yeah uh right and uh after we've done that shall we just yeah we're gonna update like the beginning yeah and start right and start we're going to update and start yeah we're going to do like an instart first aw0 of course that's you know initializing and then k1 and then we're gonna update and start this now it's becoming k one plus one that's the new start right and then the second list will be n start all the way to k2 right and then we're gonna again update this in start to be k2 plus 1 and then the next sub list will be and start will be k3 right 2 sub list 3 um if we do have a sub list for okay three equal plus one and uh if we do have a sub list four there um it'll be and start you know to the end i mean something like that um that is if you know if we still have something yeah let's say this is if you know k3 is less than n minus one it only happens if k three is less than n minus one then we're going to have uh this right because there's a chance that you know this zero is the last one in the original list so here we go we have a uh an iterator yep so um for zeros and zeros list right we're gonna see and start yeah we're gonna end start equal to zero you know initial uh sublist start index in original nums list right um so for that our sub list equal to um equal to nums and start until k1 and start all the way to uh zero right because yeah that's how you do it um to the first zero um and then there's an if condition if zero is less than n minus one right if we're still not at the end of it we're gonna do this and we're gonna um send the sub list what to calculate that right um bright um we're gonna do sub list max append right we're gonna append that and uh selpus max we're gonna say it's that uh container for sub list max products i'm going to append that right so in the for loop like that we're gonna we have implemented this if condition right so this helps to define you know if we're hitting the end of it um and so we're going to do this until k1 this until k2 uh this until k3 and then we're going to update and start after we've done that uh update and start how do we update and start well end start equals to zero plus one right yep um shall we actually use a while loop because well we're going to do for loop and since we have three of them this is only going to create three sub arrays sub yes a brace and it's not going to work on the number four right so this number four is something you know all these are like the for loop right this is going to be like a for loop uh and this is like the last treatment right the special treatment here and for the for loop we really don't need to worry about um this because we're just taking the sub array before these zeros so right we're not going to be worried about that and you know after all of that you know see if there are still um numbers after the last zero uh if so if zero last is less than um if this is like less than n minus one that means yeah we do still have some array there then we're gonna do another sub list equals to you know and start which is going to be 0 minus 1 uh plus 1 all the way to the end right and then we're going to still do this sublist append and then we're gonna compute the maximum all right i think that's all the sub lists uh we're gonna compute the maximum of the sub list max uh product so we're gonna return actually the max of sublist max right yeah so this is a prototype i don't expect it to fully work all right so there's something here and object is not subscriptable oh okay because there's only one zero so i guess that's why it throws a tantrum at me actually we're at the last zero right oh zeros uh yeah zeros you should say zeros so that should uh that should work now name zeros is not defined okay zeros is not defined zeros list right okay that worked what about the rest six well this went wrong um wait expected six how can you expect six in this is like weird expect six right um let's see expect zero minus two 0 -1 we should expect 0 for this let's see um well this one actually produced minus one wow okay so these two are problematic we have two problematic cases but i think i know what's going on because we said that excuse me if you remember we said that um the only time that we uh when we actually take a zero is if everything else is negative we have not implemented that right um if everything else is negative which is the case here then we're going to take a zero so where do we put that special case if like everything else is negative um if everything else is negative right we can do it here because we don't really care about the value of the sub lists in here we only care about it at the last moment right so if let's say it um if all the sub-lists are negative right can we still return negative somehow yeah we could still return negative somehow um if all the sub-arrays um if all the sub-arrays um if all the sub-arrays are negative we rather just return zero yeah if yeah i'll just calculate um result equals to you know sub list result if sublist result um is less than zero return zero else return this is probably going to fix one of those problems but then what if we only have one zero in there yeah so what happens if we only have one zero in there um again we want to add this in there right if n equals to one we just you know return whatever is in there yep all right so i think uh we just did a hot fix for that singular case and now six zero minus two um looks alright let's just submit it to leeco to see if it now satisfies the problem definition simple test cases were correct but we still got our own answer here so 0 minus two zero we should expect a zero okay so there's something that we're still not considering correctly oops what did we just do zero minus two zero um for this one we're expecting zero and what do we get we are getting one i see huh but hey i mean um shouldn't we in this case i mean return zero because in this case the sub list result is like less than uh all of them are like less than zero and you should just return zero right so now let's just try it okay restart the kernel and after that we start the debugger and we set the breakpoint at um here want to know what are the sub list results because according to this the sub list results should be like a minus 2 or something wait oh yeah did it go there yeah sub list result is what one really sub list max is a list and um it's got a one and a minus two wow how come we have two sub lists that's so strange um right so the sub lists okay this is where we for zero sub list because the first zero is at zero so it's going to be numbs um zero to zero okay it's going to be numbs zero to zero um what is zero to zero right just because yeah the in start is zero right and then the first zero because the zeros list is going to be zero and uh 0 and 2 right yeah so this is going to be 0 and what happens with nums 0 to 0 i don't know we'll find out like yeah what is going to be numbers uh 0 to 0 what does that return us let's try that empty okay so if it's empty then max product zero free with an empty sub list so what do we do with empty sublist are we going to return yeah we're going to return something called a uh one and that is totally wrong so we're gonna have to account for cases where the list is empty so what to do if the max product of that is like we shouldn't be sending empty lists to uh to it here right because by design we want to make sure that you know this zero the first induction of the zero um is not zero because if the first element is zero we just ditch it right we want to make sure that the first one is not zero make sure yeah make sure the first one uh if right we're gonna say if uh if k y equal to zero just ignore it right if k one equal to zero just ignore it so how do we ignore it well zero's list uh let's say yeah we can afford if zero is not equal to zero we can afford this right because there won't be like a huge number of zeros so we can afford uh this computation yep but actually uh but actually even for um even for this yeah we're still gonna update and start in that case yeah so it's just that you know we don't make a sub list for the first if 0 equals to 0 if the first zero is at index zero we don't do that yeah just like that whoa what is wrong ah okay we didn't include a uh um a column right so that is okay and let's try everything else expected minus two zero yep now this seems correct uh let's just submit it again to leak code let's just directly submit it okay accept it um great and you know our runtime actually beats most people great so that means our algorithm really is pretty it's pretty neat and efficient and memory usage is fine because i think we could still improve by you know um removing some of the unnecessary variables i guess we can improve that still but i mean this is not bad right beats 99 let's uh submit it again whoops um it only beats 19 so and now this beats uh 76 so it's i guess it's like above average so all right um it turned out today's coding is pretty smooth and i'm going to so before i wrap it up let's take a look again at what we have so we had basically several key insights into the problem the first insight is that you know signs matter and the only thing that can hurt the product value is the minus sign so we need to be careful how we deal with minus signs um in the list and uh the only thing we need to differentiate is whether there's like odd numbers of amount of signs or negative signs or uh or even numbers of negative signs so for the odd case for the even case we just take them all for the even case um for the even case we take them off with the odd case we're just gonna have to make a choice between taking the left most negative sign or taking the right most negative sign we're of course going to take everything in between as well and this discussion is you know without the consideration of zeros so then we went on and took the consideration of zeros so zeros for multiplication tasks they're like compartment doors you know they shut the list into separate compartments and that's what we did so we had a more higher super level higher level function that identifies these compartments and then we're going to use another subroutine or another function to compute the max within each of those compartments and then come up with the maximum of them and that is it guys that's our algorithm and it worked beautifully um we got accepted uh and then an internet above average code um so that's it uh lastly let's take a look at some of the solutions there's of course the brute force iterate everything your complexity to be high oh by the way what is our complexity i mean for our problem um our complexity right uh we probably have in terms of uh time complexity um oh if uh and because we didn't have anything that is like a for loop inside a for loop uh with respect to n so we probably only has that and in terms of space complexity are we remembering anything like extra complicated um well we do have for loops right but for loop is not a memory uh so we are sending the sub array into functions so i don't know it's somewhere between of one and o of n i guess somewhere between all of one and of n right yes something between there i'm not quite sure but yeah now this complexity yeah the computation is pretty heavy because if you use brute force you're gonna have to sweep the beginning and the end dynamic programming yeah two things can disrupt you combined uh zero is negative numbers right zeros will reset negative numbers a little bit tricky single right so you're going to have to think about odd numbers or even numbers you're going to use dynamic programming to compute your thing and it's on and one so actually um i think we could have tried the dynamic programming approach here using your using this uh using this intuition here but ours is not bad so i'm gonna just sit on it and uh if you're interested you can take a look at the solution here uh for the dynamic programming solution right it's a python3 dynamic programming solution and then in the discussion of course you can find wow okay you can find people's solution there this guy's face show up a lot i guess he's really cool um right and you can read some of the codes in there more simple wow this is really a simple code anyways there are multiple ways you can attack this problem um and i just did it in my intuition um let me know if you found you know my code could be improved in any certain ways or if you found like a smarter trick let me know in the comments and uh thanks for staying along with me and i'll see you in the next video oh wait hold on um today's summary i think we just uh walked through our summary so all right that's it i'll see you in the next video
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
1,925
let's solve 1925 count Square some triplets so the question says that you need to find all Pythagoras triplets until the number n so say for example of the N is 10 okay n is equal to 10 so I need to find all Pythagoras triplets under 10 so the first one would be 3 4 and five where three square of 3 + square of five where three square of 3 + square of five where three square of 3 + square of 4 is equal to square 5 right similarly there would be 6 8 and 10 we just double all the numbers and it also becomes Pythagoras triplet which is 66 36 88 are 64 36 + 64 is equal to 10 36 88 are 64 36 + 64 is equal to 10 36 88 are 64 36 + 64 is equal to 10 are 100 so that is it since n is 10 this is the most we can get now let's look at some other pyus triet under 10 then there is variation of this so three 4 5 4 3 and 5 is also a Pythagoras TR similarly 68 9 8 6 and 9 is also 8 6 and 10 is also Pythagoras triplet right so we just swap these two numbers and we get another Pythagoras triplet similarly there is so that's it so there are four pyus triet under okay to find out Pythagoras tripletes up to n that is a interesting method say my pyas trip is say anything any number say 10 or 15 or anything right so what will I do is I'll go for all the numbers between 1 and 15 okay and take it as X okay and I'll take all the numbers from 1 and x and take it as Y and I'll just check if first of all I check if X and Y both are even then I can ignore it if X and Y both are odd I can ignore it and if gcd of X and Y is greater than one then I can ignore it okay well uh so if gcd of X and Y is greater than one it cannot be a pyus triet but if it's even numbers or both are odd numbers then also we can avoid it and finally I need to check so if can find Pythagoras triet by doing x² that is X into X Plus X Y into Y and 2 x y and x into x - Y into Y and 2 x y and x into x - Y into Y and 2 x y and x into x - Y into y so this gives us 3 numbers which are Pythagoras triet okay that's a method of figuring out that's one way of figuring out Pythagoras trib so we are going to use this method logic and as we have seen in the example that once we have a Pythagoras triplet we just need to add the same numbers in it and we get another Pythagoras Tri in like in case of 3 4 and 5 double of 3 + 3 6 4 + 4 8 5 of 3 4 and 5 double of 3 + 3 6 4 + 4 8 5 of 3 4 and 5 double of 3 + 3 6 4 + 4 8 5 + 5 10 + 5 10 + 5 10 similarly 9 uh 12 and 15 are another Pythor triplate and so on right so you just keep adding the same numbers once you find one Pythagoras triet until the third value is less than or equal to n which is provided to us okay let's code it up so what I'll do is I'll first of all what I need to return is I need to return the count how many pyas tripletes are there so I'll maintain a variable count initialize it to zero then I'll do for X in range 1A n + 1 n + 1 n + 1 for y in range 1 comma X okay so in that case I can even initialize this to be two right because one will never be an option okay and then I can check I can do a three do the three checks if x is odd and Y is OD okay or if x is e even and Y is also even or gcd of X comma Y is greater than one then don't do anything just continue skip this Loop and continue to the next now we are calculating gcd here so I need to create a function named gcd so I can do that here gcd it takes an A and B while a comma B is equal to B comma a person B and finally return B right that will give me the gcd that's the one way of calculating um gcd and then if it pass if it doesn't pass through any of these conditions then it continues to the next line and there we see we calculate the third value only this we need to check the largest value among the triplet if it is less than n less than or equal to n so the third value would be X into X + Y into + Y into + Y into y okay and we'll check if x if to sorry the spelling is incorrect third if third is greater than n third is if Y is 1 Y is = 1 and thir is greater than n then we return C right and after this what will do us this condition basically says that if thir + x into X which will give us the this + x into X which will give us the this + x into X which will give us the this entire oh sorry not third if Y is 1 and X is equal to n then return C so what does a Sayes X into X then we'll check if Y is = to 1 Y is = to 1 Y is = to 1 and thir is greater than n in that case I'll return C and if not then I'll continue figuring out more SE so I'll check while her I'll basically take third into a new variable say t and check if T is less than n continue okay and in that case I to add two count to C because both variations will count if it is 3 4 5 so 3 and four and five this variation and four and three and five so two variations will count so I add those and then I'll increment T by3 so it will check for first time it will check three four and five next it will check 6 8 and 10 next it to check and so on of 9 12 and 15 right so as soon as it crosses next will go on to 12 15 and 20 but since 20 is great than n which is 15 it will break the loop okay so once it breaks the loop I do not have do anything I just continue okay finally I return slight error in this calculation of gcd it will be while B and I'll return a so while B because I'm reducing B at a faster rate than e but this is not C this is Count this is count and this is Count slight mistake here this will be T less than or equal to n let's run this and that worked let's submit it and that work too
Count Square Sum Triples
count-nice-pairs-in-an-array
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2:** **Input:** n = 10 **Output:** 4 **Explanation**: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10). **Constraints:** * `1 <= n <= 250`
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map. If it is, then add that count to the overall count. Then, increment the frequency of nums[i].
Array,Hash Table,Math,Counting
Medium
2129
138
lead code practice time so two goals the first one is to see how to solve this problem and then we are going to put some code here and the second one is to see how they behave during every interview suppose this is some problem happening in the real interview so let's get started so the first one is the first step in the interview is always to try to fully understand the problem if there is anything uh unclear please bring the question to the interviewer and at the same time think about the ash cases so let's take a look so copy list with random pointer a linked list is given such that each node contains an additional random pointer which could point to any node in the list or none all right so it has two things the next pointer and the random pointer okay so return deep copy of the list the link list is represented in the input or output as a list of n nodes so each node is represented as a pair of um of okay so each node is represented as a pair of value random index square while it is an integer representing no doubt value a random index is the index of the node where random pointer points to or none if it doesn't point to any node all right so let's see um example something like this okay so i think i kind of understand i pretty much understand what is happening here so let's see node value is between active ten thousand to ten thousand and no dot random is none or pointing to a node in the linked list so number of nodes will not exceed 1 000 okay sounds fair so let's see how to solve this problem so how to solve this problem one thing i can think about is uh so we so the first so we have so we will have uh two pass so the first pass is to so we are going to go through the linked list and do a copy of each of them and get the linked list instead of setting the random and at the same time we are going to have a hash map from the original node to the copy node and then for the second pass we are going to set the random index based on the hashmap so that's my thinking so this one the runtime is going to be all of n so space y is it's also going to be olefin as well so n is the number of the nodes within the linked list uh that's the that's this solution um so let's see i think it's the best regarding the runtime but let's see if we can save some space so i'll say um so we need we really at least we need to find the relationship between the original node and the copied node so i'll say if the list is modifiable one solution to save the space is we could tweak the original linked list so for example we have this linked list and we have the copy links that link list we just set the copied linked list to the next node so like we insert a node here like which is the copy node of seven and similarly we do a copy node as 13 like sometimes like this so this is the first step and then the second step is we try to uh we try to set the random node for the new created nodes so because node dot random pointing to so for example for this one the red node seven for node seven the random point into one so for sure that the next node the random pointer is going to be the next node of this node so that so in this case we are going to reset the random node there this is the second pass and the third pass we are going to detach the new nodes from the original link list and form a shiny new link list there so that's so for this one it's gonna need um a one regarding the space um yeah so but it really depends you need to ask your interior if the link list is the input is modifiable or not so let's assume is not modifiable because that's easier to implement and let's do some coding work so the correctness of the code and the readability of the code and also the speed of the code so you can discuss with your interior whether it's modifiable or not so i would say there are two paths if the inheritor wants to give you some more difficulty of course he is going to say okay this is modifiable and go ahead to implement the space-saving implement the space-saving implement the space-saving solution but let's just go with the hashmap solution so for this one you have okay so let's see if it's gonna be empty so it's so that it doesn't say that the head could be empty okay so i would say that would be the last case so if hat is equal to a non-pointer then we is equal to a non-pointer then we is equal to a non-pointer then we just return a none pointer for it otherwise we have a hash map from node to node so this is i'll say node map as a new hash map okay and um so let's say editor node it here is equal to head well uh is not equal to none we are going to say all right so um so node copy is equal to newnode ether dot value and we set uh is equal to so we first initialize it um but we need to set the next node so what if we don't set the next node here but instead we set the node map in the next pass so i will say node map.put this is the editor and the copy and next time it raises you could have again and well editor is not equal to none um we are going to say okay um node map dot uh now the copy is equal to node not talking to uh either all right uh this should be enter is equal to next and then we are going to say okay next is equal to node map so know the map dot get entered on next copy dot uh random is equal to node map docket ether dot them okay so that finishes pretty much everything about copy so at the last we are going to return notemap.gethead notemap.gethead notemap.gethead this one it should have entered equal to eight or down next okay so copy random list node if hat is equal to none they return none so the next step after you're done with coding the next step is about testing so testing you go through time simple task case to explain how this piece is going to work and at the same time do some sending checking the logic and um if everything goes well then you can mention that you want to set up some other test cases to uh make sure it has good enough test coverage so let's take a look at this one we have first of all we initialize the node map and the unit is we do the one pass through the list and every time we copy the node so first of all we copy seven put it put the original node and the copy node into the map and it is equal to the next one which is 13 similarly we are going to copy 13 um and at the next time we will have we will we are doing another pass and um well it is not none we get a copy of the current node he said okay next point next node points to one and based on the hashmap we have the new copy of the one and we set it to we set the copy of seven next pointer of the copy seven to pointing to the copy one similarly we set the random pointer all right so i think it looks good to me let's give it a shot okay it looks good all right so everything looks good uh like i said there is another solution oh one solution but you need to do a separate pass like the third pass on the linked list but i'm just going not i'm just leaving it for you to implement so thanks for your time watching it if you find this video a bit helpful please uh subscribe to this channel um i'll see you next time thanks for watching
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
1,332
hey everybody this is larry this is day eight of the march lead code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom remove panoramic subsequence okay given only a's and b's could remove one parameter subsequence from s we turn the minimum steps to make it empty okay n is equal to a thousand so okay so my intuition here uh and i'm solving this live so if it's a little bit slow fast forward or whatever you need to do i feel like i always have to remind people to do it because a lot of people are just looking for just a solution and that's fine but uh that's not what i do here but anyway let's see right so for this problem oh wait subsequence not uh the subsequence makes it more interesting because initially i for some reason i read sub string or like um or just like uh what's it called there's so much terminology that sometimes i get confused but i meant just like contiguous like next to each other um but because i saw this example where okay you could go a b then it becomes a little bit more interesting maybe um and looking at that n is equal to thousand a couple of things come to my mind uh which in an interview maybe it's a little bit metal but um but i know that n squared is gonna be fast enough but you know now it is a little bit interesting that it's only a and b and these things so it also reminds me of a more competitive programming problem where maybe the answer is just something weird and by that i mean um like looking at this i would try to fake think about a way to maybe because without you know the my initial misreading of the problem where is the substring i would think about some sort of dynamic programming maybe some sort of n-cube dynamic maybe some sort of n-cube dynamic maybe some sort of n-cube dynamic programming something like that like a divide and conquer dynamic program or something like that i don't know right but given the n is zero the thousand and then i looked at this well that's not the this problem um so given that it is subsequence what can we do hmm okay can we do greedy right well the thing to notice is that and i don't know if this is an important fact but i'm you know this is a live problem so i'm just going for my thought process i think one thing that i noticed is that you know and this is maybe obvious but sometimes you have to put emphasis on it which is that um every character has to be removed once right and then the question is okay if every character has to remove one um how do we combine them in a defective way right um for instance well okay now i just think about something that's really dumb right which is that okay given that it only consists of letters a and b you can actually remove everything in two steps which is this kind of thing is the thing that i was talking about with respect to like i think this is like one of those annoying tricky problems and what i mean by that is that you can do everything in two moves because the first move will be remove all a's and then second move we return all b's right we move for b sorry and if you do that then there's gonna be at least two moves and also it's very easy to verify that a string of all a's and a string of all b's are paradrome if not then maybe pause the video and think about that um okay so now that we know the answer is two then the question is um okay how do we you know so two is the answer no matter what or like sorry 2 is the answer in the worst case no matter what and then the question is well what then now you can break it down to okay what would give me an end of 0 what would give me the answer of 1 and what would give me the ends of 2 right and then okay the answer is s is equal to i mean for an empty string is zero because then you know because you don't have to remove anything you're done so then the question is and then you know that everything else is returned too so then the question is how do we check if we can remove one right and then this is actually pretty simple in this case because if you can remove this in one step and you can remove everything in one step if it's a palindrome so you know and you can write this in however each way i'm just gonna write in a one-liner but a one-liner but a one-liner but um but feel free to kind of write it in you know a one line if statement this is technically different how you want to do it uh it jumped out right accounting is a little bit you know the complexity is a little bit tricky depending on your language and how you do it and whether you create an instant of another string uh otherwise but like you know even the most um like it's not that hard to write you know the two pointer version where um you know you have a pointer to the beginning you have one at the end you just kind of merge into the middle you're in a while loop that should be okay the enter is accepted cool uh and of course this is gonna be linear time because no matter what you have to look at the string and the like every count of the string and that's gonna be linear time in terms of space like i said you have two pointers to count the pound room this is very basic problem or you know you do what i do which is kind of maybe oven space depending on how the language uh the language implements it but you know i'm just kind of because i'm focusing on the explanation and hopefully the dot process uh and versus you know uh on all the details for now um remember of course like i said you should be able to up solve this at home by making it all one space but yeah um i don't think this problem is tricky oh sorry i don't think i have anything i mean this farm is tricky but i don't think i have anything tricky to explain after i know the solution like before like it's one of those trick problems where you know if you know the trick then actually it's duh uh if you didn't know the trick then you know and hopefully um you saw how i did it i got done you know went for different processes and maybe even a misreading um but yeah after you see all that you know after hopefully you know when you see my explanation or like my live explanation because i thought about this live uh you know now they're looking back i feel like i've solved this problem before but i still didn't recognize this off the bad because this is such a one-off the bad because this is such a one-off the bad because this is such a one-off right like if you memorize this problem um then you know like it's not a waste it's not a good use of my memory to memorize these problems so even though it feels familiar i don't remember the solution but that said um hopefully the way that i thought about it gave you some insight on how to solve this for yourself um cool that's all i have it's a fun silly problem but you know it's cute um probably not gonna see this in an interview or at least well maybe not by itself maybe you could see like two three problems in like a session and then do it or force it to do it because it's such a you know like it's such a weird interview question because it's like if i were to ask you this problem it's like either you know it or you don't and admit and i don't know how much it teaches me about you as a candidate so that's why i wouldn't give this problem but who knows anymore everyone asks a lot of questions a lot of interview questions that i disagree with so anyway that's all i have um stay safe stay cool uh you know stay healthy and to good mental health i'll see you tomorrow bye
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
146
okay so uh lead code practice time um this uh this is the last question for today uh there are two goals for this uh video the first one is to see uh how do you solve this problem and then we are going to put some code in and the second one is to see how to behave in a real interview given the question so let's get started remember the first thing is to always try to understand the problem if there is anything unclear to you please ask the question to the interviewer and also think about some edge cases which we need to take special care of in the next step so let's restore the problem so it's called design data structure that follows the constraints of a least recently used cache has which is lr cache so implement the error lru cash class liu cash so errol cash is if you um have some capacity and the least recently used item is going to be removed uh so that's essentially what an iou cache is so let's say it has a constructor which initialize the capacity of the uh cache so it's for sure to be positive which is both in bold font so it has a good api and if the key doesn't exist then it return -1 and it has a put api -1 and it has a put api -1 and it has a put api to update the key and value so if the key value exists let me try to update it otherwise you add a new keyword appearing to the cache so if the number of the keys exists exceeded exceeds the capacity from the operation that we evict the least recently is key so follow up so can you do get and put in a one-time complexity do get and put in a one-time complexity do get and put in a one-time complexity so of course we can yeah so there isn't too much to clarify i think pretty clear and also i don't think of any ash case at this moment because we have some pretty strong assumptions saying that the capacity is going to be positive for sure um and yeah i know so uh if the key doesn't exist then we return -1 okay so that those are very return -1 okay so that those are very return -1 okay so that those are very good assumptions uh we have so we don't have any ash cases at this moment yeah so uh let's think about the solution so the solution yeah so the solution is to have the hashmap to store so first of all we will define a doubly linked list so the double linked list the tail of the linked list is the least recently used key value and for the hashmap we are going to store the key to the corresponding node so when we so for the implementation of the get api you try to get the corresponding node based on the key from the hash map and then update the curs update the doubly linked list for the put same thing we are going to put the key and value into the hashmap and also update the double linked list so both are going to be 01 regarding the time complexity for the get and put operation so having said that let's do some coding so uh for coding part uh there first of all we need to define some uh member members so let's say this is the capacity and we also need to have the hashmap which is the integer to node this is let's just call it map um so we are going to define a class let's call it node and it has several different members the first one is a key of course and the second one is the value and it also has the previous the reference to the previous node and it also has the reference to the next note and then we have the public sorry public note we have the constructor here let's say key and the value this dot key is your key this dot value is equal to value all right so that's it for the node definition and we are also going to have the head of the uh link list here so in the constructor we are going to initialize the hashmap uh we are going to have the capacity is equal to ct okay and node is equal to uh the new uh sorry it's going sorry the hat should be a none pointer so for the get and the set for the get key i said first of all check if the hash map contains the corresponding thing so if mat dot contact not contains a key then simply we are just going to return -1 going to return -1 going to return -1 otherwise it means we have the corresponding node in the hashmap so that's the time uh we are going to say okay node.note is equal to um node.note is equal to um node.note is equal to um map.gas the key map.gas the key map.gas the key and uh we what we should do is uh we should first of all detach the node from the linked list then we are going to reattach it to the head of the linked list then we are going to return the uh we are going to return all the value okay so that is good and for the put um same thing so if a map dot contains the key so if it already contains the key um then it means uh we are going to just do some update for it so if it contains a key we are going to say okay uh no it is not equal to map gets the key all right so now that value is equal to updated to the value and then we are going to uh attach the node uh and re attach the node and then we just return it otherwise it means that we have already uh so otherwise it means that uh we don't already have the corresponding key and value uh in the hashmap so you're going to have the new node so new node is good new known as the key and value so we are going to put it into the hashmap that put as a key and the uh what is that this should be the node okay and we should also attach the node so the thing currently is we also need to check if the size of the map is larger than capacity if my dot size is larger than the capacity then that's the time we are going to do something to remove one node so we are going to detach the uh prev the which is the tail node the least recently used node and we are going to a um so okay so maybe um let's say node remove node is equal to head dot pre so we are going to do that and then dots remove the remove node key yes so that's it uh so we detach and then attach so first of all we attach the node to the head and then we detach the last one i think it should be okay so the next thing for us to do is to implement some helper function so okay the detergent attached so private boy the detach and the private void attach um yep so this is the node and node this is a node okay yeah so if i attach it then it means we need to put it as a head node so if um head is equal to some none pointer then you're going to say head node.next is equal to uh node.next is equal to uh node.next is equal to uh node and node so it's like self-reference self-reference self-reference is equal note it's like a self single note circle so we are going to say all right had is equal to note now and we just return otherwise it means it's not the head is not equal to none so you're going to say head dot next equal to head and note dot brave is equal to had.pray and then no had that spread that next is equal node and the head that's brief is equal node as well so we are going to set head as equal note all right so this attach and then the next thing is about detach how to detach the node from uh from it so um so how they detach so the thing is if um so uh is it possible that we detach something uh i don't think it's possible if the head is called none then it detects something so if uh okay so if um node dot next is equal to node so if there is only one node within the double linked list that means um we just had set had as equal to the num pointer otherwise and then we just need to return otherwise we will have node dot spray down next is equal to node.next and note equal to node.next and note equal to node.next and note that next the parade is equal to node.3 is equal to node.3 is equal to node.3 so that's how to detach the note from the length last uh yeah so that's it and also we need to say hey um node is equal to head there you have know that next hat is equal to node.next otherwise it's going to cause node.next otherwise it's going to cause node.next otherwise it's going to cause some problem um yeah so i think that should be it so remember the last thing is about testing so um usually we will go through um some test cases manually uh to do sanity check and at the same time explain how this piece of code is gonna work uh but uh since uh we don't have enough time for this uh i would just uh using my pure eye to explore the correctness of the code so let's see so first of all we are going to initialize the hashmap so this is a cap capacity and then highlights so when we try to detach it uh if it is just a single note circle then we are just going to set head is equal to none then return it otherwise if it is equal to a hat the height is equal to node.next the height is equal to node.next the height is equal to node.next yep and uh now we are going to how did we are going to set know the free down next is going to know next now down next up pretty basically not afraid okay so that's how they detach a node from the linked list and uh see how to attach it into to the head so if head is none they get a self redirecting node and the set has a secret node the return so otherwise uh we are going to have no down axis had no the previous had approved no dot prive dot next is equal node and the prey had dodged had a previous equal to note okay this looks fair um so we have the get and the foot so we have so when we get first of all we see if it contains if not contain return minus one otherwise we get the node from it detach it and attach to the head then we return node dots value sounds fair so for the put we will see if it contains let me just get the corresponding thing updated and then detach and attach and then return otherwise we are going to have a new node and we are going to attach it and then we are going to put it if the size is larger than the capacity uh then we have to find the tail node and detach it and then remove from the map all right all sounds fair let's give it a shot okay it's accepted yeah so you can see this is my second version of my implementation yeah so for my first version i actually made a stupid mistake and i spent quite some time to debug where to code it where the bug is so i'll tell you where the my previous block was so it was here uh so i didn't set the node uh i in the detach function if node is either had i didn't set reset the head so if i don't reset the head then it is going to cause some serious problem because uh the attack the attach means we are trying to attach the node to be the previous head and then um yeah and it causes a series of the issues but glad i caught that bug and then i redo this video so that's it for this question coding question uh if you have any question about this coding puzzle please give me leave some comments if you find this video a bit helpful please give me a like and i'll see you next time thanks for watching
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
684
welcome to midnight coding everyone today we'll solve lead code question 684 redundant connection this is a graph problem and we'll be using union find algorithm to solve this problem but before we continue please like this video and subscribe to the channel as it will provide you with all the luck you need on your upcoming job interview so if you are planning on getting into any of the fan companies or if you have an upcoming interview if you like this video i promise you will get the offer and also it encourages me to keep making educational videos like this is a medium difficulty problem but before we continue with our explanation and coding it up i want to go over the concept and explain to you guys how exactly union find is helpful in this situation and how we can optimize union find so let's jump into the explanation now let's think about how union find or disjoint set with rank works in the beginning all the notes are going to have rank of one and when we connect two notes it doesn't really matter which one is gonna become the parent note or the root note so let's just say that i'm going to make this one the parent note so this one is the parent note and since we have made that one the parent note let's update the right so the rank of this one is going to be two and this one is it's child note and this is the parent note now so now when we connect this note over here with this note over here now we ask what's the parent of this note so we can go up and we can see that the parent node of one this one over here is two this red one and we're going to check the rank so the rank of this is two and the rank of this one is one and we're gonna do the same thing with um this node over here two and we're gonna try to find its parent node and how do we do that well we know that this note is the parent of itself because of this connection so we can just imagine that all the notes starting out they're going to be their own parents so now after we have done all that we know that the parent of this node is this 2 as well and we can just keep the rank as is so let's do the same thing with the second half of this graph so let's connect these two and let's make its rank 2 and let's connect these two and now what if you wanted to connect this one and this one so if you wanted to make a connection between these two first of all we're gonna find its parent so we're gonna go up and we found its parent is two and then we're going to go up again and this node's parent has a rank of two as well so as i said again if they're equals it doesn't really matter uh we can just connect these two like that and then we can make the parent of this set to be this node and then we will just update its rank as well so to do these operations we need two functions we need a function called find and we know the function called union hence called union find basically what happens is that you have two nodes so this union function takes two arguments so it takes note one and note two and this find function just takes one argument which is known find goes to this node makes itself up to the parent node and union just tries to connect two nodes together and here's what's so nice about union find our disjoint set is that for example if there was three nodes we're gonna call union on these two nodes and we're gonna try to find its parent right let's just say for this example they were their own parents that's fine and we're gonna do the same thing for this two note and the parent is going to be this one over here and now if we try to connect these two nodes we're going to call our find function over here on this note and on this node as well but their parent is the same node that means there's a cycle in this graph so once we find the cycle we can just return true and we can just return the index or the value of these two nodes so that's basically how we're going to use union find to solve this problem now let's think about what path compression is okay so let's just say that we're looking at this note right here we called our union function on two nodes and let's just say this node over here happens to be this node over here so its value is x so the parent of x is y but that's actually not true because the parent of x is actually this one over here let's call it node c so we're gonna say if x is parent equal to parent of x because remember this root note is going to point to itself making it's the root note so when we go from x to y does not equal to its parent so we're gonna make this is the current parent and the parent of this also does not equal to this note over here so we're gonna make our way up and up until we find the parent or root note but in this example you can see that we're going one by one and we don't have to do that we can do what's called path compression basically what we're gonna say is that parent of x this one over here is currently this one but we're gonna say parent of x is equal to parent of x right now is this not over here so this notes parent meaning this one over here so we're making our progression faster by doing path compression so here's a picture i found from geeks4geeks and visually it looks way better than what i just drew so i'm just going to use this picture so as you can see the initial note or the root note is 9 over here and these are all of its children nodes basically what path compression does is that it turns this structure over here and makes it like this so next time we have to access this three over here so if this three wanted to go up this can just go up instead of going from here to here into here so instead of doing that it just makes it a really short path to follow so that's just basically what path compression is it's a really nice optimization technique and it's going to lower our time complexity now let's jump into the coding all right before we actually jump into the coding i want to talk about how we are actually going to initialize the parent and the rank variables that we're going to create so in the beginning we want to make sure that a node points to itself so this node's root will be itself so we need that information to begin with and how can we do that right so all the information we've given is the edges for example this node has an h2 here and this node has an h to here so what we're basically given is x y and x c and the length of our input is 2 but as you can see there are three nodes and when we initialize basically what we're going to say is that we're going to take the length of our edges the input variable we get and then we're just going to add one node to account for all the other nodes because if we don't we'll be missing out one node so after that when we get this we're basically gonna say so this node it points to itself this node points to itself and we can do the same thing for rank so the rank of this note is going to be one and one here as well and one here again so that's how we're going to initialize our parent and rank variables so in python we're just gonna use a dictionary and in go we're just going to use an array to represent this relationship and the next thing i want to talk about is the time complexity so just to find function itself it would be o of n however since we're using path compression we can say that the time complexity is o log of n so union on the other hand since we're using rank over here let's just say that in theory the operation should take log of n time because we are using path compression to use find but the time complexity of disjoint set using path compression and rank together the two optimization techniques it actually comes down to o of amortized n and that's the worst time complexity so with that being said now let's go into the coding so here's the solution to the problem in go so as compared to our python solution our go solution is going to be a little bit more lengthy and that's just one advantage python has over all other languages because it's just so easy to write even so in go it's not going to be difficult anyways what we're going to do right now is that we're going to create a struct called union find or disjoint set so let's call it type disjoint set and it's gonna be estra and our struct is going to consist of three things parent and rank and the number of components so we need the parent because we obviously need to know which disjoint set goes into which disjoint set and we need a rank because we are utilizing this technique called path compression as we discussed in our drawing explanation and we need n to know how many components there are within our graph so now that's done now we are going to define our functions find and union so function find is going to receive a note and that's going to be of integer and it's going to return an integer as well so here is how we're going to do our path compression while uh in go it's four and one thing we forgot to do is that we're gonna have to uh define this u variable over here because uh we are going to be uh using this our disjoint set struct so uh we'll be using this u variable and it's gonna be this joint set so while u dot parent of n does not equal to n itself meaning that if it's not the parent of itself then we're gonna do a path compression which is now that u dot parent n is going to be u dot parent n you dot parent off you don't parent uh of n so that's basically what the path compression is what's happening is that so n is probably connected to other nodes and then we're gonna say is that the parent of n is the parent of n so we're basically shortening the path so next time we iterate we have shorter distance so now we're just gonna say this n is going to equal to u dot parent of n and if we found the root of this node n then we can just return the parent of n and now we need to do the union function so for union uh we are receiving two inputs we're receiving uh one note and two known and it's going to return a boolean value because we know that as soon as we find a cycle in this graph that's the answer we want to return what we're going to say is that n1 root and n2 root is going to equal to u dot find n1 and you don't find n2 for that matter and then what we're gonna say is that if n1 root equals n2 root then we know that there's a cycle in this graph so it's going to return false um the reason why we return false is this so in our main function find redundant connection what we're going to say is that we're first of all we're going to initialize our disjoint set so our destroying set is going to be this joint set uh and let's give it in the length of edges plus one and then what we're gonna say is that for i is zero and i is less than uh less than the length edges and i plus what we're gonna say is that if edges at i and if the zero disjoint set dot union with so we're gonna union edges i zero and i1 if this is false then we're just gonna return an array of these two elements and based on the description we're guaranteed that we're gonna get an answer at least an answer but if we just leave it like that go it's not gonna like it so we're just gonna have to return an empty array like this although it's not gonna get executed so that's why we are saying if n1 root and n2 root of equals this is false so what happens if this is not false so now uh now we're gonna use our rank to determine which disjoint set this uh another disjoint set goes so we're gonna say if u dot rank of n1 root if this is greater than n2 roots rand then the rank then the parent of n2 root is going to be n1 root so if this is the case then u the parent of n2 root it's going to equal to in one root else if it's the other way around then we're just going to switch it up and then we're going to say that the parent of n1 root is into root and we have another condition which is else that's if these two are equals they're equals like it doesn't really matter which one uh it's gonna have a higher rank i'm just gonna say that n1 is going to have higher rank and then we can update the rank of n1 root plus equals one so next time it comes uh n1 root is going to have higher ranking than an and two root okay so that's basically it now we just need to construct our disjoint set so over here i'm going to define a variable called uh construct disjoint set and it's going to receive the number of components and then it's going to return disjoint set so parent and rank they are going to be uh an array of integers uh with the length of n that we give it to uh so that this that n is the length of edges plus one we went over y length of edges plus one in our drawing explanation so you can go back and check y and rank is also going to be the same so we're gonna do for i so i is gonna be zero and while i is less than n and then i plus we're going to say parent at this index is going to equal itself and rank at this index is going to equal 2 1 because all the nodes is going to have initial rank of one and at the end we can just return at this joint set of parent is going to equal to parent rank is going to be rank and n is going to be n so that's basically it for defining uh and using this join set to solve this problem now let's run it to see if it works uh sorry but that we don't need uh commas in here when we're defining struct now let's see if it works oh we need to close our union function over here now let's run it again oh and then um because since we're returning false here and it looks it's expecting us to return a boolean we're going to return true over here all right now it runs now let's submit it and yes it works so that's basically the whole intuition of using this joint set to solve this problem so if you've made this far into the video thank you so much for watching and if you liked it please like the video and subscribe for eternal luck and i hope you guys learned something new today and if you guys have any questions any lego questions that you want me to cover please leave a message in the comment section and i'll try to get it done as soon as i can so i'll see you guys in the next one
Redundant Connection
redundant-connection
In this problem, a tree is an **undirected graph** that is connected and has no cycles. You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. The graph is represented as an array `edges` of length `n` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the graph. Return _an edge that can be removed so that the resulting graph is a tree of_ `n` _nodes_. If there are multiple answers, return the answer that occurs last in the input. **Example 1:** **Input:** edges = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** \[2,3\] **Example 2:** **Input:** edges = \[\[1,2\],\[2,3\],\[3,4\],\[1,4\],\[1,5\]\] **Output:** \[1,4\] **Constraints:** * `n == edges.length` * `3 <= n <= 1000` * `edges[i].length == 2` * `1 <= ai < bi <= edges.length` * `ai != bi` * There are no repeated edges. * The given graph is connected.
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
685,721,2246
1,248
hello fans today I'm gonna talk about new decoded trail for a two car number oh nice Subway's the problem that came an array of integers none and you need your K a subway he's caught on ice if they are K or the numbers on it between a number of last several ways no Kevin Jews Emperor why is that there are five numbers K you were three I was returned to which he that has some ways to service that has all the other numbers equals three so there are a lot nicer ways for the second example we have we can find any nice sub array because they are all human and for this sort example there are sitting nice sub arrays so we can sing about first the idea is that we can use the Bluetooth was two loops find all the subways here hmm and then during that then during the second loop we were kind of harmony or numbers that has cleaner birds this algorithm takes Oh and few times of course we can organise you - Oh n square course we can organise you - Oh n square course we can organise you - Oh n square times uses which is a second method based on the sir I do like the pre some idea if you have for me now is prism actually a week we can call it a pig hunt and for you food for subway I to tell us what no number all the you go to the I okay if we pass one in for the number J is odd if it's not or if it's not on dollar odd there will be the same it was not all there will be the same control and I J in Phenom sure it's even and this is no takers om and so a time is actually this problem is way also we had caused time limit in the sacred because and you could file times 10 power 4 and so where we take 25 times 10 power 8 this week all the time and image a new city generally if it's about hemp house 8 or 10 power 7 this is public they will have no time limit exceeded problem here so the first sort of problem that is we can use ideal that is based on two pointers so the idea is that for example here we have they have it already about a 2 to 1 to 4 is here and the K equals 2 and we can carry that to your the trapunto whines air the other is out and there are counter and kind or counter so far and we have the subway Hunt's subway nice subway not serious number over here for first away my son yo you put 0 and equal to zero as well and we will see that you will have a subway for example run here and here if this is a sample of a there is nice then we will find that it has a tail you go to right and then we will I need to shift this Punto expect only beat so we were shipping out to AMA and then can you to check whether there is the audience your 2 to the order is not true so we worship over this okay adios we are two so against we so far right and when there were here she shifted a oh here only Hawai element that is necessary ok you go to so we will increase the increase our here so you kind of there are two numbers over here mm-hmm it's are two numbers over here mm-hmm it's are two numbers over here mm-hmm it's numbers because it when I'm was has order you were two as well so we are there may be achieved again with one hmm and can you know so well answer it would like plasma and pare away and we go here to here shifter memories shifted by 0.04 to here shifter memories shifted by 0.04 to here shifter memories shifted by 0.04 while here pattern actually with the lambo countries one butter we have all answers from what from the periods are out here so we need to pass a while again so in this is a trigger part of this that we need to detect to Canada you call the Pew is reliable and certain eyes have a Vietnam people a Sarah is 1 here so applause well here any time if we see any time if the current number is all the way we are said the Knights have not equal zero so then that's basically together the numbers here so first of I equal 0 and yeah are you gonna do yeah you could zero here and the Cantor you go to other country you could do and not country you could do and a second here cos 0 and I do 100 0 is 0 and I see and sovereign number is 1 and we have answers here answer sulphides 0 5 0 and here is y 0 and y equal to and we care a counter or equal to 1 and not some is your 0 and kindest your 0 for the force here because the Cantor number is 1 we will continue to move the right apprentice my point was should be sweet hmm 300 equal to and then the sauce not sub-arrays with Joe mmm sauce not sub-arrays with Joe mmm sauce not sub-arrays with Joe mmm scientists a row as long as this is co-author we will assign the line subway co-author we will assign the line subway co-author we will assign the line subway service number zero hopefully this is a kind not a service of kiona not subway for the kind innovation and here is the studio it's you didn't say we need to live how was the shiver left back because the kinda boy is our number is a 2 over here but our number 2 is just which is equal to k so where is she oh yeah equal to Y over here and because the last number you secret oh wow this because it's our language to then I wish here is the last number shift air you could have one key and get a nice number equal to again yeah his analysis in this tool and so on I was just too so we shifted or okay yeah okay yes we know the kind of this only this one element and the mass number is equal to 3 here because the overall number is already change it will be 1 because the only you will manage the previous to shift 1 so you watch so we are allocated a while loop and pass the nice table number is 3 so answer it should be sweet and then which paneer the shifter cable ship only 4 and which we found that I found this number is 2 again 1 plus u 2 again you know you two again yeah wait this the nice type of it is sofa is zero and here so range to where we are used while oppa so maybe she left again for so this is kind the body while number over here so and can't count Auto counters become wow and nice number has increased the one because previously should be increased oh and here also here we should four plus one again and when you put a tool should be the shifted for file and although hunter also still while now some nice oblong with one here we have to add one is fine here's this chick apartheid a nice acronym we should be there should be no since 1 or 0 should be cable same as this person's previous table because for although for all the you a number the period is we can the answers again you were here I was four okay and they will help with this also answer and since again and all this will be sub away okay so it's nice suburban avoid should be you could be increased should it be capable the same so every time we pass one to the answers so basically this is a code logical here photo J and should be left Pentos and I should really uh very pentose million changes here so I mean integrated way is all numbers we all increase the work on and initialize it with you a number was we wait cable the previous and last cyber numbers and then when or now is equal okay we will use a while loop to analyze Sapna was plasma and she for the left pointers to write him one step more and decrease the ordinal or controversial kind of embodies it's all numbers and their way every time we personalize some numbers there we are killed answers so basically this idea of the how the code yeah this is one okay this code what's because I have all day I write so talented candidates all go huh you know something you all again there should walk oh they shouldn't be though ow okay yeah we made it thank you for watching
Count Number of Nice Subarrays
binary-tree-coloring-game
Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it. Return _the number of **nice** sub-arrays_. **Example 1:** **Input:** nums = \[1,1,2,1,1\], k = 3 **Output:** 2 **Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] and \[1,2,1,1\]. **Example 2:** **Input:** nums = \[2,4,6\], k = 1 **Output:** 0 **Explanation:** There is no odd numbers in the array. **Example 3:** **Input:** nums = \[2,2,2,1,2,2,1,2,2,2\], k = 2 **Output:** 16 **Constraints:** * `1 <= nums.length <= 50000` * `1 <= nums[i] <= 10^5` * `1 <= k <= nums.length`
The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?
Tree,Depth-First Search,Binary Tree
Medium
null
201
hello everyone this is sham saari and I welcome you again in the new video of our YouTube channel so this is a lead code problem which was asked on 21st of February and the problem is medium so pit wise and of numbers range so they have given two integers left and right that represent range left right left to right and we need to return the bitwise add of all numbers in this range inclusive including left and right so left equal to 5 and right equals to 7 so the bitwise or bitwise end of this range will be four uh then bitwise and of from left to from left equals to Z to right r equal to Z bitwise and will be zero so left equals to 1 and right equals to this so the bitwise end of this operation will be zero so how to solve this type of problem let's discuss the approach so first of all we will initialize a variable count to count the number of right shifts needed to make left and right equal so that's the basically that's the approach so if we will initialize a variable count and count the number of right shifts needed to make the left and right equal and after that while left is not equal to right the right shift both left and right by one bit so here we in this inside the file look while left is not equal to right then we will do what we will do right shift both left and right by one bit and increment the count after each right shift operation and after the loop left shift left y count bits and return the result and after the loop here the left shift left by count bits and that will be the result overall result that's the approach here to solve this type of problem so let's C this solution before that if you are new to the channel hit the like button and subscribe for more content so first of all we will do we will create account variable and initialize it to zero and why left is not equal to right so we will do what we will left shift uh we will WR right shift left to one and right shift right to one and increment the count and if and we will return if left of Le shift of count and what is the value of that we will return here uh we will left shift the left by count times so that will be the answer that's the only solution let's look at the overall solution yeah the test cases run successfully let's submit the code yeah all the hidden test cases done successfully so here the overall time complexity will be biger off log of minimum of left or right so what is the minimum of left of right left or right value and log of that will be the time complexity here so and the space complexity will be big of one as we are not using any container so that's it if you enjoyed this video or found it helpful don't forget to hit the like button and subscribe for more content and also stay tuned for upcoming lad code problem of the day videos and exciting monack web development projects happy coding and let's make this year a fantastic one together thank you
Bitwise AND of Numbers Range
bitwise-and-of-numbers-range
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_. **Example 1:** **Input:** left = 5, right = 7 **Output:** 4 **Example 2:** **Input:** left = 0, right = 0 **Output:** 0 **Example 3:** **Input:** left = 1, right = 2147483647 **Output:** 0 **Constraints:** * `0 <= left <= right <= 231 - 1`
null
Bit Manipulation
Medium
null
1,696
hello everyone so in this video we are going to solve a question complete code it is jump game 6 this is 1696 question read code and this comes under medium category all right so let's start with the problem statement you are given and zero indexed integer l in nums and in integer k you are initially standing at index zero right we are standing at index zero initially and in one move you can jump at most k step right so we can jump any number of steps ranging from one to k right so we are basically given at most k step all right so like without going outside the boundaries of there so like this is the range of the k jump and you want to reach to the last index of the array and your score is the sum of all the numbers day for each j you visit in the array and at the end you need to return the maximum score you can get right and then we need to return the maximum score we can get let's see through an example so this is our first example let's just pop it from here and let's move toward this tech body so let's see this is our example right this is another example so in this example what we can do is we can jump for few steps right we have k equal to 2 here and we have k equal to 2 so for this k equal to 2 what we can do is we can make at most two jumps right we can make at most two jumps so we can make one jump or two jumps these are two possibilities we have right so let's see we can either jump one step here or two steps here right we have two possibilities here so let's see all the possibilities so basically we will be making a tree to see all the possibilities here right so let's make a tree here so there are two possibilities for this index right either it can go to -1 or index right either it can go to -1 or index right either it can go to -1 or minus 2 so if we go to minus 1 the updated sum would be 1 plus minus 1 right so this will become 0 and the whole array will remain same 0 minus 2 4 minus 7 and 3 right and similarly for minus 2 this 1 plus minus 2 is equal to minus 1 and the whole array will remain same so four minus seven and three right now let's see the possibilities for these right the possibilities for these are again two right again two possibilities it can either jump to this or this to this height so if we jump to minus 2 and if we jump to minus 4 so let's see if we jump to minus 2 we will get 0 plus minus 2 is equal to say minus 2 4 will remain same this is same right and if we jump to four so the updated array would be four minus seven and three right and in this again we have two consolidated minus one and four right not minus one and four it should be four and minus seven right so four and minus seven now let's see the combination so in this we have um this will become three minus seven and three right and in this it becomes minus one plus minus seven it is equal to minus eight and three will remain as it is right now let's see for the cases right so this will become the here we have two possibilities right you can go to here or here right so we have four and minus seven right so if we go to 4 we will get 4 minus 2 is equal to 2 minus 7 and 3 right and if we go to minus 7 we will get minus 9 right minus 9 and three will remain as it is right similarly for this we have two possibilities there is minus seven and three so for minus seven we will get minus three and 3 right and this 4 plus 3 is equal to 7 right this is 7 and for this 3 minus 3 and 3 we will have total answer is equal to 0 right and for this 9 minus 9 and three we have equal to minus six and here we have two possibilities so this will become uh minus seven and three right so the answer will come out to be um minus 7 and 2 so this is equal to minus 5 and 3 and this is 5 right and this is minus 2 right so we have till now got minus 2 5 6 0 and 7 right now let's see for this remaining one right so for this remaining vl we have eight and three so this eight and three will become five right this will be a minus five and for this will again have two possibilities right that is minus seven and three so for minus seven we will get minus four and three let's end this for three we get six and this four and three we get minus one so now we have checked for all the possibilities right we have checked for all the possibilities and the answer we got is this one right these are all the possibilities so you can easily see the maximum out of these answer is 7 right so we are returning 7 in this case so this is the first example right and this is a recursive tree just formed after all the possible combinations right so the total number of combinations we get is equal to k to the power n right and we just need to you know iterate recursively k to the power n times so if we try to memorize in the dp so it will just reduce to k 2 k into 10 right but this solution is also not accepted on delete code right so let's see optimized approach to solve this question which will reduce the time complexity to beco of n right currently the time complexity is because e to the power and then we reduce 2k to the power 9 in the dp memorization and now let's see the approach of dq to further reduce this time complexity to beco of n right so let's see so let me just copy the same example from here right let's take this example here right let's take this here all right now let's take let me just write the indexes of this is 0 this is 1 this is 2 this is 3 this is 4 and this is 5 right and what we will do we will make a dq here right so let's make a dq so we are making a dq here and let's initially store a zero index here right let's initially store a 0 index here and we have k equal to 2 right we have k equal to 2 in this example so let's see how can we approach this question right so we have already taken 0 and we are basically storing the indexes in this dq right we are storing the indexes in this dq right now let's see we initially stored 0 and let's see all the combinations for the remaining array right so we'll start with this index that is minus 1 right so let's find out the sum for this so 1 plus minus 1 is equal to 0 right 1 plus minus 1 is equal to 0 so what we will do we will just push this button index into this dq because we just iterated through this right now right and let's see whether the left elements right which we just iterated just now or we just already created the values whether these are smaller than zero or not if this is smaller than 0 then we don't have any use of this because we need to find out the maximum one and we need to find out the maximum so we don't need the lesser value but in this case 1 is greater than zero so let's keep this value because it must be needed afterwards right so let's see for the next case right so we just taken this minus one now let's take minus two here right so let's take minus two so let's update minus two with the maximum out of this right the maximum out of this is zero and one so out of this maximum one is one so let's update minus one plus one is equal to minus 1 right minus 2 plus 1 is equal to minus 1 and let's see whether the left elements are less or not no they are not lesser these are greater than minus 1 so let's keep it as it is and let's um push 2 into the dq right now we are at 3 so now we are when we are at 3 we basically are checking the k indexes because let's you can also assume this as a sliding window approach because we are maintaining a window of k size right so whenever we will come to three so we will just check the two elements or we can say the k elements so this one is extra right this element is extra so we will just pop out this from here right we will just pop out zero from here and let's see for these two values right and you can also observe one more thing that this one the front element of the dq is always the greater one right this is the index so the value of this index is zero so this is always the greater out of all the values of the dq right so let's see for another case that is four so let's add four with the greater one that is zero so let's add zero here right and what we can do is we can just push this 3 into this dq right let's push this 3 into this eq and let's check this should be this is 0 plus 4 is equal to 4 right so let's see whether the elements on the left side is greater than or less than right so in this case the elements are lesser than 4 right so we don't need it anymore let's just pop it out from here we are just popped out these elements from the dq let's just pop out these elements from dq and we have three on the front now so you can see that this is a maximum one which is kept at front right now let's move further so now we have minus seven so when we have minus seven let's add 4 into this minus 7 so 4 plus minus 7 that is equal to minus 3 right and let's also see whether the left one has greater than or smaller than or not so they are not a smaller let's keep it as it is let's move forward and let's push this four here right now let's see for this one the fifth index right for the fifth index we have three let's add the maximum out of them so 4 is the maximum right so let's add 4 plus 3 is equal to 7 right 4 plus 3 is equal to 7 so let's check the previous values there is smaller than 7 let's just remove it and also remove from the queue and let's push this fifth index right so whichever index we are just processing we are just pushing it into our key so we have just completed the iteration right we've just completed an iteration and at the end we have one element into our dq that is five so let's just return the fifth index value so the value of fifth index is seven so our answer is 7 right so this is our answer and we have just iterated the whole array once so the time complexity right the time complexity in this case is big o of n and space complexity is becau of n because at most we are just storing n elements into this d right so i hope the approach is creative if you still have enough in this approach feel free to comment down let's move to the coding part all right so let's make a dq here so dq of integers let's name it dq and initially let's push zero into this dq right and let's run a for loop from first index to the last index or num start size and i plus right now let's check let's see what we were checking first we are checking the size of this window it is k window right we are just checking whether the k elements are there or not so how can we check this we have the value of i right and we have the value of k right and also we have the value of this dq right or we can say we have this index so we are just basically checking from the front let's see so let's see we have we are checking that this dq dot front right this dq dot front whether this dq dot front eq dot front is less than this less than i minus k it is i minus k if dq dot front is i less than i minus k we will just pop it out from here right so if dq dot front the q dot front is less than i minus k right is less than then what we can do is we can just pop out from here right so um dq dot pop front right so this should work fine let's turn it into a while loop so if there might be multiple cases so this while loop will handle right now let's update our nums of i right we are we were just updating this nums of i right we were just updating this nums of i with the sum right you were just updating this number i with the sum which was greater so the greater one was always at the front one right so let's update with the front value right so numbers of i plus is equal to dq dot front and since this is storing index so we are just keeping this into our nums all right so this is fine right now also check whether this like the previous left elements are lesser or not right so if let's also run a while loop again so the while loop will run till the ego dot um dq dot let's write empty right let's write empty here while dq dot empty until unless not empty and also check whether this dq dot back right this dq dot back and they should be indexed so numbs of the q dot back is less than equal to nums of highlight we are basically checking whether the previous elements are lesser known if they are lesser than we don't need it anymore let's just remove it from here so dp this should be dq right pq dot um pop back and this while loop will just remove all the lesser element right and let's add our current index into the dq so dq dot push back right and let's return the answer from here so return numbers of islam right we are just returning the last index of this nems array because this is storing the maximum value right so let's just run this yes working fine so let's just sum this yeah it's working fine so let's calculate the time and space complexity so the time complexity is big o of we write it here time complexity is because n because we are just traversing through all the n elements like we have already seen it here we just severed through all the n elements only once right only once that is the time complexity is big o of n and the space complexity is we go off and because we have stored at most n elements into this dq right so i hope the approach and solution is clear to you if you still have any doubt in this question so feel free to comment down please like this video and subscribe to our channel i will see you in the next video you
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
54
hi everyone welcome back to this channel I hope you guys are doing well today we are going to solve one of the famous lead chord problems spiral Matrix in this problem we have one mn2 and Matrix and we need to retrieve all the elements in spiral order for example for this Matrix we need to travel like this from this cell to this and again 2 to 3 and then three to six and this way all the way to 5. this problem can be solved in multiple ways but we are going to solve it using one of the graph traversal technique DFS or depth first search generally when we perform DFS on normal grade we are allowed to move either in four direction or eight direction for example suppose we have a cell we can go to right side we can go to down we can go to left side and we can go to ok I'll just name it but here we need to Traverse in One Direction till we reach the boundary for example we start from here and we go only in the right direction and from this cell only in the right direction but from this cell since we cannot go to the right direction obviously it will go out of grid so here we need to change the direction to downwards now interpret this with this four directional moves for example initially we only moved this direction and when we no longer able to move in the right direction we change the direction to down okay from here again will be going down now from here 9 again we cannot go further down since it will go out of boundary so we'll change the direction to left so here we went in down Direction till we can then we had to change the direction to left side okay so we have to Circle those Direction in other words we'll be going right direction till we can then we'll be changing the direction to down and then down to left and then left to upside and again upside to right okay so we'll be going like this and from here to here now from here we can go upset okay but we already visited that cell we cannot go in the up Direction so we must have to go to the right direction now we need a way to find out whether we can move in the same direction or we need to change the direction okay and we can do this either by maintaining a visited array or we'll change the cell value to some other value too so that this cell is visited now let's jump over to the code I'll be writing my solution in C plus but you can easily write in your own preferred programming languages okay so that should not be an issue first of all I'll write the directions for movement so we'll be going right direction first so in right direction or x coordinate or I coordinate will not be changing and in the downward Direction ith value will increase by 1 and then left and then up similarly will be defined for y direction it will be 1 0 minus 1 and then again 0. so our Direction right down left up okay some prefer to write in pairs but that's okay also I'll declare two variables for dimension of our Matrix now let's define our DFS function so in this we would be needing our cell position our current cell position that is I and J in the direction and the direction means we'll take direction as an integer and if this value is 0 meaning we are moving in the right side if this Dr value is 1 then we are moving in the downward Direction and so on and then obviously we will be needing our actual Matrix and one more Vector we need to store The Matrix elements let's call it answer now when should we stop reversing when we visited all the Matrix elements and how can we identify that we can easily identify the Matrix contains M into M elements so after visiting all the elements the size of our answer Vector will be exactly M into n that will be our base condition if size of our answer is m in 10 just return from here okay now we'll collect the current cell value so that puts back Matrix I into J now I have taken the value of cell I comma J we need to mark this cell as visited so that we do not visit it again for that we already discussed about either you can maintain a visited array or we can change the cell value to something else if we seen the problem or Matrix cell value is ranging from minus 100 to 100 okay so we can mark it with something big like 10 to the power 9 now we need to check if we can move into the next cell in the same direction or we need to change the direction okay so we'll change direction okay so we'll be giving the position of the next cell dir and same for the jet coordinate don't worry I will implement this function in a second when we will be changing the direction when this the next cell is invalid meaning either we are going out of bounds or the cell is already visited in those cases we'll be changing the direction so our new direction will be why we did it in this way because suppose we are moving in the upward and now we need to change the direction and so we'll be going in the right direction but here the index will be 3. if we just add one more into the direction it will go out of bounds and that does not make any sense so we need to modulo this with the length of this direction Vector so that it will give us next correct direction which is right in this case okay and then we'll make the call for next cell and that will be DFS and coordinate of our next cell will be I plus d i comma d i r comma dir or Direction and then Matrix vector and then answer okay now let's implement this change direction this will be our Boolean function Jackson and we just need cell so let's see the cases where our cell will be invalid negative index or it I is greater than equal to m or J is less than 0 n and one final is Matrix a cell is already visited so I comma J equal to this one we set this value to Market that the cell is visited so in these cases we need to change the direction okay let's finally Define our spiral order function so we need to determine the order of this Matrix M will be similarly in the cell number of columns okay now we need a vector to store our cell values let's call it answer again and let's make a call to DFS function so we'll start with the zero comma 0 and our initial direction will also be 0 and the norm Matrix and then our answer array and then finally written our answer let's run this code compiler error oh obviously the past the Matrix also so we'll just Matrix now send it again everything looks fine let's submit it our code did well in the time complexity since we are visiting every cell once so time complexity will be number of cell that is M into m as always thank you for watching this video please do like this video And subscribe to this channel
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
44
so in this video we are going to solve wired card matching problem so suppose if you have been given one string and you also have the pattern so you have to say according to this pattern this string is matching or not so if you see here suppose a string is SS and pattern is a so it will not match right so if you see here this is the a and here is a on a so this a b match with this a but this complete is not matching so I can say this is the false right another case if you see here but suppose if this is the history and if this is your pattern a also so you can say that you string a pattern matching so you can say that true take another example it is very easy right this is string compression the thing here is the pattern but in the pattern we have the two very unique character one is the aesthetic and one is the question mark obviously present the any character but only one character and that should not be empty so in this case if you see if your string is a b and pattern is question mark and B it is true because here question mark can represent as a and then of course this B is B matching right so in this case if this is the this one so if this is the string and this is the pattern so of course b match with b and a question mark represent any character right so it can be present a character also it will match your answer is the two has the more unique compared to the question mark some unique features so this asterisk can represent empty string also that I've become to show you it can represent either only one character or multiple character so means suppose if your string is in the case you can see this one if your string is empty and pattern is the Aztec you can see this is the true right and even suppose if you is this string is this one and pattern is just star if we match because star could be anything even it could be have the one character and or you can could have the any character and due to this star this algorithm is going to little bit tough compared to the other algorithms let me just fast forward let me see the few examples then you can jump into the solution so in this case CB is the string and pattern is the star of course it will be the two because star can represent the CB in this case and we are going to take this example in the our Solutions so if suppose steering is a b c p q G and your pattern is a question mark C astric G so check whether this is the this we match or not so of course A B match with a B we match with the question mark can be present any character C of course is matching with the c and Easter and this g percent this G Then star can be present the p and Q and you can say this is the two so it's matching another case if the steering is same and this time pattern is just a b c star not the G of course a is matching B is matching with the question mark C is matching with the c and here e star we represent the all three character and U string is correct and another pattern nothing in the pattern only you have the star yes it will match any character but now I am asking you if steering is this pattern is this and if instead of the G suppose here is a p there which returns that to no because this T is not matching with the G here this star will be present only the PQ but this ending character is not matching and wizard would be the force right so if this is the G here U it is 2 even without G is also to only star is also true right again suppose if your string is the empty string and pattern is question mark it is false because question mark represent any one character but one character must be there but in the empty there is no anything right so question mark will be the false but if you have the this is the string and this is the pattern it's two because question mark represent empty character also right but how it is difficult right why you cannot do the one comparison and say I can do that I am going to say why it is the complex so if you see here your string size could be anything and pattern size could be anything right so your string size could be of the 20 character but your pattern size could be the any character less than equal 20 right or even it could be the pipe only and that it could be two because St can be present the multiple character at a time right that's why it is going to the 80 bit complex here and another complexity what I am saying here suppose this is the history and suppose this is a pattern try to understand here now I am saying you whether this is correct or not so now you see if a is matching with the a and B represent with the question mark and now here C so when you confusion the C to C we cannot say to here let me repeat my sentence again if you this first character matching with the first character pattern I say this is two first character right another character is matching IBC this is two second character I don't know about the next character right now come the third character now she is C matching I can see two but now think if suppose this was the false even though c is matching can I say to you no because previous one is the first even though C is matching it will not make the two it will become the false so current index matching is depend upon the previous one so when you compare the this index if this is the clue if this is the two then you check the previous one if deviation was the two it will be true if this is the first previous one this is the false so this completion is based upon the two things one thing is that if do not match suppose this here was the C here was the F it was not matching then I can straight forward I can say this is the force but if it is match this index character then you have to take the previous value not the current we have you previous value that could be the two and that could be the force in this case suppose if it is was the f so a was matching I can see to b f is not matching I can say for c is matching cc is matching what is the previous value false so this will be the false if suppose this is the question mark then this become the true then cc is matching previous value 2 so this is the two so to make this kind of the solutions we have to take the a very easiest way to take the 2D Dimension so what I will do here I will put the pattern here in this case pattern is a and here we take the string what is the String here a b c d f okay but important thing is that we have to leave one low also and the one column also so this values will be come from I will explain you so because why I shoot the wire should not start index 0 because we have to always depend upon the previous one so if you start your calculation on the index 0 then we don't have the minus 1 index so you have to start all the calculation from the index one so you will have the index 0 for this kind of the calculation so that I will detail uh no let me wrap the board and take the example so suppose if you have the string s and the pattern T and you can see I have just given the indexing right so to solving the problem I will come across through the 2D dimension for the Boolean so I will give the name of this 2DS the match and of course at the size of the this 2D would be one size greater than string so it will the low Y is the string event so if you can say this is my string so this is the string we go by and column wise is the pattern so I have given the pattern one extra I have taken the event because as I discussed that I need go to the previous one to fetch the value I so that's why I have taken the extra one here so if you see that my pattern would be start from index one and I kept one empty stick on the both on the pattern also and on the string also I will detail you why I have kept that so this is my indexing for the pattern this is indexing from either string okay so the beauty of this 2D so if you see that if you see here the empty would be match if it is match I will be presented to you so when I start up I algorithm by default I will make the two for the uh this one and now if you see this empties matching with the a it will not match the a so I can put the force here and also something I want to say you the beauty of this one if you say the two so what is the value of match 2 it will become these two and these two I'm talking about this one so this value whether this is the 2 here Force here this box represent the pattern this one a and question mark and this represent the string a b so if you see here the match 2 means still would be the a b t here what is the string a b here and what is the pattern Q2 a question mark So this represent the pattern matching or not matching for this particular value so if you case if you see this is matching I will give the two that I will come across that just I want to show what is the importance of this grid when I save 4 or 3 that means till index of the 4 for the steering and T index for the pattern 3 so 4 up to p and this is the box I am talking about right and here so string would be a b c p and the pattern is still three a question mark and C so this value whatever the value would be here that will be represent the pattern matching field here I'm not talking about the full string so if you suppose taking this one this box so this box represent where your pattern matching for this string and for this pattern this very present so I am going to play one by one and see that and this value this box will be present you complete string and the complete pattern is matching or not and this is your final value if this is returning the true means your pattern is batching if this box returning the first your pattern is not matching okay so now c one by one here so how we do that so actually we will follow the three logic here that logic is that first logic if you character matching or suppose if collector does not match then we will use the force then no need to do anything I will represent the first means suppose if this one and this one is matching if this one is not matching I will say false first condition second condition if character match if it is match then we will see if character match then we take the previous value previous diagonal value so it will be here previous value means suppose here if C and C is matching right in this case if C in C is matching so I will take the previous value what is the previous value before c this is value and before c this is the value right so if you are talking about this value this one this C and this C right we are talking about this one so if C and C is matching I will see the what is the previous value means before c this one and before c this B so this is the previous value I will take the value from here right that's why I say the previous value no so if this is the star is coming then take one example when then you can understand so suppose if I am taking the ABCD a b c p and pattern if you take the pattern a question mark C and asteric so in this case there are two possibilities what I will do first take the string adjectives and pattern consider the pattern acidic is not there because S2 could be the empty and see whether this is true or not first I will check this one to enforce second case you consider that this star is the P so you can remove the peep from the history so this case ABC and here and see whatever the value you both take the all and take the final value so in this case if you see here suppose this is the a b c p and the a question mark CQ I am talking about this one right so if you take this box then take the first case I remove the asterisk so if you're talking about this box you remove the asterisk means you move the asterisk so you are talking about then this one you are talking about the a question mark C and the string acbp means here so you are talking about this one this box and for another case you remove this p and you are talking about this box so I will check this box and make the all condition that is for the aesthetic okay let me see the example then it will give you that okay so foreign and we represent the pattern is equal to J and string row Y is the I so I make the two for you one for the I start from the S string so your wise and then the four J is a pattern wise that's why this is the S7 and this is the prevent and of course let me do the first then because I have started the form one and one so we first compute the Zero part then this code will be start right by default on the Zero Geo will put the two because obvious this empty MTV Match so I put the two now this empty and this a is not matching so anyhow if you guess this one means your string and pattern is the a so it is not matching your pattern is the MTA it is not matching so I will give the first the same case it is a false here also false here so because in here what is that your string is e and the pattern is empty a question mark C obvious it is not matching I will put the first In Here Also first and the same case if your pattern is empty it will not match any one here so I will return the force so before starting the code we have to fill this zeroth column and the 0 because my uh would be start from the 1 why could we start from here right now I'm saying that if P pattern J minus 1 why I did the J minus 1 because it is J star from the one and pattern if you see here so J minus 1 is 0 so I have to start from zero the and this is start from the one that's why I always given the minus one right so if you see if this is the if this one p and this is as if it is matching I am talking about this box right so because i1 J1 i1 and this is the one so I'm talking about this box right if this is matching or pattern is a question mark then you put the value of the I minus 1 and J minus 1 so if you here if a is matching then I minus 1 J minus 1 what is I right now 1 and what is the J one so I minus 1 0 J minus 1 0 so what is the value of J what is the value of Max jio is the two so it will come from here and so I can make the 2 here and we have already discussed that if it is matching if we take the previous value now it will go up and this time I is equal to 1 J is equal to 2 right I Square 2 1 J is equal to 2. so now in this case pattern is 1 and this is the zero right so now and right or not yes so now if this is the now this is the and we are here talking about this box so my pattern is my pet in for this box my pattern is the A and question mark and string is the a right so you have to check right now so it is matching or not because J is equal to 2 and this is the zero this is the one so in the case if no right time G is equal to 2 so this is a 2 minus 1 so I'm talking about this one and I is still one so one minus G one zero so this one I'm talking about this box and I'm talking about this box so it is asking that if both are matching or the G minus 1 is the question mark yes G minus 1 question mark if this is the case then you take the previous value so we will take the previous value here so it will become the false next now I'm talking about the this is not matching at all so make the first but this time we make the Force form it was not matching and the force was already there so when you create the 2D Dimension or the value is equal to false so it will contain the force so now to move forward that now this is the A and this is the streak right now the S3 case is there so in the St case what I have to see we have to see this value or this value if one of the two I will put the two but both are the first so I am going to make it the force so this is the force and of course A and G is not matching I will make the false now come here b or a is not matching give the first B and question mark So this condition so you have to take the previous one is equal to 2 so make the two B and C is not matching give the false b and s t again I will take this value and this value both all false so it will become the force B and G is not matching give the force c a is not matching no problem give the false see question mark this condition so then you have to take the C question mark you have to take the previous value right figure is equal to false so let's go to the false and then cc is matching if it is matching then take the previous value so for this is the previous value so this 2 I will take the two c and question mark So in this case C and St so take the both or here is the force here is equal to 2 then take the two e sorry C and the g is not matching put the first p and the a not matching give the first p and question mark this condition to take the previous value false p and c not matching give the force p and the stick so again previous this one and this one is equal to 2 you can see if once U we get the 2 for Star it will be the continuous star continuous two so now p and the g not matching put the Force Q and A not matching give the Force Q question mark this condition take the previous value false q and the C not matching give the false q and the star take both of the all this is the two because one of the value in this value one is for 2 so put the two Q and G is not matching give the force G and a not matching give the false G question mark this condition take the previous value G and the C not matching give the false G and star this one and this one to G and G is matching and get the two so the moment you get the two this is your final result it means that this pattern this string at this pattern is matching right so that's why this was the now we see in the code how it works but one more time I want to explain that if you come any particular point if you suppose take this example too that means from here that means this is string come here and this pattern must be matching you can see this is the ABC and here the a question mark C right both are the correct so this represent the column into those value right let me so but we have the one corner case if suppose you have the S3 only right only the asterisk in the pattern so if you make this one so this will be the your pattern on it this is the empty St and here if you see this is your uh this is your empty string here and you have the a and a right so in that case this by default is to you then if before asterisk if anything is true you have to make the two to satisfy this condition of the this kind of the corner case otherwise it will give the false so when you make this match DP in that we have to first view this rho and this column keeping this condition in the mind that I will show in the code so first what you have to do we have to create one two dimension I will give the match name and anything you can give version and as we discussed that rent would be the one character mode of the string and one character mode of the atom so in event plus one and here better plus one okay and by default we will first make the this index 0 and 0 is equal to 2 right and you have to give up the first row keeping the conditions that I will explain you so in the case suppose your s is equal to a and pattern is only a stick so just feel free for this condition we have to make the row figure so obvious if we start from the one because I have already taken the jio so I will start from the one and it will go equal to the pattern event right we are going for the zero wise right so only the first view so it will go and then I plus and here if we check means in the match we have three only the first row means this is the first two right and the Comm is equal to I so I will check if previous we have you I minus 1 is equal to true and pattern is at the I minus 1. right you're getting my point right the If the previous character and why I am getting the character I minus 1 because my index is starts from the one so if that is the static so that's it so if this is the two keep the two if this is the first keep the whole fall first right so now we're done now if you go the first entry for the First Column right so I will start from the what am I talking about so I because you have already given the uh zero index so this we are giving the First Column so compute the S right so it is the s dot length of course equal because we are taking the from the one and then I plus and here I will keep the complete I and jio because I'm talking about the First Column I will return the force because only the first is the two otherwise you're fitting the force now our logic will start and the logic we start from the one right and first is the row y so I will take the S3 Dash Dot length and now take another one is the column wise right so G is equal to 1 and of course equal length of the pattern right and then J plus if the first condition if your s character at the I minus 1 because string is the I equal to that term J minus 1 if both are matching right if both are matching then uh whatever do if both are matching here and or your P dot character is equal to star in both case we have to take the question mark So in both case we have to take the previous value so what is the previous value match I and J equal to match I minus J minus a right foreign then what you have to do match I and J equal to is from the up and underapped from the website in upside if it is any one to IB take the two so first case I will make the minus I minus 1 keep the J intact or next time keep the eye intact and the J minus one if any condition that I may take it and this is the false is here and this method and here will be Vita on the above the last Index right so match s dot length this is the last this from where from the right bottom right so p length this is the code let me just run and check whether it's working or not it's working fine right so now it's working fine and take some different examples to one in my case what we have taken that a b c p q G and it was the a question mark B and see that style G right and check this is working or not this is also working so it is giving the first because we have to give the a b is matching if you give the C and then it should work too right okay these two what I have given the first case because this is the corner case suppose you have the 2A here and if you have given the s t right so now if you can see it is working fine it is giving the two but you if you remove this part is true now suppose if you are not keeping giving this part and try to run it will give the false that's why the first we taken the corner case for the first one right so this is the first feature that's why you need to put this condition just for this corner cases so now everything is working let me submit this code and see how it works submit the code this would work because I have already tested here so this is accepted right so thank you very much please don't forget to subscribe and like the channel thank you
Wildcard Matching
wildcard-matching
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where: * `'?'` Matches any single character. * `'*'` Matches any sequence of characters (including the empty sequence). The matching should cover the **entire** input string (not partial). **Example 1:** **Input:** s = "aa ", p = "a " **Output:** false **Explanation:** "a " does not match the entire string "aa ". **Example 2:** **Input:** s = "aa ", p = "\* " **Output:** true **Explanation:** '\*' matches any sequence. **Example 3:** **Input:** s = "cb ", p = "?a " **Output:** false **Explanation:** '?' matches 'c', but the second letter is 'a', which does not match 'b'. **Constraints:** * `0 <= s.length, p.length <= 2000` * `s` contains only lowercase English letters. * `p` contains only lowercase English letters, `'?'` or `'*'`.
null
String,Dynamic Programming,Greedy,Recursion
Hard
10
841
hi guys welcome to algorithms made easy in this video we'll go through the question keys and rooms there are n rooms and you start in room 0. each room has a distinct number 0 to n minus 1 and each room may have some keys to access the next room formally each room i has a list of keys letters given in an array form rooms of i and each key is an integer in 0 to n minus 1 where n equal to rooms dot length or the length of this particular array that is given to us or the list that is given to us a key room of i j is equal to v opens the room that is numbered v initially all the rooms start locked except for room 0. you can walk back and forth between rooms freely and you need to return to if and only if you can enter every room so in the example one we can say that in room 0 we have the key to room 1 in room 1 we have the key to room 2 we have key to room 3 so we can go through each and every room which is 0 to 3 and so the output is true in this case while for example 2 you can see that from the room 0 you can either go to room 1 and 3 and in room 1 you have the key to either room 3 0 or 1 and in room 3 you have the key to room 0 but there is no way you can get the key for room 2 because that key is already placed in the room 2 and so we cannot enter that room and so we return false so that's all about the problem statement now let's go ahead and look how we can solve this question let's take this example where we have these three rooms that we need to visit so now first you will go and enter room one now room one has the key for room two so what you do is you need to mark this room as visited and you will go to the room 2. while you go to the room 2 say you have these two keys one is to the room one and second is to room three so since you have visited this room one or you already have the key to room one you would not need that key again you can just take the key to this third room and go ahead in the third room say you have the key to room one so now do you need this key no because you already have the key to room one and so you just mark this as visited and now all the rooms or all the list that was given to us is traversed and we would now need to check whether all the rooms have been visited or not so with the ticks that are shown here we can say that all the rooms that were there are already visited and so we can return true in this case for example if any of this stick was not there then we could have returned false so what do we need to do in this particular case we would need a boolean array to mark whether a room is visited or not so that would be of length rooms dot length or n secondly we would need to recursively call a function that would collect all the keys that are being there in a room and would be going into the next room according to the condition of whether the room is visited or not visited with these two things we can actually solve this question so let's go ahead and write some code for it so the first thing that we are going to need is a boolean array so let me take a class level variable so that we can access it everywhere and the length of this visited array would be the length of the rooms that is given to us and now since we were already having a key for room 0 we can mark that as visited after this we'll just call dfs on our rules and starting with the zeroth index once this dfs function is complete we'll check whether any of the room is still unvisited or not so we'll check for each value in the boolean array and if this is not true we return false otherwise we can just return true now we need to just write the dfs function so that would be so this is rooms and this is index we are starting with index 0. so now as we know that at a particular index we would be having a list of integers we would need to iterate over each one of them so let's write a for each loop if this particular iath room is already visited that is if visited of this i is already true we do not need to do anything but if this is not visited in that case we would need to market visited and apart from that we need to call dfs on rooms and on this iath room so that's it let's just try to run this code and see whether it works and let's quickly resolve all the errors and it's giving a perfect result let's try to submit this and it got submitted so the time complexity over here would be the number of rooms that we are going to visit since we are not visiting each and every room that was previously visited we will just say that the effective time complexity would be equal to number of rooms but in worst case we can say that it could go up to o of rooms plus the number of keys that we have so this is the dfs way of doing this question you can also do it iteratively by using a bfs method wherein you will be using a queue the logic behind it remains the same that you need to mark the room as visited whenever you are taking that key and at the end you need to just iterate over this visited array to check whether any of the rooms is still not visited so that's it for today guys i hope you like the video and i'll see you in another one till then keep learning keep coding
Keys and Rooms
shortest-distance-to-a-character
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms. Given an array `rooms` where `rooms[i]` is the set of keys that you can obtain if you visited room `i`, return `true` _if you can visit **all** the rooms, or_ `false` _otherwise_. **Example 1:** **Input:** rooms = \[\[1\],\[2\],\[3\],\[\]\] **Output:** true **Explanation:** We visit room 0 and pick up key 1. We then visit room 1 and pick up key 2. We then visit room 2 and pick up key 3. We then visit room 3. Since we were able to visit every room, we return true. **Example 2:** **Input:** rooms = \[\[1,3\],\[3,0,1\],\[2\],\[0\]\] **Output:** false **Explanation:** We can not enter room number 2 since the only key that unlocks it is in that room. **Constraints:** * `n == rooms.length` * `2 <= n <= 1000` * `0 <= rooms[i].length <= 1000` * `1 <= sum(rooms[i].length) <= 3000` * `0 <= rooms[i][j] < n` * All the values of `rooms[i]` are **unique**.
null
Array,Two Pointers,String
Easy
null
1,725
now let's go over the code question number 1725 number of rectangles that can form the largest square now the question says you're given an array rectangle is at index i represents the i rectangle at length and width so this is length and this is good you can cut the eighth rectangle to form a square with a size length of k if both k is less than or equal to length or k is less than or equal to the width so for example if you have a rectangle 4 6 you can cut it to get a square with a side length of at most four and if you don't know what square is squares should have all same size when you have a rectangle that looks something like this let's say that this is four and this is six in order for us to get a square we have to cut this by length of two and this will have a length of four this would have four and so forth so squares should have all same size so from this rectangle the largest square that we can make is this four by four square that next length be the side length of the largest square you can obtain from the given rectangle so that would be four in our case return the number of rectangles that can make this square with side length of max len okay now let's look at our example so for example we have this as our input array and remember that each one represents a rectangle so we have four rectangles here now you have to figure out what the maximum square we can make out of this each and individual rectangle so for the first one it's going to be 5 because we can't make a square that's greater than 5 right because our length is 5. and for this one it's going to be 3. this is going to be five and this is going to be five now what they want us to do is you want to first get the maximum square and then it wants us to return the count of maximum squares so what's the maximum square here well it's going to be five right because we have five three five and five is the biggest size and how many fives do we have one two and three so our result is going to be three because we have three size five rectangles now let's look at our example two so what's the maximum square that we can get for each rectangle it's going to be two here it's going to be three here there's going to be 3 here and what's the maximum square out of this whole rectangles that's going to be 3 right because 2 is smaller than 3 and how many 3s do we have 1 2 and 3. so our result again is going to be same as before 3. now using this logic we can try to solve this problem in two ways first thing i can think of is you can try to store the max square into an object and then get the count for each and lastly return the count of biggest square and the second will be more optimal because for this solution you won't have to make it object to store the count of the squares well instead of counting the number of max scores that we get what we can do is we can just track which one is the largest and if it is the largest and then second keep a count of the largest square so using these two logics try to implement your solution first of all would be to create an object to store the count of each square that we get and next what we can do is well you don't really have to make an object so just check which square is the largest and then keep the count of the largest square only so this will be giving us a space complexity of oven because you might have to create an object that's equal to the size of the input but for this one we just have to keep this one variable that's where it's going to keep the count of the largest if you guys find this helpful make sure you guys like and subscribe thanks now let's go over our first solution and our first solution is going to have a time and space complexity of o-o-ven later we are going to of o-o-ven later we are going to of o-o-ven later we are going to actually optimize our space complexity but let's first code this solution because i think it's easier to understand and time complexity will be oh then because we will have to iterate through all the elements in our given array so first thing i'm going to do is i'm going to create a variable named output and this is going to be an object and here what we're going to do is we're going to store our keys which is going to represent the squares and values which is going to represent the count of the squares and later we are going to get the maximum key and then return the count of that largest score that we have so i cream i'll put the store on my result and i'm going to create a for loop and let's just create a for overloop and for each rectangle and rectangles array what i'm first going to do is i'm going to find the square so let's just call this men or you can just call it square let's call it square and i'm going to set this equal to math dot min square operator rectangle and what this does is if you were to just console log square you can see that it's giving us the square for each rectangle that we have so largest square that we can make out of the first one is five second one is three five and that's exactly what we have so we now have our squares but what we need to handle is you want to put these squares into our output object and count how many of the squares we have so first let's check so if the output does not have the square what i'm going to do is i'm going to give a value of zero if it's the other case so we initialize it with a value of zero and then we increment the output by one it's not output it's output at square okay now let's just console log our output and we have a count of our object or squares let's just call some log here so you can see that we have one square because we have a value of one that has a size of three and three squares that has a size of five and if you were to just cause a lot of squares again here you can see that we have three fives and one three so it's looking good so far now what we need to do is we need to be able to get the maximum square and our output so i'll call it max and we are going to use math.max and we are going to use math.max and we are going to use math.max to get the maximum value and we're going to use the spread operator and dot keys to get all the keys in the object and pass in our output object and let's just console log our max square and it should give us a five right because we have only threes and fives we got our maximum square but now we need to return the count of the largest square which in our case is going to be three so how do we do that well how do we access a key or a value in an object well we do that by first we're going to return because that's going to be our result output at key max and that should give us three which we got because again we have five threes which is the largest square and let's just uncomment our second input we have three here and a two here so maximum or the largest square is three and how many threes do we have three of those so that's why we get three so this is our first solution again i think this is really easy to understand but let's try to later optimize our code so that we can see some space now let's go over our second solution where we optimize our space complexity if you remember from before we had a space complexity of all of n and the reason was because we had an object to store our key value pairs where key represented the square and value represented the count of that square but here what we're going to do is we're just going to keep two variables where one tracks the largest square and another one tracks the count of that largest square so having two variables we are able to save some space so given that now let's start coding so first i'm going to create two variables one is called the max and this is going to be the largest square that i'm going to have and another one is going to count and this is going to keep track of how many largest square that i'm going to have let's use a 4 overloop and it's going to look similar let's switch things up a little we want to have length and we are going to have width for the second one so what we're here doing is we're just destructuring our array and if you don't know how that works i'll show it to you really soon so rectangles okay now if i were to just console log length and console.log width you can see that console.log width you can see that console.log width you can see that length represents the first value so 5 3 5 16 and so on and so forth and with represents 8 9 12 and 5. so this is a way to name the first element in the array this is the name of the second element in the array or you could just don rectangles for this motion if you like it doesn't really matter so now what i'm going to do is i'm going to find my square and this is going to look similar to our previous one it should be min because it can't be the bigger than the smallest size that we have so we are going to pass in length and width and if you want you could just do the same thing as before where you pass rectangle here and then just use sprout operator and pass in our rectangle and if you were to just constantly log r square you can see that we have our squares right so for the first one it's going to be 5 3 five and five now what we need to do is we need to check well if my current square is greater than my maximum square that means that i need to change my maximum square to the current mode right so we are going to set max equal to square so we are replacing our maximum square here and then there's one more thing what we have to do is we need to increment the count so we're going to set count equal to one okay that looks good and another thing is if our square is equal to the current maximum square what do you have to increase the count by one so let's say that we were passing a value of five well first is square equal to max well our max is negative infinity for now so that evaluates to false so we skip is square greater than five well five is greater than maximum which is negative infinity so what we do is we reset maximum to our current square which is five set count to one and then next what's our square is three well is square greater than three no right so we just keep looping and then our square is 5 again well is our square equal to max well it is because at first our square became 5. so we increment our count to 2 so this evaluates to two now and then next we go to the next one and have another five and square is equal to our max so we increase our count by one again so after we're done we just want to return our result right which is going to be stored in our count variable so there you have it uh we have our result of three and let's check for the second one and second one also gave us a result of three now using the same logic that we used before i want to go over this solution one more time but we are going to use reduce for this one well the code itself is actually going to look really similar but i think it's good to practice solving questionnaire in a little bit different way and here we can just practice using reduce too so same as before first thing i'm going to do is i'm going to set my max to negative infinity and then here i'm going to use videos so rectangles dot reduce and here i'm going to pass in two things my accumulator and my current value and i'm going to give an initial value of zero and our that means that our accumulator is going to be zero right and later i'm going to return my accumulator and this is actually going to store the count of the largest square that we are going to have the same as before what i want to do is i want to get the squared so square is equal to math.min squared so square is equal to math.min squared so square is equal to math.min and let's just actually rename this to rectangle and we are going to pass in a rectangle and let's just console log square you can see that we have our largest square for each rectangle now let's just get rid of that and same as before we need to have some if statements to check so if square is the same size as our max what do you want to do we want to increase our count right but here we don't have a count instead we are going to have an accumulator that's going to keep the count and we can just actually rename this to count if you want but i want to just leave it like this for now and we're going to increment our count or accumulator by one and next we need to check well there's the current square greater than our maximum square that we stored well if it is we want to reset our maximum square the first to the current square and then set accumulator to one and we're actually done so everything inside the reduce function looks the same it's just that we have an accumulator and instead of using a for loop we just use reduce but the logic is the same and as you can see we have our result and let's just uncomment this you can see that we have three for this one also if you guys find this helpful make sure you guys like and subscribe thanks
Number Of Rectangles That Can Form The Largest Square
number-of-sets-of-k-non-overlapping-line-segments
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`. You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`. **Example 1:** **Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\] **Output:** 3 **Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\]. The largest possible square is of length 5, and you can get it out of 3 rectangles. **Example 2:** **Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\] **Output:** 3 **Constraints:** * `1 <= rectangles.length <= 1000` * `rectangles[i].length == 2` * `1 <= li, wi <= 109` * `li != wi`
Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).
Math,Dynamic Programming
Medium
null
394
hello everyone welcome back after a very long time welcome back to my channel i am amitesh and today we will be discussing a very good question which i found while i was solving it for uh this uh six companies 30 days challenged by our square and the problem name is the code string it has been asked by goldman sachs and uh let us first see what the question is so we will be given an encoded string and we have to return its decoded string now what's this so we'll be given uh this kind of form which is k and an encoded string and we have to print the encoded key number of times which means where the encoded string inside the square bracket is being repeated k times right which means for example a is there and outside the bracket key is three we need to print a three times right i'll explain it in the examples first let's understand what the question says next is it's given that there is no number except that uh that k the repeating number right so we can safely assume that there is only one digit uh there is the only digits represented here are k which means that uh it is for uh repeating elements right now we can also assume it's given in the question that there are no extra white space square brackets etc right let us now jump into the examples the constraints are the length of the string can be 30 and yeah okay fine let's see the examples first okay so i've already written it what uh the question as the question says this is k this is my encoded string right it's very difficult to write here so i have to print it uh write it three times so answer would be a e what's the answer here how will we seeing it so here it's written to c like 2c so firstly i'll write 2 times c right first step would be this and the second step would be c 3 is here right so let's go and write acc three times so ac c a c and as you see ah i cannot write just understand it right so there these were the examples i hope you have understood it now let us right now dive it into uh how would we how are we solving that right let us see it's a very good uh very good question i would say it took me time to understand how to approach it so uh let us say if 3a is given right now we have to decode is decode it as a now how i am coming up with three is i know there is three written here how will i get it when will i get it and uh i also want a and then multiply or like print it three times right so for printing we need three right and for uh the content i need a right how will i do it let us see so first of all our intuition comes that we need to uh search for a closing bracket first closing bracket no closing bracket this is a closing magnet right now go back to the uh till we find uh opening bracket and pop out all the content inside it which is three i have popped out oh sorry a yeah i have popped out a now i go back once more and pop out three and then c uh and then multiply it a multiply here means like i am repeating it three times okay don't misunderstand it right then let us take another example for example 3 is 2c right this was my first example so let us see now as i said i'll go for finding a closing bracket yeah here is the closing bracket my first closing bracket is here pop out all element till i find the next opening bracket which was c then pop out again the number so 2 into c will be there and then i'll push back all the c's inside the okay so this is acc i have pushed it into the stack now three again pop out all three this three till i get an opening bracket and then multiply it by three which means three times hcc right so i hope you got it like i'm using i'll be using a stat right pushing out every element for example in the first case i'll be pushing oh let me rub it uh it's very it's not looking good just let me uh rub it first and then show you i hope you have got it because it was uh really very interesting uh to use this approach let us say we have a right i have used the stack right let us go through the example uh i'll be on this string uh i'll beat this character sorry put it into the stack i'll be on this character now put it into the stack then i'll put a right i then i found this and when i found this i'll pop all the characters still the opening bracket which was a and this opening bracket which is of no use and again pop out the number of times the character needs to be repeated and then finally multiply the answer with that right and then put it back into the stack and then return the answer go so this was very simple i'll show you another example to assure that this process is working now let's go like 2 a three b okay so how we will go as i said i'll use a stack let's take a big stack right put two put an opening bracket put an a put a 3 right put a opening bracket put a b now we have found a closing bracket here right now i have to pop till here right so b and an opening bracket gets popped out this is of no use i'll pop out three also and then multiply it by b and then push it back into the stack which means now our stack would look like b three times right then a then an opening bracket then a two right then again i found a closing bracket right and i pop out b bbba and then multiply it two times right this would give me the answer let us jump right into the code so stack off i'll put i'll make a stack as i said and then traverse the string quentin is equal to 0 i less than s dot yes length and then let's start length i'll traverse the whole string yeah if i find a till i find a closing bracket i'll just push the content in this into the stack pushing it through whatever i said i am writing down in the code i pushed everything instead now what i found uh i found a like opening bracket right i'm sorry my bad i found a closing bracket right i have to pop out till i close it so why where i'll store first of all let me keep a current uh string to store that whatever i pop off so i am storing right so while sp which is our stack top if it is not equal to a closing sorry opening bracket till that time i'll fall till that's ml what pop and put it into a our current string which would be yes i'll go through the examples again for sure to tell that this process is working now what uh after uh like while stack not equal now stack top is equal to skip top is equal to uh this opening bracket right i need to pop that too which is of no use as i said by popped opening bracket now i might have two cases from here i might have a number outside here right or i cannot have a number outside here or the stack can be empty also because uh let us take this case like uh let me show you like let us take this case so a is only here right and the stack is this a and when i found this i pop out a i pop out this was of no use so i just pop out and the current was just a right current was a but we didn't have anything here so i like the stack can be empty right so we don't pop out anything from here so if while not stack dot empty right and and uh this digit the drop element which is st top is the st top is a digit then i'll put it in number which is uh my string dot top and then press the number right and then next now why i did this i'll explain it again and telling oh i have my number right let us convert it into an integer first so string to integer stoi is string to integer i have converted it into an integer and we have to repeat that string that number of times which was in the question k number of times right so number of times till the number of times is there i'll go through every character of that current string and then push it into the stack which would be this and then for sure what i did here is got my stack pushed and this process gets repeated every time now that i have pushed everything into my stack now my stack contains my answer right so let us print the answer so while stack is not empty all right i'll just answer equal to st top press answer plus answer and sd dot pop mistakes so i guess uh my this would contain my answer and i will return it let me see if this code works there might be somewhere else no there was no other i'll submit it anyhow i have made it so uh this was a very good question and see this day this is faster than 100 of uh c plus submissions how i did it i'll explain it again right okay so i'll explain again for clearing all the confusions you have and this time i'll take a good example so let me take three a two c okay three 382c let's go okay so my code says that i'll go till uh i'll be pushing the content till i get a closing bracket okay so this is my current stack okay i'll be pushing it uh the content till i get a closing bracket so three an opening bracket a two an opening bracket i'm writing here okay see now i found a closing bracket so what happens now i found the closing bracket now pop it out until i find uh this code pops out and sources into the current till i find the opening bracket which means here is our opening right here this one so my current now stores see true till i popped out till the closing uh the opening bracket now what now i'll pop the opening bracket also and put the number if it's there so let's see now i popped out this one and then uh checked the number so times now times variable now contains two right from this code you can see the times variable contains the number which was true right now what i did is while times minus for every character i push that into the stack so this was the stack correct three this and a so for times minus means two times i put c inside the stack push finally i am done my pointer was here now the pointer moves here again it found the closing bracket again it repeats the same sequence till it finds an opening bracket and it pops out everything from here like acc pops out this right st dot pop was here i mentioned it here popped out this and then for the number i find the number that would be the number of times my answer would be repeated which is 3 so 3 into acc which would give me acc three times yeah let's leave it yeah so i think i hope you would understand this uh if you like the video do give me a thumbs up because it really motivates me to make new videos for you every time right and explain your better concepts very easily to understand thank you
Decode String
decode-string
Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer. You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`. The test cases are generated so that the length of the output will never exceed `105`. **Example 1:** **Input:** s = "3\[a\]2\[bc\] " **Output:** "aaabcbc " **Example 2:** **Input:** s = "3\[a2\[c\]\] " **Output:** "accaccacc " **Example 3:** **Input:** s = "2\[abc\]3\[cd\]ef " **Output:** "abcabccdcdcdef " **Constraints:** * `1 <= s.length <= 30` * `s` consists of lowercase English letters, digits, and square brackets `'[]'`. * `s` is guaranteed to be **a valid** input. * All the integers in `s` are in the range `[1, 300]`.
null
String,Stack,Recursion
Medium
471,726,1076
1,247
Hello gas welcome you new video, so this problem is a very interesting problem and one of my favorite question is from Giridih. Okay, so in the question it is said that we are given two strings S1 and S2 of equal length. It is already mentioned that out of the lengths of S, Van and Tu, X and A from two letters will either be only And 2 strings are made as if this tu makes tu string equal tu h other what we have to do is we have to make S1 equal to S2 which gives as many characters as there are in S1, there should be same number of characters in h2 and out of the two There should also be the amount of characters like here it is XX and here it is A so we have to make it X A If we have to string with both characters, then this thing has been said and we have been told that return d minimum number required to make s1n2 equal. Okay, so we have been told that we have to tell the minimum number of cells so that we can make 1s2 equal. If you can make it and if it is impossible then make a return mine. Let us understand it once. Look at the problem is very straight forward but the logic is very good in this. So if I talk about the approach to the problem then in this The first example that is given to us is that we have a string which contains Let's see again the condition is that there are many characters to type S1, both should be different, so look friend, there can be four conditions here, okay, the first condition is that like in S1, we talk like this here. This is It is possible that this A and this A can also be found and that can also be found like this, okay I am talking about such a The sequence of XX can also be found like this, AA can also be found, If there is a minimum number option then let us again take the same example in which it has been given to us that XX and AA are A, we have to make them tomorrow, then what does your basic initiation say that they can be of equal, they can be equal only then. We can see when whatever is ours becomes Let's see how to do it. So here we understand that we can perform one character response by picking one character. Okay, so here we will be looking at Ace of Zero. Have done s van of zero is shared with van is ok and after shopping we got the form of A X and minimum operation then I would have got X Sorry A This increased our limit, so we understand that if we swipe like this, it will take us a lot of steps. How many are the total number of Let's do something and try to make both the streams from, first in the string there should be as many We will give a team under his command, okay, so we will perform shopping like this, we will solve zero s zero with s van, but man, nothing is getting full, so before full, let us talk about this, so we will get the basic instructions till now. What all did we come to know? Okay, so the basic idea is that we came to know about two things. After understanding this much, let's look at the problem. Firstly, I am in the testing size, this was given to us in the question itself, okay, so we do not have any right to it. Our question is this banda but this second point, this is a very important thing to note that the amount of character from this string exactly content is ok, what am I trying to say, as you can take an example, see here we were told. The exact content of a string is the amount of characters. It can mean any string when there is amount of characters in both of them, like if there is an This is S2, okay, it is in the same way, so if there should be one A in this too, okay, if every news in this is 2X, then there should be 2X in this too, that means there is equal distribution of characters, okay Dan, and in the same place, if If I talk about it, there is no sharing of equal amount in both, like you can see in this example, in S1, 2X came, in S2, two brothers came, so now we know that how many total How many are there? If there are two, then these two By doing this we will make it equal, but see when we are not able to make it equal, look, we will not be able to make it equal then, as from here till now you all must have understood one thing very clearly, that thing is that look like take this example here. Pay I can keep it and I can keep one A in S1 and I can keep one A in this, so let's see an example from where we will start getting clear about the actual shopping etc. from whom and why to do it, how will the minimum be arrived at, okay? So the example is that I have taken a string S1, there are some characters in S1 and there are some characters in S2, so look actually this is my Tak Ji Han is absolutely ok, this is my A, what was my position now, S van S, you are equal, so Ji Han is absolutely ok, now here comes the point, he is my ex and he is my brother. Is it equal? ​​No, it is not equal, so it equal? ​​No, it is not equal, so it equal? ​​No, it is not equal, so we have to make it equal, but to make it equal, we have already come here, right on the second index, we have got an If you want to make it equal then remember I had talked about four conditions at the top that look either I get X or I can get Bhai which you can get There is no problem but if this happens then there is a problem. If this happens then there is a problem because we both have to make a call. Okay, so let's leave X and A for a while, then we got the same Let's keep it and again if it is AA then there is no problem in it. Again there is no problem ok brother but this has a problem and what is the solution to this problem ok then look X A you are ok if you will not be able to do anything then I What will I do na I will try to do this I will open that next Which again a episode why that because again diagonal like I set this so what would I get I would get If I get a sequence of But if they get Look how they are going to look, if we diagnose them, there will be no benefit even after shopping, there will be no change in them, so for this too, we will have to set them as X A, so when we swipe on X A, it will convert to A I and what will happen in A If one operation is done, then they will become There is If So I am going to undergo minimum two operations, so friend, from here onwards everything is very clear, look, it was equal, there is no problem, but here there is Want a greedy approach? What should we do is that axi is neither, I have to find the next Along with A, there will not be Later this one will come, it will take two operations. Here, how much minimum pressure will I have, it will take two operations, but if I talk like this, I would have had one more Here, two legs of And if we get one more sequence, what will we do with these two in one operation because X will become A, then this A will go here to A and this X will become I got his brother This is this D Power PDS This means we go from the gate to confusion Pay A Look this look brother if I get X A's brother In this way, if I get the same day of A, why do we have to talk because look here, if it becomes direct, then it will make X A and There will be a swipe, this will create The Man, take the total of four times This is the index from s2px, okay you guys must be seeing this is how much is my total, my One A came here One came here How many times have we consumed A in the same manner So X A once came here Just became one And talking about A Now, if I talk about the minimum number of operations required for this, then remove it from the game, I do n't see any problem in it, okay, Y-Bhai n't see any problem in it, okay, Y-Bhai n't see any problem in it, okay, Y-Bhai is also already a shortcut, so remove it too because there is no problem in it. Let's come to X A and A look at the axis if It will be reduced in one operation, happily it will establish its setting, ok, it will equalize in one operation but the problem comes, if A is X then A Will take your butt here, is n't it, there is only Would like to open But look here Because I will do two operations with this one to equalize but with this one less becomes mine. Okay, but now we have to check the same thing, X A got his partner but AF did not get it. Along with A, X can also be A can also be I could, but it is necessary to have one of the two because I actually want as many F's as there are. Look, all these So I am not sure if there is another A If there is X, then A Try this thing because unless you do it yourself, maybe it will be very clear to you but A Why did I say this? I see, A wants it simultaneously, it can be X, A can be A or A can be He may have a lookalike or it may be the opposite, like X is lookalike It should not be, these two are the same and why should they not be? Let's take an example like here X A After doing this, he used to check whether You must have called yourself in the operation, after performing this shopping, now it comes to my poor ex, and ex has his day, not mine, brother, with whom he could have reduced one operation, he got ex, if he got ex, then it is his friend now. Look, I will have to do two operations, I am taking 0 sign, now I will check each index by applying fall loop, okay, if the size of both is equal, then you can go for the size of any one, and what to do X A And we need less amount of So we have to count, in this way I had still explained to you that the account of X A + A Please still explained to you that the account of X A + A Please remind me once again in the video, if there is any problem then it is ok then return it means it can never be equal and if it is not like this then we have to return it, don't look brother, if we get a lookalike of X A. I get its cousin If you do it, I will get the minimum number of operations, one operation and the third express, the fourth will do that operation with Axi, accordingly, I had to do Axi/2, okay, in the same I had to do Axi/2, okay, in the same I had to do Axi/2, okay, in the same way, you will do the second one also on A's account, so that That A will do with A What is the account of Along with one operation, I will do the operation, but one ex will be left, about whom we cannot do anything, he is not found, okay, in the same way, I will do shopping with one ex upon you, three upon you, one. Again I did so much shopping in one operation but look at doing the All the There is an account and for every AX there exists an A So, if for each ex the ex is not gifted, but the same person must be exiting that amount because we have first put a check and returned it to the mine owner, so that this does not happen, that is why he has come here, so for the ex. A Only If there is a minimum operation then minimal operation would be done and only one axis would be left. For this axis, an A If there are only a few left then I will get the answer in this way, so that's why I had to do XA model Tu in Tu, why didn't I do Tu plus directly? If I know for sure that XA will survive, it is not necessary that if AXI survives. If axi is left then only it will be multiplied by 2. If it is not left then it will not happen. This direct case is going under and here one more thing, here you have to write not equal, let's submit it and see. Now look here one thing. It may have happened that you people may not have understood this even a little, but as much dry return as I did, it is up, now you guys do it once yourself and then watch the video, you guys will definitely understand, it was a very logical question. I hope you guys enjoyed this gravy, let's meet in the next video, thank you.
Minimum Swaps to Make Strings Equal
decrease-elements-to-make-array-zigzag
You are given two strings `s1` and `s2` of equal length consisting of letters `"x "` and `"y "` **only**. Your task is to make these two strings equal to each other. You can swap any two characters that belong to **different** strings, which means: swap `s1[i]` and `s2[j]`. Return the minimum number of swaps required to make `s1` and `s2` equal, or return `-1` if it is impossible to do so. **Example 1:** **Input:** s1 = "xx ", s2 = "yy " **Output:** 1 **Explanation:** Swap s1\[0\] and s2\[1\], s1 = "yx ", s2 = "yx ". **Example 2:** **Input:** s1 = "xy ", s2 = "yx " **Output:** 2 **Explanation:** Swap s1\[0\] and s2\[0\], s1 = "yy ", s2 = "xx ". Swap s1\[0\] and s2\[1\], s1 = "xy ", s2 = "xy ". Note that you cannot swap s1\[0\] and s1\[1\] to make s1 equal to "yx ", cause we can only swap chars in different strings. **Example 3:** **Input:** s1 = "xx ", s2 = "xy " **Output:** -1 **Constraints:** * `1 <= s1.length, s2.length <= 1000` * `s1.length == s2.length` * `s1, s2` only contain `'x'` or `'y'`.
Do each case (even indexed is greater, odd indexed is greater) separately. In say the even case, you should decrease each even-indexed element until it is lower than its immediate neighbors.
Array,Greedy
Medium
null
277
hey how's it going everyone welcome to another video today we're going to be doing another leak code problem and this is a problem that is really fun in my opinion and it's called find the celebrity and it's a leak cook medium and this is actually a problem that a buddy of mine saw in a phone interview at Amazon so obviously it's a problem that gets asked in the real world so the definition here is really long and like makes it confusing so I'm just gonna explain the problem to you guys basically you have a list of people at a party or a group of people and one person in that group is a celebrity and that's celebrity doesn't know anyone else however everyone else knows that celebrity so you're given this function here called nose and it takes in two values and it returns a boolean so if a knows B then it returns true so the way that we can use this is that if anyone ever knows someone we know that person isn't the celebrity and the person that knows someone also is in the celebrity so basically say you have nose and you have said we actually have the celebrity in here and we have like person a this return false because the celebrity does not know the person so using this function we need to figure out who the celebrity is and also if the problem states that there might not be a celebrity there at the party so that's also something that we need to take into account so the way that to approach this problem is let's just first start with the first person and have that as our potential candidate so these people are represented as integers so we'll just say candidate equals and then we'll you know we have to start somewhere so let's just start at zero so what we need to do is we need to loop through the rest of the people and we need to start at one since we already have zero all right so with this person what we need to do is we need to check if our candidate knows them then our we know that our candidate can't be the celebrity because the celebrity doesn't know anyone so what we can do is we can say if knows candidate and I then we need to update our candidate and our potential new candidate is gonna be I since someone knows I but we don't know if I knows anyone yet so that's why we're calling it a candidate so it's going to be candidate equals I all right so once we go through that we know that we have one person left that someone knows them but we don't know if anyone knows them or not so we could do potemkin edit but that's only if we were guaranteed to have a celebrity since we don't know we need to do another pass through so what we can do here is we can do four and then we just do another for loop all right so at this point we'll have a couple cases here so we'll do if so we want to first make sure that value that we're checking is not the actual candidate and we also need to check two things now we need to check if our candidate knows someone or if anyone knows the candidate and if either those are true then our actually if the opposite is true it'll return false so let me just show you so if we have knows candidate and I so if the candidate knows someone that can't be the celebrity or if I knows the candidate so I doesn't know the candidate then the candidate can't be the celebrity so if we have either of those two cases we just return to minus one because that's what the function says that's what the prompt says otherwise we do return that candidate so let's go ahead and run that and we have an error because of course we need semicolons in Java and so that looks good let's go ahead and submit and we get success so we have a run time of 97% and a memory we have a run time of 97% and a memory we have a run time of 97% and a memory usage of 58% all right so let's look at usage of 58% all right so let's look at usage of 58% all right so let's look at the time and space complexity of this since we're not using any additional space the space complexity is just going to be constant and the run time is going to be n because we have a loop here where we're going through each element and we also do have this extra for loop but this isn't adding to the time complexity because we are just doing another pass through so the time complexity will just be linear or n all right that's gonna be all for this video I hope you guys enjoy the problem as always thank you guys so much for watching please like subscribe if you haven't and I will see you guys next time
Find the Celebrity
find-the-celebrity
Suppose you are at a party with `n` people labeled from `0` to `n - 1` and among them, there may exist one celebrity. The definition of a celebrity is that all the other `n - 1` people know the celebrity, but the celebrity does not know any of them. Now you want to find out who the celebrity is or verify that there is not one. You are only allowed to ask questions like: "Hi, A. Do you know B? " to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). You are given a helper function `bool knows(a, b)` that tells you whether `a` knows `b`. Implement a function `int findCelebrity(n)`. There will be exactly one celebrity if they are at the party. Return _the celebrity's label if there is a celebrity at the party_. If there is no celebrity, return `-1`. **Example 1:** **Input:** graph = \[\[1,1,0\],\[0,1,0\],\[1,1,1\]\] **Output:** 1 **Explanation:** There are three persons labeled with 0, 1 and 2. graph\[i\]\[j\] = 1 means person i knows person j, otherwise graph\[i\]\[j\] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. **Example 2:** **Input:** graph = \[\[1,0,1\],\[1,1,0\],\[0,1,1\]\] **Output:** -1 **Explanation:** There is no celebrity. **Constraints:** * `n == graph.length == graph[i].length` * `2 <= n <= 100` * `graph[i][j]` is `0` or `1`. * `graph[i][i] == 1` **Follow up:** If the maximum number of allowed calls to the API `knows` is `3 * n`, could you find a solution without exceeding the maximum number of calls?
The best hint for this problem can be provided by the following figure: Well, if you understood the gist of the above idea, you can extend it to find a candidate that can possibly be a celebrity. Why do we say a "candidate"? That is for you to think. This is clearly a greedy approach to find the answer. However, there is some information that would still remain to be verified without which we can't obtain an answer with certainty. To get that stake in the ground, we would need some more calls to the knows API.
Two Pointers,Greedy,Graph,Interactive
Medium
1039
1,725
hello everybody today we will focus on solving lead code problem one seven two five number of direct tanks that can form the largest square if you read the question we are giving off the in uh this arrival list and here in this array list we are given the items that represent them represent the length and width of the rectangles the problem is that to find the maximum square with this units i made some illustration here to explain the quest the problem better we are given off the list of the rise this each item represents the length and width of the rectangle we need to find the maximum square how can we find the maximum square by taking the minimum value inside the minimum value from that items it's 5 and as you can see here we will get 5 to make the square from this rectangle and otherwise if we get the 8 it will not be possible to make the rectangle with the unit of 8 and because of that we will iterate these lists and we will get the minimum value and after that we will keep inside our dictionary at the end of the time at the end of the function then we need to find how many times can we get the maximum square as you can see here we go if you iterate this i a list for it for the first item the minimum is five week and then three five we have the three times five one times three units or three yeah three unit and we will return that we maximum square is 5 how many times 3 times first we will focus on solving this problem with java and first of all we define a hash map first of all yeah we define a flash map integer hush map and after that we need to iterate that rectangles list for rectangle i'm sorry rectangle close and after that we will check if this rectangle yeah and sorry first of all we will get the minimum value and ins new val is equal to math to mean and this is awry and we can get the items by index like that rectangle 0 and like tangle one yeah and after that we need to check that whether that value inside that dictionary how can we look that we can type like that count map contains k mean y if that's true we need to get that value and we need to get this case value it's like that hash map point cat and meanwhile in other ways we will get zero yeah and okay account and after that we need to put that inside the map hash map put and yeah meanwhile comma plus one and for this loop we will get the hash map with the minimum value and the number of the minimum squares and we need to convert the case to the arrival list firstly we define that list of integers here lists integers and hash map point okay we will get the okay set and after that don't forget that and return hash map sorry hashmap point get collection get or collections nocturne points max yeah max hash ri i will explain that one second and this point i think it's okay yeah and actually after for after digital forward point in this for loop we will sort k and the values we get the minimum values and after that we count how many times and at the end of the loop we have a list hash map and we convert the case to the list and from this list we get the maximum value collections of the point max and after that we return the and then we return the maximum and the number of the maximum squares if we run this card we need to look that everything's okay run codes okay yeah we sorry for square or curly brackets did we type that yeah rectangle i think yeah that's the problem yeah it's accepted and submit that it has been accepted with java 6 milliseconds and if you solve this problem with patent python 30 actually yeah it's same actually first of all we define my dict is equal to dictionary and after that we need to iterate that we will get the minimum value for rectangle in rectangles and we will get the minimum value if mean rectangle not in my dict if that if not in my dictionary that's the least minimum than the minimum value of that list we check that if it's not a dictionary then we need to obtain that my dict rectangle tangle rectangular that should be uh we need to just count that yeah one sorry one else my dick in rectangle plus one my dictionary minimum rectangle plus one and at the end of that we will get the list with the case and the values and we should return my dictionary max your max mind it case think should be okay submit that it has been accepted just look differences and yeah java is more java faster than the python yeah i hope that you understand the logic or the basics i lo i hope that you enjoy that and thank you very much for your watching
Number Of Rectangles That Can Form The Largest Square
number-of-sets-of-k-non-overlapping-line-segments
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`. You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`. **Example 1:** **Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\] **Output:** 3 **Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\]. The largest possible square is of length 5, and you can get it out of 3 rectangles. **Example 2:** **Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\] **Output:** 3 **Constraints:** * `1 <= rectangles.length <= 1000` * `rectangles[i].length == 2` * `1 <= li, wi <= 109` * `li != wi`
Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).
Math,Dynamic Programming
Medium
null
43
Loot Exams will see the program of multiplication of two strings. It is from the list. The program of multiplication of two strings is simple in pattern. To understand this, there are some things in which we have to understand that when we do this multiplication, we will not use these teacher functions. This is not for any We are doing string multiplication and then thought using internal function is not possible, you see how to understand this, if we print, that's why we have inputted, we make this multiplication of gas unable, so in that condition, if we print. If you do then this is your erotica in austin that your hair and yours so you cannot notify STF in this you can fold it if you convert it into simple city interior like this MP3 Jai Hind that now if we 10 If you modify it in minutes then it will give your result which is given in the question on Patiyara, here you do not have to use the wait function i.e. simply not have to use the wait function i.e. simply multiply the two strings without putting in teacher function. Now how to do it. Coming to its logic, there are two or four things that we have to keep in mind. First of all, the logic that we have to keep in mind is that we can multiply it by using the help of your face, we will add sisters, like you can ask for anything. Is it a character, be it zero, if it is a character or a number, in any condition, you must have added it, your note will be CM and character, that is, I have added it, Lokayukta will be bathed, then what will be 55050, then its people of the institute are Asim Ninth Class. Player will be 57th on the side, we will solve on this logic, how do you understand this because like here 4830 is the festival of zero i.e. out of hundredth, we - if we do zero i.e. out of hundredth, we - if we do zero i.e. out of hundredth, we - if we do FT, it will come out to be G. O. What happened to me, convert it into number. The scene is done, if it is forty nine, it is the hello of your festive one 's caravan, then if they add 340 grams of dry ginger, 's caravan, then if they add 340 grams of dry ginger, 's caravan, then if they add 340 grams of dry ginger, then what is the join aayega or understand it like this and tenant is its value of one and from this we - make it. one and from this we - make it. one and from this we - make it. What will be its value in that condition? You will think that we will start simple on this logic, keep one more thing in mind, now we will solve on this logic, here we will solve the multiplication which we do first, we will fold it on that logic only. Explain how this sequence is repeated. What will we do with a number for the first time? We will multiply it with the file. Then we multiply it with our mind. Then what will we do? One, we will multiply 66 and if we multiply 163, then my dear 10 grams, apply 570. Six. If we multiply by next 9 then fire into six cyber cafe 30340 started and limited reminder yagya is done then we store zero and 30th here in the list, first of all we understand what is a list, we to The size that we will declare is the chest size that we will deposit the cash in. First look at the length of both of them. You see that the length of the first time is two to the contesting comment. Whenever you multiply this number, then the length of the lunch of both of them is more than in front of the lens. It is not possible, that is, if you multiply a tube digit number and a two digit number, it will not go more than four digits off and digit. If you fry the top three digits of symbol 3D, then it will not go more than six digits. Player or 382 Pat. If you multiply, then you will get more than 3425 benefit in more time. You will not have its link. The third part of multiplication is simple. What is this play list string? This is toot jokes train. So here we have declared the list. Fourth, to store the number, we A list has been declared whose link is for and everyone we have stored zero then we will do this multiplication then fire into sex ati aaya to zero aham third pocket money start and thing after that profit could have been done by Mr. Then what will we do hi * could have been done by Mr. Then what will we do hi * could have been done by Mr. Then what will we do hi * one -click Had it come, the file will come and one -click Had it come, the file will come and one -click Had it come, the file will come and what would we say, Shankar yes, these are my sarees, then what will we do, if we multiply the family tree, then what are we doing here, what have we done with the back, so what is it with the back 412 we The reminder that has been received, let the reminder unite and start ahead that I am the same as we are, the reminder of the torn one digit ahead, this trick was 3000 stored, on the reminder, the digit ahead is broken and one pocket is ahead, so did the SIM, what are we doing here, hide which plus would be 80. If there is cotton's for that toe, here we move one digit forward toe question profit is toe then what will we do if one * one comes then take out 141 important time do if one * one comes then take out 141 important time do if one * one comes then take out 141 important time because reminder is nothing here used to hide that zero minister 's team logic Using this, we have to create this program. Let's 's team logic Using this, we have to create this program. Let's 's team logic Using this, we have to create this program. Let's create the program further, after that we will try to understand it better. Now the first thing we have to do is take two strings, then we call them input and declare the back list, what will be its link, what will be its length. The length of both of your stings gives some effect. I turn off the net in S Plus, the play list is declared, it is simple, you print it and see that in reality it is also 0.2, that in reality it is also 0.2, that in reality it is also 0.2, dinner is done, if what we do not give here, friend. So this black would have been your star, so we all are not robbing Vijay of the right to store Jio in our pockets. Now we come to the program, there is also one thing and you have to keep in mind that whenever we do multiplication or add, see it from this program. Before doing this, I would request you to see the program of my addition to make number or string, it will be easy for you to understand that we can do multiplication by converting internally, why will we do such a big program in this trick because when we use any If you convert the number in director jar and multiply it, then its reason is that whenever we use it, you will be using excel or according to stomach, if you see, then this compiler also has a range, it cannot store numbers more than that strange. The number is stored till the Africa digit, whether it is tow or edit, beyond that, there will be no notification of that condition or what to say about it, when we will do idol multiplication in this trick, then this will be your multiplication according to the number. There will be no single digit multiplication and we can store this team as long as we can so we can store it as long as possible, so we need to do this, don't we? Player, now let's come to the program that we were in, how we can do this first of all. And what you have to keep in mind every day is that when we do this multiplication, we do the multiplication from the back side, this is how we notify the mind from one, we do not do mental multiplication, we will do the tips from the pilot side, then we will do one, then we will do that, we will do six, then we will do one. What will we do for this, we will start both the strings from the back side in a look, add will be 654 and it is 15.41, first education will come, then 15.41, first education will come, then 15.41, first education will come, then forest will come, then first thyroid will be formed in the soil, so for this we will see either You can reverse it, we will not lift the skin, we simply apply it in the look itself and I am in the range that for the name of S minus one A R Rahman, counting is done from all the districts, so the minute will be and will go up to - 120 pockets. so the minute will be and will go up to - 120 pockets. so the minute will be and will go up to - 120 pockets. And we will do minus one here Tega player, this is the first look, the first number is the first number, you should understand one more thing here, first what we will do is multiply 6 by the height, then multiply by and, that is, the first look is we will multiply one digit and To multiply both of them, let's give another look to that also. We set the back side setting of all this coin range length of S1 a minus one to - formation of a minus one to - formation of a minus one to - formation of a clear. Now understand in this that wearing this will cure your one digit height separated and five. What will you do with your 60 notifications, Naseer, one will be multiplied, then there will be a zoom loop, the next one will be made and then Vansh or Hafta will be fixed and mind will be multiplied, so we two people here, we have given both of them in the report, what should be the store and when the multiplication will be done, which will be back. If it is on the side or if the house is snatched then six orders 15051 player What will we do after this? The importance of gas will be converted into tasty and the logic which we will explain will come in it. We will convert any of these number strings into numbers and multiply them by single digit. What will we do for this? Product pic has been sent, let's take that equal to you and we will make that RD. What will happen with this, the ASCII value of your string will be removed. The app is hide app - we will do it for test, either add it - we will do it for test, either add it - we will do it for test, either add it here and do it like this. You can do that arty 01 we make it for tasty we have done a lesson and will do multiplication so that etc. Desmond now once pinpoint - term difficulty that every here both people have come back to me so this we click that This is that now so that we have converted the number into digits, what will we do after converting, let us come to this simple current position of the number which we will start, on that we come to that I plus Z plus one A plus product. That at the time of this action you mostly we are here simple attend what will be the location of your six because we will work the program from the back side to the American number reverse Murai tree location got 1 and one question is my zero which will market vacation of 151 If you do notification then you can see 518 multiplication, Hello Hi, what happened at one position and it is fixed at one position, Parv 124, what will happen, have you done plus one or daily new thing, my work will be done at yellow position, the reminder that has come will be stored. What will we do for this? If we do the store at a good position, then what is the first time found at the third position because we have stored Jio in the entire list. For its logic, we have included platinum i plus z plus one here. Now on to the program. Complete here, what we will do is this I plus Z plus this lineage is equal to two, we do the model, just understand that I G plus one first time, what happened is 101 and plus one on the third position, we will start, do reminder, if we press 3000, then ka Look at this, we have to meet at the third position, he is forced to have the worst position, these 10 and these two and these come to force us on this position, we want A+, 10 people, we do it, yes brother, it is loot, now understand this as we have done in the East. We are storing thirty, we are storing a request of two, here is plus quality, job is plus mixed, the number system is three plus, the pimple will break on hunger strike, there will be no plus effect in this number, my daughter, is now fixed. What do we do on the next number that will sit there, this reminder will be set that you like the quality, so what do we do here, plus is equal to two, now we simply print this, if we have one or two playlists, we will print that now. We will see the number notification 130 if we multiply the sixteen then what is my zero is coming in the first pocket then we will look ahead to remove the zero for now we understand the whole program 240 is my output which is my multiplication which is my coming this What do we do for this, first of all, this whole logic is this, you understand the logic office and article, when we make the notification of five six for the first time for 21 months, then what will be the five or six, my 3838 Gaya location, whatever. Location is happening for the first time, you are the first time, what are we in the complete list, so what is the constitution, zero will come, which was given, product plus is equal to Z plus one is equal to two of mine, this is the first time, only zero will come or the account. If you do then you can easily understand what is the item Hello, here is the call of height, one of six means one plus one two three plus what is your first time in the list on Vanshi position, you can understand here what is the first time in the list C position But if there is zero, then if we clear it then it will be zero, 360 will come, when we take out the reminder, then zero will come, okay, then at which location will we start the zero, then you see here the program that we have made - A see here the program that we have made - A see here the program that we have made - A brother plus Z plus one that position. But let's start zero, player, then egg, what is this item position, where is the first position, two that we have stored, care of hands free, then we come to the next step, next when people will run, I will be the application of fiber one. So if there is multiplication of 541 then there will be benefit. What is my position at thing? What is my position at I? What is my position at 543? Understand this, I plus G plus one. What is the position of I? One is G. Zero is zero plus one. There was a minister on the end to second position question, then when we understood it as a reminder, five plus 3.2 when we understood it as a reminder, five plus 3.2 when we understood it as a reminder, five plus 3.2 data was given to him, what will happen to me on the skin position, we store it in one pot and on the worst position, if I deposit it with carat then it is zero. As soon as the next one comes, you will complete the program by dividing it into five. You should understand this music better. Then when we start, what will happen is this 1618 out of 5126, let's see its location. What is the location of one, what is my location, what is the location of zero, and what is the location of six? 1051 is done and when we will pay our fees plus, what store were we set on one or grade second sitting position, then we got six seats, we got 2015 on second position, we are starting again on four, which is a reminder. I came out and one position i.e. I plus J I one position i.e. I plus J I one position i.e. I plus J I was my zero it was boiled on that we start one then in the next step when we go your 2101 will come then what we did Vansh plus will be done I plus J6 plus one this If it is your Jio, this is also Jio and plus we had stored 1 here at position 191, that is, when we will take out one oath, you will come immediately to the position, we will do two customers and like zero position, we will take out a reminder of Pattu, that is this zero clear. In this way, we can easily solve the complete multiplication of this string. Now the problem is that we are going to put another zero in front of it. To start it, first of all, let us work on the number. Given in this list, we take it open in this trick, now we dip a string in the air W, so now we put a loop here, for IAS in research, the length of China that W plus is equal to two, we make it tear, that is, By converting this, we have added a number and given a string. After that, what do we do? We will print it when we have timed the W to be able to say that it is a 1615 pajama application that your zero is 1402 408. This is If we have to remove the giver which is there at the last, then what will we do for that? Simple, let's apply another logic here, use a small function here, toe is kept, it has happened that the result is 0n first pocketmoney if equal to if Kill zero, don't worry about it, there will be a function of allot porn, we will remove zero 's fast pocket, remove the sin of zero, this is 's fast pocket, remove the sin of zero, this is 's fast pocket, remove the sin of zero, this is Jio in the first pocket, then if there is a reminder, then what will happen in that condition, the reminder is your net that you are on this Simple problem, if we are doing multiplication, then in the last here two is for, then here you are, if your hello appears in the list, then we come in that condition, it will remain there, otherwise we will remove the first profit, what will happen with this, should my first pocket be removed? Now when we will do multiplication on 1616, you will remain 214 80. If we apply notification custom here 12345 4 5 6 comment, then it will come 570. Hey, it is a simple program, there should not be much problem in it, first of all what will we do, link soft, we will take all the list. What length will you show in the list, which will be the length of steam, two strings will be from the front and all the points in all the pockets of the list, we start from zero, so we have to open a cafe, now let's come for that, we have already listed, let's do the multiplication from the back side, so What should we do? Friends, we have started this team from the back side. You can do this by doing director's research, using Pankaj or by doing direct reverse. In any variable, you just want to say that if you reverse one to just, then what will happen to you, equal to two faces. But forced and Salman can be reversed in the next video force, I have not resided here, simple says she is believing in following the function so that small, my program will be found player and we say next first what should we do This trick is to convert a number into a number, after converting it's reminder i.e. the time which I have kept as my reminder i.e. the time which I have kept as my reminder i.e. the time which I have kept as my reminder and then store it as hello, it is simple, if my list is going to zero then define the list that we The arm of credit of pole digit is the art powder, its return is my zero, we have used the function to remove it and after that, whatever was left of my tablet, we simply added it to a string and printed it. So friends, if you liked my video then please subscribe my channel, like the video, comment, if you are interested in any program, there is a help chart in the description below, there is a link of Facebook Instagram, you can join Selva Telegram group.
Multiply Strings
multiply-strings
Given two non-negative integers `num1` and `num2` represented as strings, return the product of `num1` and `num2`, also represented as a string. **Note:** You must not use any built-in BigInteger library or convert the inputs to integer directly. **Example 1:** **Input:** num1 = "2", num2 = "3" **Output:** "6" **Example 2:** **Input:** num1 = "123", num2 = "456" **Output:** "56088" **Constraints:** * `1 <= num1.length, num2.length <= 200` * `num1` and `num2` consist of digits only. * Both `num1` and `num2` do not contain any leading zero, except the number `0` itself.
null
Math,String,Simulation
Medium
2,66,67,415
1,027
today we will be solving lead code 1027 that is longest arithmetic subsequence so in this question we are given with an array Norms of integers and we have to return the length of longest arithmetic subsequence in nums or given array and we all know that arithmetic subsequence is nothing but a series of integer where the difference between these integers is constant like we can see in example one there is 3 6 9 12 and you can see that 6 minus 3 is also 3 9 minus 6 is also 3 and 12 minus 9 is also three so as the difference is constant so we can say that this whole arrays in arithmetic subsequence and therefore we return the length of areas output so how we can solve this question as something we will see so we are going to utilize this example number two for understanding how we can approach this particular problem so the first Brute Force approach that I can think of is like first thing is very clear to us that we need a difference right we need a difference between two values for checking whether the rest of the integers are in series or not arithmetic subsequence or not so for that we always need two integers so let's consider this is our left value this is our right value and we will do right minus left for calculating difference after getting this difference how we can check the existence of arithmetic sequences we can do R plus d and whatever the value is we will check the rest of the array if this value exists in this portion of the array then we can say that yes there is a series present else what we can do we can increase our pointers or we can say we will move forward and check the difference between another two values that is 9 and 7 then again we'll do the same thing we will subtract 7 minus 9 and whatever the difference will be we will again add the right value to it and then we will check from 2 to 10. so this whole approach will take how much time as for left and right values we need to nested Loops so it will take big of n square and then after getting the difference and getting the sum of right value and difference we will check for the existence of the arithmetic sequence and in worst case it will take because of n times so the overall time complexity will be bigger of NQ and we all know that this is most likely to exceed time limit therefore we can't proceed with this approach so how we can optimize this so now what we will be doing rather than taking left value and right value we can take left and right as a range so now this is our range and what we have to do is we will check for all the arithmetic sequence in this range and this is how we will be calculating for all the ranges like for firstly 9 and 4 will be arranged then 9 to 7 will be another range then 9 to 2 and then 9 to 10. in this manner we divided this whole problem into smaller sub problems right and we all know that this approach is known as dynamic programming so we will be solving this whole problem using dynamic programming approach now we know that in dynamic programming we also use minimization so in this problem where we can use it we can see it very clearly that the traversal that we are having in this range is going to be repeated in the next stage or next further traversals right we can see this portion is going to be repeated and then this portion is also going to be repeated so how we can cut off the computational time we can or the traversal time we can save the result of this traversal so that we can utilize it when we are going to Traverse this next range right and then again we will be storing the result of this traversal so that we can utilize in next traversal and this is how we will be using the memorization trick too now let's see how we are going to store our data and what we are going to store so firstly what we have to store we need to check and secondly what will be the data structure that we will be using right so first thing that we can see is there are elements in Array and these elements are going to have differences in the sense we will be calculating differences like for 9 and 4 then for 9 and 7 then for 9 and 2 then for 9 and 10 so we can see one element of array is going to have multiple differences and with all these differences we know that the ranges keep on changing so the length of arithmetic subsequence will also be changing right different so how we can store this we know that 9 minus 7 is also 2. and 4 minus 2 is also 2. so only on the basis of difference we can't store the value right so how we are going to store the value so that we can refer it again and it should always be unique in some sense so that we can check in our next step is suppose we are at this step this is our left pointer and this is our right pointer so how we will be storing it as right pointer then the difference and the longest subsequence in that particular range and this is how we will be storing the values in our data structure so that when we are going to increase our right pointer suppose it will go to here and we have stored this value so when right is here our left pointer will be at this place so every time when we are traversing when we are storing data it will be in this format and when we will be checking for the existence of that data in our data structure what we will be checking left and the difference because in the next step our range is going to be incremented right so we won't be getting the same value but we know that our left pointer is at that value can be at that place right so we will be checking for left pointer and difference if these things doesn't make sense right now not an issue because we will be going through the whole array once using this approaching we will try to visualize the whole approach so at that point of time things will become clear so okay let's start and see how we can solve this example using this approach so at first my right pointer is going to be here and my left pointer is also going to be at this place now one condition that we will always checking is a left pointer should always be less than right pointer then only we are going to check and check that particular image okay existence of subsequence because we know that we need two values to get a difference and then check the existence of arithmetic sequence so when both the pointers are at same position we won't be able to do that so our left pointer should always be less than right pointer now I will be increasing our right pointer and it will go to 4. so now what I am going to do write minus lip that is 4 minus 9 difference is minus 5 now I know that we need to check what the existence of left value and the difference in our DP so how we will be storing our DP as we discussed to make the value unique we will be storing right pointer and the difference as a key and the length of the subsequence as the value so right now as I DP or hash map is empty so we will be simply inserting this value how we will be inserting when we are going to insert we will keep write value that is 4 and minus 5 is equivalent to 2 okay so right now these are two elements right then we will increment our left pointer it will become equivalent to right pointer so we step out this nested Loop and we will increment our right pointer so it will go to 7. now what we will do our left pointer will always start from 0 because we have to cover that range as we discussed previously so now our right pointer is at 7 and left pointer is at 9 so what we are going to do is 7 minus 9. the difference is -2 now what we will be checking we will -2 now what we will be checking we will -2 now what we will be checking left pointer and the difference that is 7 and 9 and 2 is there in our array in our hash mark no then what we will do we will simply insert write value difference and the length of consecutive sequence now we will again increment our left pointer will come here and now what we will check 9 minus 4 this is 3 we know that 9 4 minus 4 and 3 is not present in our hash map so we will be inserting the right value that is 7 and difference that is 3. and the length now we will again increment a left pointer it will become equivalent to a right and we will step out of the nested Loop and again we will increment the right pointer it will go to 2 now we will again check right minus left that is to minus 9 it will be minus 7 then we will check the left value that is 9 and the difference minus 7 is not there in our DP hash map so we will simply insert right value that is 2 and difference as a key and this is the length then again we will increment our left pointer it will come to this place and we will do 2 minus 4 it will be minus 2 now we will check 2 and minus 2 is not there in our hash map so we will insert what 2 and 4 and minus 2 is not there in our hash mark 4 is that left pointer that's my bad and 2 I minus 2 will be inserted with consecutive uh with the subsequence length now again our left pointer is going to be incremented it will be at 7 so what we will check 2 minus 7 so this is minus 5 now again left value that is 7 and minus 5 is not there in our hash map so what we will insert 2 and -5 -5 -5 equivalent to 2. now again we will increment the right pointer because when we are going to increment a left point it will become equal to right and then you will step out and increment the right pointer it will come to 10 now we will do write minus left that is 10 minus 9 it will be 1 and we know that 9 and 1 is not a key in our hash map so what we will do we will again insert the right and the difference and the length then again increment left pointer this is 10 minus 4 this is 6 we know that 4 and 6 is not there in our hash map so what we will do 10 and 6 equivalent to 2 then we will go to 10 minus 7 that is 3 we know that 7 and 3 is there in our hash map so what we will do we will increment it by a point okay because this was already existing so in this subsequence ring length is going to be increased by 1. now we will again increment the left pointer so it will go to 10 minus 2 this is 8 we know that 2 and 8 is not there so we will insert it that is 10 n 8 equivalent to 2 and now we are done with our old traversal so we can see now our hash map is having all the subsequences and all the lengths are also done so now what we will do we will Traverse this hash map and we will return the maximum length that is this one three so our answer will be free so how much time this whole approach took for returning the answer is because n Square because for left and right ranges we are having nested Loop so the time complexity will be big of n square and a space complexity will also be equivalent to bigger than a square as the size of the array will be equivalent to this one Big O of n Square so now let's try to code this whole approach you will be surprised to see that this approach took this much time for explanation but the code is going to take only five lines so firstly let's initialize our hash map then foreign pointer you must be thinking why I am taking right and left from 0 but the thing is this will take care of all the edge cases so that we don't have to you know Define conditions for different edge cases separately this Loop will take care of it so these two are going to be are Loops at which we will be getting our range now in that range firstly what we will do is we are inserting right and the values difference right so numbers right minus nums left this will be the distance and we will check if this already exists what we were checking if left and this whole thing again that is nums right and nums left is existing in r hashmap then take the value and if it's not existing then return 1 because we will add 1 and it will become 2 if the value is not there else it will become 3 or it the value will be incremented by y so this whole condition will take care of our lookup and incrementing part if the value is there then it is going to return the value else we will be getting 1 and we will increment it by 1 so we will get 2 because at the end the length 2 is always going to be there because we will have two values for calculating the difference right and at the end what we have to do we have to return the max of DP Dot values and we are done this was the mold code now let's see if I had done something wrong now it works fine I guess yeah the whole solution is submitted and you can see it is quite efficient so this was the whole problem although my explanation might be you know a simplified version of this whole problem but this problem was not a medium question this problem was a quite hard problem but now we know how to solve it so hope you find this video useful and if this video helped you to understand this whole problem then you can like this video subscribe my channel and soon I will be coming with some more questions and if you have few questions that you want me to solve then you can share them in comment section I will definitely try to solve all those questions and response it for this video and I will see you soon with another question thanks for
Longest Arithmetic Subsequence
sum-of-even-numbers-after-queries
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`). **Example 1:** **Input:** nums = \[3,6,9,12\] **Output:** 4 **Explanation: ** The whole array is an arithmetic sequence with steps of length = 3. **Example 2:** **Input:** nums = \[9,4,7,2,10\] **Output:** 3 **Explanation: ** The longest arithmetic subsequence is \[4,7,10\]. **Example 3:** **Input:** nums = \[20,1,15,3,10,5,8\] **Output:** 4 **Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\]. **Constraints:** * `2 <= nums.length <= 1000` * `0 <= nums[i] <= 500`
null
Array,Simulation
Medium
null
449
Hello Hi Everyone Welcome To My Channel It's All The Problems Realized And Civilized GST Socializing Converted Alphabets Object Into A Sequence Of Which Sadhak Can Be Stored In File Or Memory And Transmitted Across Network Connection Link To Be Constructed In The Same And Other Computer Environment Designer Loot Civilized and Mrs Free Word This Problem Is Constructed To-Do List Co Problem Is Constructed To-Do List Co Problem Is Constructed To-Do List Co Problem One Is Like C Tronic York Phase Problem Gas 108 Constructive Work From Already Problem Solve This Problem Solving Problem Life Enjoy's Problem Solve Place Understand How Will solve this problem is solved Vestige 251 and 320 Phase one will do for realization of civilization which will use Peter Friedrich Andhe Factory subscribe to subscribe The Amazing Releasing The * Space One Space 354 Sikheta Singh First of all evil spirited person who lives in Delhi Ministers And Converted Into A String Of 2G Live Well And 30 Subscribe Placid In The First Of All The Best All The Food Factory Not Subscribe Like Subscribe And Not From Next Qualities In This Earth End Subscribe Vikas Liquid Form Ko Subscribe Sure Zee Newspaper Today I Will Give We Do Subscribe My Channel I Will Also Help You Explain Subscribe Channel Thank You Need To Do Anything Just MP District Wise Subscribe Do A Spring Builder Sona Novel Call Rediff This And This Let Se And Let Me David Feldman f-35 virud ndps vpn india and will f-35 virud ndps vpn india and will f-35 virud ndps vpn india and will return string return string return string that singh and prem s well so that will return to its own way and definition of birthday wishes for a deficit and entry no deep rooted in the string that builder hai saeed sunna ko Hair withdrawal benefits also optional in this will return otherwise will happen when you for the value of root develop subscribe The Amazing subscribe must dot write 210 only our serialization party done using this festival has been created to string using reproduction and after releasing this legislation will check Data Is Page No Entry Channel Subscribe String From All No Data Speed ​​Limit Absolutely From All No Data Speed ​​Limit Absolutely From All No Data Speed ​​Limit Absolutely Return From Truck Tasty That From Also Preorder Traversal Bill 5 This And Standard 10 And Did Last Indexes Don't Length Minus One So Let's No Improvement Medical Staff Busty Sudhir What Is The Name of the Subscribe Intestine Tasty Intellect and Goal Start With Now School subscribe The Channel That Advice Will First Aid Vinod Episode Version Lenovo Dates That Involves Dia Fruit of the Tree and Safari So Let's Root is Equal to New Trend Mode Ko Switch youtu.be Hotspot Close Subscribe Must Subscribe Now For Do Subscribe Index Loon This And Subscribe Node Which Will Be Liberated Soul String Will Be Used For GPS Of Index This Investment Considered In The Entire And A Dot Pass Intes Office Start Which Is The Root Directory In This Will Reduce Loop absolutely delayed course to subscribe our Channel and start from not starting boil subscribe must subscribe fruit dot right subscribe and subscribe the subscribe and subscribe pimp node in the river tricks three but 101 in interesting detail 012 that 411 you can be a leader Like This Is The Visualizer Tool In The Best Quotes And Will Be Sonal And 5th That 2050 Govinda Right Side Soldiers Will Be This Is The Bell Next9 So Let's Compile NCOS Workings For All The Best Places Is Or Actress Work In Flats Submitted 137 Accept Some time complexity of civilization is to phone number note Same time complexity of Video then subscribe to the Page if you liked The Video then subscribe to
Serialize and Deserialize BST
serialize-and-deserialize-bst
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. **The encoded string should be as compact as possible.** **Example 1:** **Input:** root = \[2,1,3\] **Output:** \[2,1,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The input tree is **guaranteed** to be a binary search tree.
null
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree
Medium
297,652,765
35
Hello hello viewers welcome back to tech news hindi video bhi seedha 100 china short position problem wishes from list to date end of june challenge so let's not look at the problem statement the problem remaining life middle aged person ten writers others the video then subscribe to the Video then subscribe to the Subscribe Tree Not Present So If Elements Of Maintained In Ascending Order And Difficulties Inserted Into Death Six Will Go In Between This 517 Index 512 Index 76306 Goals Between 517 Index Of Beloved Country Land Which Will Push 7.23 100 Index 7 Vikram Between 517 Index Of Beloved Country Land Which Will Push 7.23 100 Index 7 Vikram Between 517 Index Of Beloved Country Land Which Will Push 7.23 100 Index 7 Vikram Thakur Okay so you will just have written in the newly selected element which of this is the return of birth Okay no matter you want to 100000 laptops subscribe The Veervikram One to 100 quick events will be shifted by one position so you will just to Retain its position which element will become doctor 0.5 inches from left side right side you will return lost 0.5 inches from left side right side you will return lost 0.5 inches from left side right side you will return lost in the mid-1960s President of 1000 subscribe and subscribe the Channel to do the time complexity of main research if you already know its latest From Your Target Element Five Initially Sufi Applied Sciences You Will Find The Attacks Of A To You Can Simply But What Is The Element Is Not Present In The Food And Subscribe The Channel Please subscribe and subscribe the 12th Part Plus Minus Point To That Is This Subscribe Will be late suman sur log iljaam bhi point to the same element aisa hi now you can find the value and welcome to the same point someone will also point 1000 compete with shyokand se 1000 festivals -1.2 this point note this loop festivals -1.2 this point note this loop festivals -1.2 this point note this loop CO2 values ​​of 100 parties Will go to three for this CO2 values ​​of 100 parties Will go to three for this CO2 values ​​of 100 parties Will go to three for this 60 element after this and exception and when you all the three leather industry element which is the largest fresh water issue index point to my people okay so this point case no if you go out of votes than what you Can You Simply First Form Check Is The President Of Australia And Greater Ahirwal You Can Just Check Which Element Of This Point To Point Tours Plus Points 258 Your Value Will Again Be Updated To Make Plus One Log In No Way Want To 7 Minutes Will Also Be Appointed Seven Day Special To Zulu Value Will Get Updated And This Point To Which Of This Point To You Will Return Just The subscribe research station par use up the phone is this code words like request you just implement android soeing in this paste on with your target and you can simply subscribe and finally target which are you doing this you will just subscribe the channel like share and subscribe
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
472
um hello so today we are going to do this problem which is part of lead code January daily challenge so we get an array of strings words that don't have duplicates this is important and we want to return all the concatenated words in the list of words now what do they mean by concatenated words they mean that um if it's comprised of entirely of at least two shorter words from this words list okay so it's a so basically a concatenated word is a word from this list that can be obtained by concatenating at least two other words right you can calculate more than two but a two plus okay and of course like if you can continue just one that would be the initial string itself so that's what makes what it means here so if we take a look at this first example you can see for example um this we have here cats dog and cats and that's just a combination of cats in dog so it's two plus right it's two and then it's a concatenation of them entirely like there isn't if there was a x at the in the end this word would not be a concatenated world because it's not entirely comprised of concatenated strings from this list okay so if we take a look here um so there is this one which is comprised of cats dog and cats right then there is this one that has dog Cat's dog so still two here and then this one has rat cat dog cat so it has this one and then has dog right so it has even three um so you get the idea um now in terms of time in terms of constraint here we have the list of words can be really big 10 to the power of four the list of individual the length of the individual words is a little bits on the smaller side so it's 30. um and so the words are unique this whole piece is also important so let's see how we can solve it um okay so how do we solve this so this is an example of the first example we have cat cats and then the rest and so how do we how can we think about this in a way that we can arrive at the solution so one way to think about it is let's pick for example one of the words let's pick the bigger one right what do we want to be able to get from a letter the first letter to the end using only other words from the list right that's exactly what we want okay and so how do we how can we so this is that means we want if we try to think of it in terms of a graph that just means we want a path from index 0 to index n minus one and what are the edges so if you want a path and you want to use a graph then you we need to think about what are the edges well what are the components of this word here just letters right and their indices right and here you can see if we want a thermostat of a graph the graph a path is usually from a source node right to a certain destination so this all if tells us maybe we should try to make the letters be um be the nodes because we go from one letter to the other and that's the path we want so okay so that means maybe let's have a graph for each world so basically this is for a specific word that we want to check if it's a concatenated word so for each word what we can do is just um create a suppose we have a graph from uh out of that word and the nodes are basically the letters of course will represent them with their indices and then what would be the edges now that's the question well let's think about what would be the solution you can't go from you can divide this into just CA and then TS why is that because there is no CA and TS in word right and so what the edges have to be just from the valid transitions what are the valid transitions the about transitions is if it's a word in this list of words right so for example from a c to a t that's a valid Edge right and so what we can say here for example this is a valid Edge right let me actually write it in a different color so what we can say for this one here is that c to T this is a valid Edge C2 TS is a valid edge here is a valid one and here's its cat is a valid one in this world so we can create edges like this because why is that because the path that we want to take that we want to end up with has to be just something like cat here it's not cat possible but here the right the correct path would be to get to the end is going to be cats two dog right to um cats right and by its path I mean you go from C to S you go from D to DJ and then you go from C to S right and so that's exactly the idea here is that let's just create make this be a graph and we can just how can we find a if there is a path from one node to the other in a graph while we can just use DFS right and this is the smart idea is that well there is no Edge between C and A because there is no word CA in this world in the list of words that we are taking a look at okay and so with that idea we can just solve our problem right we would have an implicit graph that basically if that says basically if um let me write this down so if w i j is in the words and maybe we can convert it to a set so that it's easy to check then that means basically there is a path there is an edge um from I to J okay so that's the main idea here that we are going to apply now there is one caveat though um so from this C what about from this C here to the last s right for this world does if there is a path should we say this is a concatenated word well no because the problem says at least two right and it needs to be different towards not the word itself right and so but this is a word in the list of words so it is a valid Edge according to our graph definition so how do we avoid that well we can just do the check when we are doing the traversal to find the path we can just make sure that I either I is different than zero or J is different than the um then n just so that we don't count this Edge right so for each word we don't want to count the edge that constitute the world itself right so that's the only distinction but otherwise the rest should be the same um okay so let's take a look maybe at the second examples and applied there so the second example is cat dog and then cat dog right so what we will do is we'll run through the example so first cat Okay and we'll just say um go through the do a DFS for I so I will start here and we'll check for All J's right that are from I here so I'll say is C so is the basically is the w i j here is this a valid um Edge is I to j a valid Edge well it's not because there is no C in the list of words right this is not in the list of words so it's not a valid Edge and so we move our chain here is CA which is w a j a valid Edge no it's not right so we move j again this T of value is um I to t a valid C to T here which is I to j a valid world yes it is right but the problem is that I is equal to 0 and J is equal to um the end of the string and so this is not what not the image we should take because it's the word itself and so this one would fail this check here the chin okay and so we would not count this will not add it to our results so our result is still empty and then we do we move I so we move I uh we want to try all substrings uh do we move I know we wanna get the entire path so we don't move I so we try the next World which is dog and so now I is here J is here same thing D is not a valid Edge we move j is d o a valid Edge it's not in the string so it's not valid we move j is Doug a valid Edge yes but it felt this condition because this is the word itself so we don't use it and now what it becomes interesting is now we look at CAD dog okay so I Starts Here J Starts Here we move because C A is not a valid Edge cat is a valid Edge so this is why it becomes interesting so cat is a valid Edge and it's not it doesn't uh it passes this condition so it's different than I is different than z i is equal to zero right but J is smaller than n so this one is a is valid for this condition and so that means we need to add to our result uh we need to say we need to go next right so this means basically this is a valid portion and so we advance our eye here just DFS right we found the first uh we found the first Edge and now we want to continue our path to find a path to the end so I becomes here J is here we move j here now we have d o not in the list move j here Doug is in the list and I is different than zero and so this is a valid Edge right and then when we reach the end and minus one here or we can say n because we will increment when we reach the end that means we are done right and we are done and there was a path and so we'll say um that this is a valid concatenated word and we'll add it to the list I hope that made sense um I think it will be even more clear with the implementation but essentially we are creating a graph where for each word we will go through each word in the list and to check if it's a concatenated world we will have an implicit graph where the nodes are the letters and the edges are the um are constructed using the words in the list so there is an edge if from I to J if W from I to J is in the list of words right and you want to find a path using DFS from 0 to the end of the string word um such that there are words in between right it's not just zero to n minus one we want towards in between because that's what the problem says it's at least two um words at least constructed from at least two words right so that's what we want um so that's the idea and so graph nodes are the letters edges are the based on the words in the list and we do the fs pre-shred so let's implement it and fs pre-shred so let's implement it and fs pre-shred so let's implement it and make sure it passes out test cases um okay so the supplement the solution we just um saw in the overview so what we need to do here is um so first we need to do um our word set right and so this is going to be a set of words um and then we need to go through each world right so this is just to be easy to easily be able to check if a substring right from I to J is part of the list of words because that's exactly what determines if there is an edge or not okay so here we'll just go through the list of words um and the second step is to um of course do DFS as we said for that word and we'll start at zero because remember our nodes are the letters indices and this is the starting node and we want to check if there is a path to a n minus one so this checks if there is a path uh from 0 to n minus one uh in the graph of words set right and so that's exactly what we need here is to define a DFS function that is w what it is fixed and then I is just the um the node that is that will Traverse okay and of course for DFS we need a visited set and we start out with just zero because that's what pass here and then when do we end when we reach the end of this string right and so let's define the end of the string it's just the length of the of what and if we get here that means we are good and so we want to add this word because this means basically we found a path right so this means we found a path uh from 0 to n minus 1. um using or n the N right using words from what it's set okay um of course um it's not the world itself um it's not the word itself that's something we'll pay attention to we'll take care of it down the road so here this means we want to add it to the list of results right because it's a valid one basically if we find the path that means it's a concatenated word so here we'll just need to define the list that we want to return that gets filled by DFS and so here we just written that list and now let's define the chord of our DFS here so what we need to do is we need to check if there is a path from I to J if there is an edge like this then that means let's consider this one a portion of the path and then let's check if there is a path from J to uh n right because we found a path from a to J and so to find if there is a path from I to n we just need to find if there is a path from J to n and this can be by the way multiple steps right it doesn't have to be like direct Edge right we can have multiple other steps in between um so here we just want to try all of them right so try all so we want to try all the let's say we have CAD dog right what we did is we tried this C to see if it's a valid Edge from zero to zero and then we tried C A to see if it's a valid Edge and then we tried cat right so each time we try a different J and check if there is an edge then we continue from J and so here that means we will go we'll do exactly that it and we will say so we need to go to I because we want to check the letter itself um and I'm doing n plus 1 here just because of python to get the entire let's say we are here we want to get the entire string um so how do we check if it's an edge well we just check if it's part of the words set here so if this is this means this is a word but we need to safeguard against just taking the entire world so how do we do that we just check um that either I is bigger than zero which means it's something like this so it's not the entire world or J is not the end which means it's maybe something like this or something like this to the beginning right so we check J different than the end okay but we also want to make sure it's not visited we don't want to visit the same nodes twice that's just general DFS logic right and so to do that we want to check here and J not visited okay so if all of these are correct then we want to add it to the list of visited of course but we want to also call DFS and proceed and check if there is a path from J to n okay if there is a path we'll reach here and we will add the word and so the world would be a has a the path will contain W from I to J and then some other path from J to n okay and that's pretty much it here um pretty sure fold once you get the idea of using the letters um as nodes and the words here as edges and so if we submit this and that passes our test cases right um you could of course do this DFS um in a iterative way and I think that solution is a little bit easier to work with first um so yeah uh as an exercise for you try to do it with iterative DFS um but yeah I think that's pretty much it for this problem please like And subscribe and consider supporting me on patreon and see you on the next one bye
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
598
hey everyone welcome back and today we will be doing another lead code 598 range Edition 2 an easy one you are given an MX and Matrix M initialized with all 0 and array of operation oops where oops at I is equal to you can say a limit or a range we are provided so means M at X and Y should be incremented according to the range we are given and count and return the maximum integers in The Matrix after performing all these operations so we are given a three by three Matrix as by our rows and columns n will be the rows and N will be the columns and you are given a range two by two so they are basically saying uh increase or increment the two by two column so two rows and two columns will be incremented by one and the rest will not be incremented and in the next they're saying increment three rows and three columns so the whole Matrix will be updated and incremented so return the maximum number uh count so 2 is coming four times in our Matrix and will be returning 4 in that case so what we'll be doing is just making uh variables which will hold our rows and columns so this will be n and for I in range of the length of the operations we are given so for m r is equal to the minimum of Mr itself and oops at I and 0 and MC will be the minimum of m c itself and oops at I at one so we can just return after this the Mr product MC so what this will be doing is we have like this whole Matrix and operations and you can say a matrix three by three so the m r will be initialized as 3 and declared and MC will be 3 so they both are 3 starting from the very start like this from the very beginning and now the m r will be updated by 2 and MC will also be updated by 2 in this first iteration because the value is in the first operation is 2 and in the next one it's going to increase so the minimum will not be updated and we can just return the product of these two which will before that's why uh it that's why we are going to return for so let's submit it and that's it
Range Addition II
range-addition-ii
You are given an `m x n` matrix `M` initialized with all `0`'s and an array of operations `ops`, where `ops[i] = [ai, bi]` means `M[x][y]` should be incremented by one for all `0 <= x < ai` and `0 <= y < bi`. Count and return _the number of maximum integers in the matrix after performing all the operations_. **Example 1:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\]\] **Output:** 4 **Explanation:** The maximum integer in M is 2, and there are four of it in M. So return 4. **Example 2:** **Input:** m = 3, n = 3, ops = \[\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\],\[2,2\],\[3,3\],\[3,3\],\[3,3\]\] **Output:** 4 **Example 3:** **Input:** m = 3, n = 3, ops = \[\] **Output:** 9 **Constraints:** * `1 <= m, n <= 4 * 104` * `0 <= ops.length <= 104` * `ops[i].length == 2` * `1 <= ai <= m` * `1 <= bi <= n`
null
Array,Math
Easy
370
1,255
hello friends so today we're gonna discuss another problem from lead code which is a hard problem on bit manipulation the problem name is maximum score words form by letters it states that you are given a word list and some letters add the score of each letter so in simple terms you are given some letters or actually words and there are certain letters you can used so as you can see some letters are repeated which means that you can also use these wrappers like you can only use a but you can use a two times what i mean by this is you can assume that this is a bag okay which consists of two times a one times c two times or like three times d and so on now you can only use these letters and the score you can get to use a is one so if you again use a you'll also get again one the score to uc is nine the score for using d only once is five and so on now you can only use these letters and you have to form some of these words such that you have to maximize the score but in simple terms as you can see in the example for the first example because you have one word like one like a give you a score of one c give your score of nine please give your score a five and so on now if you form the word dad you require two d and one a which you have and for forming the word good you need one g two o's and one more d and because you have two d's you can also find to do this out now you cannot make dog like though you can make dog d o g but now you do not have one more d i hope you get the point so you have to only use these words only once or like you can assume this to be a bag and you can only use or take out these words it means that you have two a's whatever word you can fit inside so that you have to form some words so that you have to maximize the total score you have and that's the whole problem now what you can see in this problem is the constraints the word length is 15 14. whenever you see that the number of words the word length which means that the length of the array of these words is up to 14. whenever you see like up to like 20 something like that then you can easily do this in like in by forming out all the subsets which means that because you can form out sorry you can use different subsets now because you can format that okay let's zoom in one case i only form this word or i form this and this word i formed this and this word and these three words so you have to first take that i have to form different subsets and because the length is very small so in bit manipulation in simple integer format you have 32 bits okay but in simple terms that in 32 bits like you can do your operations like in ofn you can do it with 22 like 2 to the power 20 also which is also like small enough so what you can simply do in this problem is sorry because the constraints are small what you can easily do here is iterate over all the possible subsets so what you can do here is if you know that or actually know that how to interval every possible subset in simple terms you can use bit manipulation so i'll tell you in simple terms yeah so as you can see what we can do in simple terms is i draw it out first so let's assume that i have some words let's this is the first word second word third word and so on then because there are three words i will define this by a three bit number the maximum three bit number is one which is equivalent to 8 or sorry like 2 to the power of 0 plus 2 to the power of 1 2 to the power of 2 which is equivalent to 7 okay now what you can easily do in this problem is it take over all the possible numbers of one two three four five six seven now every number will represent one subset that's the beauty of this bit manipulation what you can think over here is like one is like this which means that i'm taking out this subs uh i'm creating a subset which consists of only this third number like this third word the next can be two which is like one this which means i'm taking a subset of only two the three is this which means that i'm taking out a subset of this and not this is actually the bit representation of 3 like this number like 0 1 so that's what i'm doing i'm representing or taking all the numbers from 1 to 7 and representing in its bit representation and then finding out whether the like the particular bit is on or off if it is on then take that number or take that word in our subset then if you have taken like okay i'm taking out these two words then what we'll do we have to ensure that whatever characters these two words have we should have in the bucket we have or the like the set we have so we'll what we'll do whatever words we have taken will find out the frequency or the or like the number of characters we have in these words so we will make a frequency map and store out all the words which we have taken in the subset find out the frequency and store them in this map and we also have the frequency for every word we have here also so we'll just match out that whatever frequency we have in this bucket we have and the number of words or characters be required it should be less than or equal to the bucket characters we have like everything should be satisfied okay maybe it has some z and it doesn't have set then it is false or if it has one z it has three z then it is fine because like my bucket at three set and i only require one z so it's fine but it should not overshoot or it should not be deficient if it is possible then it's okay and if it is okay then this subset is possible if this subset is possible then what we'll do we'll iterate over every character and then the total score will be that okay these number of characters are required so the score is this character and the vertical character value so i have used three a's the total value we have used is three into the value of a so the value of a is let's assume that capital a is the score for a so we have also the scores for every character so the final answer is how many times we have used the particular character and the score for that character and we have to add them out and then we have to maximize that value over all the possible subjects i hope you understand the like somewhat the logic part we'll go through the code part nowadays and make it more clear so what we'll do first here is we have this bucket of different characters we have so we'll first like make a frequency map to store out the frequency of these so that we can easily match them out further in the code so we'll iterate over every possible letters it is stored in this vector and then just making a frequency map that how many times a is present b is present and so on and just updating it out so that in this frequency map f at the position zero we have how many a's are there at the position one how many b's are there and so on in this bucket we have then we have to maximize my answer initializes zero then as you can see we have to find out that we have to iterate over all the possible subsets so if we have let's assume that five numbers then i have to make a maximum number which has five bits how we can form that if i left shift one by five positions which means that i have left shifted one by five position then i will actually get a number which is having five bits and that's the number we have to iterate over so that's what we have done we have left shift this by five numbers then we have to it from one till all these numbers and then it actually represent all the subsets then for every subset what we'll do we have to make a frequency map which stores that how many different like how many characters each word have so we'll iterate over every word and we'll check that whether this particular word is in the subset we are talking about so we'll do an and operation to check that whether this particular word is in the subset we're talking about so we'll do it so if the word is in the subset then the particular bit is on so what i mean by this is if some particular word is in the subset the corresponding bit should be on one so we are checking that particular bit is on if it is on then we'll iterate over the word and for that particular word we'll find out what are the characters present in that word and we will update this in this capital f frequency map so after that we have two frequency map one is the frequency map for the particular words we have and one frequency map which is actually storing out all the characters which we have now after training or after using one subset then we have to check that whether the particular words we have used is like sufficient too satisfied like they can be easily satisfied by the bucket we have and then we let it over all the possible characters and we just have to check that whether the number of words we have it should be greater than or equal to the particular character we want if it is fine then if they are not greater then we have to make them false which means that like we don't have or we do not get we like we cannot take this subset because this is not valid if it is valid if the flag is true and what we'll do which means that my bucket is sufficient enough to make out these words which we have taken in the subset will iterate over all the port like possible characters and the total score is the character particular character score into how much that character is present and we will add it over all the possible characters and we have to maximize my answer in the end we have to just output the maximums i hope understand the logic and the code part for this problem if you still have any doubts you can mention on i'll see the next one until then keep coding and 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
59
hello everyone welcome to date headings of april youtube challenge and i hope all of you are having a great time my name is sanchez i'm working a software developer for at adobe and today i present day 656 of daily lead code challenge the question that we have in today's spiral matrix here in this question we are given a positive integer n and we need to generate a matrix of size n cross m filled with elements with values starting from 1 up till n square so we have to fill in the values starting from 1 up till n square because in total there will be n square elements and this is the way that using in which we have to fill in these elements in a spiral form to your surprise we have solved a similar kind of a question but not the exactly same which was spiral matrix one so if you carefully look at this particular question then here we were given a matrix size m cross n and we need to print elements in the spiral order so the problem reduces to identifying how to iterate in spiral order so in case if you have you guys have already solved this question or seen the video of this question then this question should be a cakewalk for you however in case not then i will tell you on how to iterate in a matrix in a spiral order in this video itself so let's get started with the presentation and let's quickly hop onto it where i'll be explaining this algorithm as well as walking you through the test case lead code 59 spiral matrix 2 it's a medium level question on lead good and i totally feel the same also in case if you have any doubt with respect to solving this question in general or if you want to ask something from me please feel free to ping on the telegram group of coding decoded or the discord server both the links are mentioned in the description below now let's get started with the question here the value of n that is given to us is 3 that means we need to create the matrix or size n square the total number of elements will start from the range of 1 up till 9. what do we do in this question the first and the foremost thing is to create four pointers the starting row pointer the ending row pointer the starting column pointer the ending column pointer and appropriately set their values these will be set to 0 this will be set to 2 n minus 1 starting column will be set to 0 ending column will be set to n minus 1 which is again 2 and let's start the traversal in the first scope we will be moving from the left to right direction starting from the starting row so the row parameter remains constant across this reversal whereas the columns keep on changing as a result of which we will be moving and filling in data at starting row matrix of starting row and the variable parameter here would be equal to j and j will line the range of ending starting column up till ending column so we will fill in data over here matrix of starting row and j will be the variable parameter whose range will start from starting column up till ending column makes sense to all of you i believe so this is the first iteration that we are going to do so let's do that iteration we'll create a variable and let's initialize it to one so let's fill one here then increment as we progress along the iteration to 2 then we have 3 once we are done with this traversal we have to move in the downwards direction something over here and as soon as we are done with this what we will do we will update the starting row pointer to the next point location which would be this one so starting row now it now points to here i'll tell you why i am doing this but just remember that as soon as we are done with this iteration don't forget to increment the starting row pointer now we are interested in moving towards the downwards direction which is this one so which parameter will remain constant over here the y param the j parameter will remain constant which is ending column so ending column will remain constant and the variable parameter here would be i and i would start from the range of starting row up till the ending row so we will fill in matrix of i comma ending column and i will start from the range of starting row up till ending row and now you understand the reason why i incremented sr the starting row pointer it was because so that three doesn't get added or consume overwritten by the vertical iteration that we are doing in this direction as a result of which we previously updated starting pointer so let's shoot for it so we have four then we have five pretty awesome we are done with this iteration and remember up once we are done with this iteration what we should do we should update the value of ec will now point to one location before which is we will reduce the pointer for ec so ec now points to this particular location because we have iterated over the last column completely let's start the iteration in the next direction which would be this one so what is the constant parameter over here is e r that means we will fill in this particular row so the static parameter is er and the variable parameter is j will start from the range of ending column to starting column remember this time we are moving in the reverse direction not from left to right but from right to left so ec to sc and let's fill in data over here we got six we got seven and once we are done with this iteration remember what we should do we should update the er pointer er is gonna get reduced by one unit so now er points to this particular location once we are done with this let's shoot for the final iteration towards the upwards direction and by light rating in this particular direction which parameter will remain constant starting column will remain constant that means the variable parameter would be i so we will fill in i matrix of i comma starting column and i will line the range of we are right now at the ending row we are going towards the starting row so e r to s r and d r is pointing to this particular location sr is also pointing to this particular location as a result of which we'll simply fill in eight over here this process can continue as we have more elements in our matrix but right now there were only nine elements so the next iteration is pretty simple you can do it by yourself and here we will get nine so when is the breakage condition is really simple till the time my sr is less than equal to er and my starting column is less than equal to my ending column i'll continue filling in data in my matrix in this order that i have just told and this is the crux of the problem so there are four steps involved in it first you are moving from left to right direction you are keeping the starting row constant the variable parameter here is j as i have told here the range for j will lie from starting column up till ending column once we are done with this iteration we should increment the value of starting row it will point to this particular location this one as we did and then it's time to move in the downwards direction which is this here the variable parameter would be i it will range start from sr to er and the fixed parameter would be ending column which is this one and once we are done with this what we should do we should reduce the ending column pointer it got reduced to this particular location and now it's time to move towards the left direction which is this let me just change the color of pen which is this here what do you see we see that the variable parameter happens to be j the row index remains constant and in the static ending row whereas j starts from ec to sc and once we are done with this what we should do we should reduce the er pointer we reduce the year pointer and now the final call where we are moving towards the up direction here the variable parameter is i again and the starting column or the column index remains constant which is sc the i parameter starts from er and goes up till sr so this is the crux of the problem these are the four directions that we are traversing in i'll be exactly following the same steps as i've just talked here and let's quickly hop onto the coding section to actually see everything in action here i've created my answer matrix if my n happens to be 0 what do i simply return the empty matrix otherwise i go ahead and create those fourth pointer starting row ending row starting column ending column and i created a count variable till the time my starting row is less than equal to my ending row my starting column is less than equal to my ending column this is the breakage condition if this breaks we get out of the loop what are we going to do first move towards the right direction what is the variable parameter here j is a variable parameter here the starting node remains the same and with each iteration we move from the starting column going up till the ending column and we allocate the count variable to ans of starting matrix comma j and with each iteration we increment the count variable once we are done with this we simply go ahead and increment our starting row pointer now it's time to move in the downwards direction and this time the variable parameter is i it will start from start row goes up till end row and the constant parameter would be end column once we are done with this we should decrement the end column pointer and now comes the case if my starting row is less than ending column that's another safety check what do we move towards the left direction here the ending row remains constant whereas the variable parameter is j which starts from ending column goes up to starting column and once we are done with this we decrement the ending row pointer once we are done with this again we go for a safety check here and followed by moving towards the top direction here the constant parameter is starting column that means j value is fixed i value is variable and once we are done with this we simply increment our starting column by one n really simple guys exactly same steps as i just talked in the presentation so let's quickly submit this up accepted the time complexity of this approach is order of n square and space complexity is again order of n square this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more update from coding decoded i'll see you tomorrow with another fresh question but till then goodbye your friend your mentor your catalyst in this journey of yours signing of sanchetto
Spiral Matrix II
spiral-matrix-ii
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order. **Example 1:** **Input:** n = 3 **Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 20`
null
Array,Matrix,Simulation
Medium
54,921
1,066
hello and welcome to another video in this video we're going to be working on campus spikes 2 and in the problem you have a campus that's a 2d grid and there are n workers and m bikes with n less than or equal to M each worker and a bike is a 2d coordinate on a grid like this we assign one unique bike to each worker such that the sum of the Manhattan distances between each worker and their assigned bike is minimized return the minimum possible sum of Manhattan distances between each worker and their signed bike the Manhattan distance is and I think this uh is used in a lot of problems it's just the absolute value of the difference of the x's and the absolute value difference of the Y's so if we take a look at the examples here's one example where you have two workers and two bikes so you can kind of tell by like an IT test what you'd want to do here so you'd want to assign this worker to this bike which would give you Manhattan distance of three and this over here would give you another Manhattan distance of three right one two three and in the second uh example you can also kind of like it test it so this will give you one then this will give you another one and then this will give you two so that's the shortest so that's four total and there's a third example but that number is like way too big and kind of useless so I didn't show it here but anyway so the constraints are we can have n workers and m bikes and basically you will have um the number of bikes will at least be equal to the workers and they will both be 10 or less and then basically they just show you that like you'll have an array in workers that every element will have an X and Y and same thing for the bikes and here are the values which isn't super important and all the bikes and uh workers are unique so you don't have to worry about like duplicates or anything so basically you have to assign a bike to each worker and there might be more bikes than workers and we have to minimize this distance and from the constraints um and just from like looking at the problem you should try to get to the conclusion that which is like reasonably obvious that or maybe there is something better but there isn't like some super good way to do this right because the constraints are really small and it's a medium problem so the chances are there isn't some way to do this like super efficiently um so one thing you can think of is just doing like a backtracking right where you would just basically just try to guess which worker will get each bike you just try like all combinations right you just try to like assign a bike to a worker and then you try to assign another one and so on so what's that going to look like so let's say worst case we have 10 workers and we have 10 bikes so basically what that's going to look like is it's going to be something like every worker will get um a bike so the first worker you'll have to try 10 bikes and then for the second worker there will be nine bikes left and then for the third worker there will be eight B bikes left and then so on and so on so this is basically 10 factorial which actually if we Google it is small enough to pass so that's one way to do it and so for this type of problem there's usually two ways of doing it so I'm going to do the less intuitive one um so backtracking you could do that where you basically just backtrack and you just try to randomly assign not randomly but try to assign bikes to the workers so you can just have like a normal backtracking template and do that but we're going to be doing a DP solution and so for DP we need a couple things right so we need State base case and recursive and so this is a good one for DP to practice because the state isn't super obvious right like how do we keep track of like what state we're on what's our base case and so on so when you can keep track of basically we want to know for each worker we want to assign them a bike but when we assign them a bike we want to make sure that bike is no longer available so we can write that down for each worker try to assign a bike from a available bikes and then recurse to some state where that bike is no longer available okay and this is like reasonably common it's like a little bit tougher version of a DP problem so you basically have a small number of items that you need to distribute right you can only have 10 bikes and once you give a bike to someone once you say like I used it I need to make sure it's no longer available and how do I have a state that represents that so the way to do this and this will only work when you have a small number of bikes but in this case we do is using a bit mask so essentially we're just going to say for our bikes we are going to initialize it to like let's say we have 10 bikes we'll just have or let's use a smaller thing to demonstrate e say we have five bikes we can just have something like this where these are the bikes and then anytime we pick a bike and we're actually going to index them backwards so if our bikes are you know zero index one index two index three index four index uh we will index them backwards so if this one's available this will be index 0 1 2 3 and four and essentially what we do then is if we say we want to use the bike like let's say we're going to Loop through these numbers backwards basically and the way to do this the way to check each bit is you just take a one and you shift it by some number to match what bit you want so let's say for example uh we can actually show this with an array so let's say I have like I said we'll just have five bikes so let's get rid of five of them and let's have it like this right and this will represent index 0 one two three four of the actual bikes are it be backwards essentially you just take a one and you shift it by the index and then you will have a one in some location so let's say I wanted to be at this location over here I will shift it by two then I'll have a one here right and so what I really want to do is I want to check if this bit is on but I need to make sure all the rest uh don't matter right so the way to do this is you just and these two things and when you and basically these the rest of these will be zero so when you and uh anything ended with a zero be zero so every other bit will just be zero and then this will be a one if this is on and if it's a zero then will be a zero and then you can just check like if this thing ends up if this is non zero then this bit is on so if that bit is on then you can use that bike and if you want to turn it off like let's say this is on you want to turn it off the way to do this is the same thing and one with the shifts right so you'll have something like this now what think about what bit operation you'd want to use to turn just this bit off but keep the rest the same here you'd want to use an X or right so any anything X word with zero stays the same so this will be 1111 or whatever it was and this together will be zero so that's how you turn it off and the check use an and so that's what we can do so for our state now that we know how we can represent our bikes because we don't want to have like an array of available bikes we can just have a bit mask and we just turn it off if we've used it so for one of our state variables we will have bit mask of bikes and the other state is just going to be the worker we are on right so we want to go through all of the workers and we want to try to just assign every bike to every worker that's available we'll just try all of them and then whatever gives us our minimum result is what we will go with so our base case here is pretty straightforward it's just when we are out of workers right so when we went through the whole workers array then what should we return this is kind of St for we want to return zero because we're not assigning anything there and the recursive case is just going to be try to assign an available bike to current worker Mark bike unavailable and recurse and what's the value we're going to have like what's that going to look like when we recurse so that part what we're going to add here is we are going to add Manhattan distance of assigning bike to worker right plus the D the DP of their curs of state which is just going to be like whatever index on the workers were at plus one and the new bit mask and we can just start with our result and I'll show that in the code we can start as our result being like infinity or something and then we can just return the minimum that's kind of how you do this it's a little bit tricky but that's this is reasonably common when you have um some kind of thing that you want to assign and then you want to turn it off so then the next person can't use it and you don't have too many of them right cuz if we had like a 100 bikes we can't use 100 bits cuz that would be too big but for something like 10 or 20 or something that works pretty well so now we can code it up kind of uh I think I explained most of the work for it so let's take a look so what we're going to do is we're going to have a cache for normal DP then we're going to keep track of the length of bikes so make a variable for that and we're going to have a DP so there's going to be two uh states that we care about W which is where we are in the workers array and then we can use like b or something as our bit mask or we can call it like mask okay so basically if W equals length of workers that means we have no more workers to assign bikes to so we can just return zero because the cost of assigning nothing is nothing now the next thing is what we want to do is the cache case right so if W mask and you can have the same state multiple times let's say you try to assign like you're on worker zero and you assign them the first bike and then you recurse down to worker one and you assign them the second bike uh that's going to be the same thing as assigning the bikes in the other order because from where we're at we just want to know the cost of assigning all the bikes left or sorry assigning bikes to all of the workers left so the previous step doesn't matter so you will have uh same States in here so you do want to have a cash so we just return cache going W and mask okay now we can initialize our result to Infinity cuz the strategy is if we want to minimize we just make it Infinity now basically what we want to do is we want to go through all of our bikes and we want to check is it available and if it's available we want to try to assign it and recurse and we just want to get the minimum one of all those so we can say for I in range B and remember this is going to be backwards so the mask if the mask is like this let's say this is index zero this is index one and so on right because we're going to shift an i that's going to start over here so it'll be one and we're going to shift it to the left some bits so this part is just going to be if um the actual bit mask so mask and I or one shifted uh left I bits is non zero that means that bit is on that means I bit is on so we want to use the I index in this worker or in the spikes array so we will try to minimize our results so we'll say res equals minimum the old result and then we want to get the Manhattan distances right so it's going to be the absolute value of workers yeah and then what's the index in the workers well the work the index in the workers is our current W index and then we just want the x value here minus bikes and then which bike is it so it's going to be bikes High y i z and then you want to add the same thing for the Y values right so this is the x value difference now we just need the um y value difference so we will add those together so same thing for the Y values okay and so it's these two things right this is the manhatt distance plus the DP of the recursive case so the DP of the recursive case is you go to the next worker and then you want to take the bit this bit over here and you want to turn that off now and remember that's just uh taking this and doing this right so it's just mask xor one uh shifted left High bits because that will turn it off okay and then finally once we get our minimum result and there is always going to be a result because there's guaranteed more bikes than workers or the same so you'll never like end up with infinity here or anything but you will try to minimize it so then you just say cach um this is going to be W mask equals result and return the result and finally so what do we want to initialize this to so obviously the worker is zero but what do we want to initialize our bit mask so remember we want it to be all ones so if you have um let's say you have five like uh your bike is length five you want to have something like this right so what ises this equal to so this is always the case whenever you have five ones that's always equal to two to the number of ones you have so in this case 2 5 minus one because 2 5 is basically one and 5 zeros five zeros so this minus one will be zero and all of the rest of these five zeros will turn into ones so that'll be this so what we want this to be is two and this is pretty common as well to get this like pattern of all ones it's just two to the length of the bikes so this is going to be uh I think we have B here and yeah it's going to be this minus one so that'll give you the same number of ones as the length of the bikes and that should be it so let's take a look um oh wait can close that see yeah and then as far as the run times once again um it's kind of a reasonably fast run time so if you just run it a bunch it like speeds up or slows down or whatever so I think I the most I got it I can look it's like let's take a look yeah so I think I got it to like adms with the same solution so it's kind of like all over the place again but pretty good it's also very hard to analyze runtime of um DP versus uh versus backtracking because backtracking is usually inefficient and kind of hard to analyze because it's like it's usually like two to the end times something kind of hard to say or like some factorial thing it's kind of hard to say like what's better like some factorial function or s like 2 to the n 10 n squ or whatever you all um and obviously the El code solution like run times aren't the don't really show you um too often how fast your thing is unless it's I think I talked this about this before so like let's say you submit this and your solution takes like 4,000 this and your solution takes like 4,000 this and your solution takes like 4,000 Ms or something and then there's solution that takes like 200 then obviously there's something better but if they're roughly the same then it doesn't really matter okay so let's look at the uh runtime for this so essentially W is going to be the length of workers so we'll call that like o w and then the mask is basically two to the number of bikes so that part is that and then we are also looping through every single bike in bike so this will be like w * B bike in bike so this will be like w * B bike in bike so this will be like w * B probably so I think it's something like this W * B * time two number of bikes this W * B * time two number of bikes this W * B * time two number of bikes but because these are only 10 it ends up being like 10 the 5th or something total which is fine um and for the space so this is just like normally the cache which is just W Times the uh two to the number of bikes and yeah so I do think this is a good one to learn I think uh this bit mask stuff comes up reasonably often to be honest in the harder um DP problems so I definitely think you should learn how to do it and use it and if this is helpful please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
Campus Bikes II
fixed-point
On a campus represented as a 2D grid, there are `n` workers and `m` bikes, with `n <= m`. Each worker and bike is a 2D coordinate on this grid. We assign one unique bike to each worker so that the sum of the **Manhattan distances** between each worker and their assigned bike is minimized. Return `the minimum possible sum of Manhattan distances between each worker and their assigned bike`. The **Manhattan distance** between two points `p1` and `p2` is `Manhattan(p1, p2) = |p1.x - p2.x| + |p1.y - p2.y|`. **Example 1:** **Input:** workers = \[\[0,0\],\[2,1\]\], bikes = \[\[1,2\],\[3,3\]\] **Output:** 6 **Explanation:** We assign bike 0 to worker 0, bike 1 to worker 1. The Manhattan distance of both assignments is 3, so the output is 6. **Example 2:** **Input:** workers = \[\[0,0\],\[1,1\],\[2,0\]\], bikes = \[\[1,0\],\[2,2\],\[2,1\]\] **Output:** 4 **Explanation:** We first assign bike 0 to worker 0, then assign bike 1 to worker 1 or worker 2, bike 2 to worker 2 or worker 1. Both assignments lead to sum of the Manhattan distances as 4. **Example 3:** **Input:** workers = \[\[0,0\],\[1,0\],\[2,0\],\[3,0\],\[4,0\]\], bikes = \[\[0,999\],\[1,999\],\[2,999\],\[3,999\],\[4,999\]\] **Output:** 4995 **Constraints:** * `n == workers.length` * `m == bikes.length` * `1 <= n <= m <= 10` * `workers[i].length == 2` * `bikes[i].length == 2` * `0 <= workers[i][0], workers[i][1], bikes[i][0], bikes[i][1] < 1000` * All the workers and the bikes locations are **unique**.
Loop over the array and check the first index i such A[i] == i
Array,Binary Search
Easy
null
1,680
hi everyone welcome to my YouTube channel and in this video we will look at problem 1680 from the code so the subject the title of this problem is concatenational consecutive binary numbers and the person you see on the left hand side is live needs I don't know his first name he was the German mathematicians and maybe at the time I think was here I think was Germany or maybe it is called Prussia but anyway he not only invented binary system but also he was the inventor of well you can say calculus along with Newton so well that is for that for historical fact and let's look at the problem statement so here is the problem statement and pause this video for a second try to come up with your own solution so I will be using n equals 3 as an example to illustrate my you know my code for this problem so n equals three that means we have to consider 123 and then we have to apply you know we have to make those numbers those integers into binary representation and then in Python we will be using binary of I so we will be applying that so this one will become binary of one this one will become binary of two this one will become in a binary of three now you have to remember that when you apply binary say one um you not only get this one um you know this is a string but you also get like some two characters like I think it was zero B so you we do not want them so that's why we have to apply this you know slicing here so that we only care about the numbers like except the first two letters so that's what's going on here and then we will be concatenating here so s plus equals uh so yeah so s is an empty string and then we will be you know building our con yeah our string for this so for if you look at this one we have one and one zero we will be concatenating those two guys and then we will get one zero and then we will be concatenating this guy and this guy so we will get one zero one now after that we have to you know return the numbers so we have to return the what is it the decimal value of the binary string and that we have to also take the modular so here we have a modular modulo equals 10 to the power of 9 plus 7. so that part is like we cannot we can always you know take the modular in the end how do we get the decimal value of the binary string uh if you look at int function in the python we have like you know where we have say if we are given a integer trip like some numbers say 3.5 and then we like some numbers say 3.5 and then we like some numbers say 3.5 and then we put int of 3.5 that will give us three put int of 3.5 that will give us three put int of 3.5 that will give us three so that function it also has this property so s can be in this case will be some number right and then we have this um the representation in this case would be 2. so what this function does is this one will return the decimal value of the binary string so if you say if you have int 11011 and then we have two here that will give us um you know 27 right and then we have to take the module but in this case since this number is you know smaller than this 10 to the power of 9 plus 7 that doesn't really affect this one but when you have like very big number like n equals 13 15 then this one will become handy um so that's for this problem and let's look at the code for this so this is the exactly same code that you just saw and let's try to run this together and see what we get so that's for this problem and hope my video helps you guys understanding this problem um I think this problem you can also use you know like beat manipulation because all this yeah this one if you look at this approach you can also come up with a bit manipulation to solve this problem um I think that has about the same time complexity but um I think if you want to try practice speed manipulation then you can try that on your own or I can you know have a separate video on this I still don't forget about you know how those string matching algorithms so I'm making a video on those topics and also I don't forget about numerical linear algebra so just um pair with me you guys and I will try to create like really uh great videos for this um because well anyway that's for that um just hope my video helps you guys and well have a wonderful you know weekend um I will see you next time bye
Concatenation of Consecutive Binary Numbers
count-all-possible-routes
Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation: ** "1 " in binary corresponds to the decimal value 1. **Example 2:** **Input:** n = 3 **Output:** 27 **Explanation:** In binary, 1, 2, and 3 corresponds to "1 ", "10 ", and "11 ". After concatenating them, we have "11011 ", which corresponds to the decimal value 27. **Example 3:** **Input:** n = 12 **Output:** 505379714 **Explanation**: The concatenation results in "1101110010111011110001001101010111100 ". The decimal value of that is 118505380540. After modulo 109 + 7, the result is 505379714. **Constraints:** * `1 <= n <= 105`
Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.
Array,Dynamic Programming,Memoization
Hard
null
1,743
hi everyone it's albert today let's solve the contest median question restore the array from adjacent pairs and before we start don't forget to subscribe to my channel i'll be constantly solving good and classic clinical questions with clear explanation animation and visualization now let's look at a question for this question there is an integer array numbers that consist of unique elements but we have forgotten it for some reason however we do remember every pair of adjacent elements in the original array and we are given a 2d integer array adjacent pairs of size -1 and that of size -1 and that of size -1 and that each item in adjacent pairs is an array of two elements uv that it indicates the elements uv they are adjacent in the original arrays numbers and it's guaranteed that every adjacent pair of elements num psi and nums i plus 1 they will exist in adjacent pairs array but the pair can appear in different order so given a json pairs array we have to reconstruct and return the original array numbers and if there are multiple solutions we can return any of them so for example one the adjacent pairs array is 2 1 3 4 3 2 and the original array is array 1 2 3 4. an example 2 the adjacent pairs is 4 negative 2 1 4 negative 3 1 and the original nouns array is negative two four one negative three and for example three the adjacent pierce array only has two elements so that would be exactly the original numbers array and data constraint the length of the adjacent pairs array can go up to 10 to the power of 5. any intuition to solve this question the first step is to build a graph data structure which is a hash map from adjacent pairs and in this hash map the key will be every node or every item in the nums array and then a value will be the left or right neighbor of that node in the nums array and next we can use dfs that first search to reconstruct the original numbers array from the graph so the main data structure to use for this question is graph which is also a hash map now let's look at the code okay and first step is to create the graph hash map and here we can use python's collections default dictionary to create a graph g and then we will loop through adjacent pairs array and then append the node and neighbors into g and next we have to find a starting point and the starting point can be either the head or the tail in the nose array which is the first or last element and once we found the head or the tail we will make it the starting point and next we will need a visited set to check at which nodes have been visited and then the rest array to append the nodes and then return at the end and finally is to dfs into the graph and then append the nodes into rest and return at the end now let's see the code in action okay and here we'll be looking at example two the input adjacent pair is four negative two one four negative three and one so with a given adjacent piece array we can create a graph looking like this and you can notice that key negative 3 and negative 2 they only have one neighbor which means that they are either the head or the tail in the original array so we can pick either one of them to be the starting point and here we'll pick a negative 2 as start and next is to start dfs and the first dfs call is dfs negative 2 and negative 2 will be added into visited since it has been visited and then append negative 2 into rest and the next dfs call is the neighbor of negative 2 which is 4 and at dfs 4 following the same process we will add 4 into visited and rest array and the left and right neighbor of 4 is negative 2 and 1 and negative 2 has been visited so you will be skipped so the next dfs call is dfs1 and at dfs one again add one into visited and rest and the neighbors of one is four and negative three four has been visited so the next call is dfs negative three and at dfs 3 the same at negative 3 into visited and rest and up to here we have visited all the nodes in the graph so we would return a rest negative 2 4 1 negative 3 which is the output for this example and this will conclude the algorithm finally let's review so the main idea to solve this question is to build a graph hash map from a json pairs array and the key of this hash map is a node in the array and then a value is the neighbors the left and right neighbors of that node and then we can use dfs to reconstruct the original nouns array from the graph so the main data structure to use for this question is a graph data structure which is also a hash map and time and space complexity of this approach are both linear and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one
Restore the Array From Adjacent Pairs
count-substrings-that-differ-by-one-character
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Hash Table,String,Dynamic Programming
Medium
2256
212
welcome back to algojs today's question is leak code 212 word search two so given an n by m board of characters in a list of string words return all words on the board so each word must be constructed from letters of sequentially adjacent cells where adjacent cells are horizontally and vertically neighboring the same letter cell may not be used more than once in a word so let's have a look what our first example looks like so we have an m by m board with a number of different characters within it and we need to find if any of these words right here exist within the board we have f which starts at the first position and ends right here and we have eat which is backwards over here so there are two words within the word re that can be found within the board so we return those as the output in terms of implementing it i would say it's very similar to number of islands but there is an extra level of complexity to this because we have characters as opposed to zeros and ones so in order to make this as optimized as possible what we could use is a try data structure to store all of our words in the dictionary so firstly what we need to do is create our tri data structure with these words the tri-data structure looks like words the tri-data structure looks like words the tri-data structure looks like this so there is nothing within the initial position and then we create the try so we've traversed down earth and we've put that within the try and at the bottom position what we usually have we're going to try is a flag of some sort to say that this is a word but instead what we're going to have is word equal to this entire word so it's essentially going to be equal to oath so we've checked over now we can go to p so p e a so now we can just add eat and rain to the try and this will make more sense in a minute when we start dfs in through this 2d array as to why we've done this so again word at this point at a is going to equal p word here is going to equal eighty and word in this section is going to equal brain okay so we've created our tri data structure now we can start carrying out the dfs on this tree so let's start the first position we have an o so firstly we need to check if o has the word attached to it in this case it doesn't so we can start looping through so we can check to see whether it's in the first position of our try so is it equal to p e r o well we have the o right here so at this point we can dfs to the next position right so up right down and left so there are four possible positions but we have to check if it's inbound so this and this are invalid because it's not inbound right so across this way is j is less than zero up this way i is less than zero we also have to check whether it's too far down this way so i is greater than board dot length minus one we also have to check whether it's too far over this way where it's board j is greater than board at i dot length minus one right so we need to check whether it is valid to begin with so that's the first step to check whether the positions are valid also we need to check so say we went to e is not within the next position of this tri so this descendant of o is not equal to this value so we cannot go down this way so the only position we can go is to this a because it's equal to the a within the tri so we can dfs at this position so we can go up right down and left so we can't go up because that's out of bounds we can't go right because the next value within the tri is t and this is equal to a so we can't go that way can we go back well we've already visited o so we can't go this way so we need to make an adjustment for this and the way we do that is we could use either a visited flag so we could have visited and pass in all the positions that we have visited so we could pass in zero but this increases your space complexity so what we're going to do is we're actually going to just set this value before we finish this section we're going to set this to an arbitrary piece of data so we're going to set it to a hash so it's no longer equal to an o so we never go back to that position then we can go to t we can dfs at that position so we can't go back because we set this a to a hash we go to t we try go to e we can't go to e because the next position in the tri is a h we go to a we can't go to a because it's a h so the only position we can go to is this value right here now this value has word attached to it okay so it has a dot word attached to it and if that is the case then we push this value so we're going to add this value to our result so we're going to have a result array and we're just going to push in both now we want to stop this from being duplicated again so what we can do at this point in time is we can set this to null now because we have found it so if there's two positions where there is oath within the board we're not going to get that now because we have set this word to not great so at this point what we need to do now is we need to backtrack because we found this value we need to go back up because all these values are currently a hash right we need to reset this board right so we need to reset this to a h we need to reset this to a t this to an a and this to an o so we can go ahead and do that so now that we've done that we can traverse through the board so we can check at position a is that within the first position of the try no it's not so we can move to the next position again a is the same so we move to n is not found within this first level of the try so again we move along e is found within it but if you see if we traverse or dfs through e the next position is a and we don't have this so we can move on to t is not within the first position a is not within the first position we go to e is within the first position so we have this e so we check is word attached to it no it's not white is not attached to it word is attached to the t down here so we can carry out dfs on this we can't go this way because it's out of bound we can't go to n up here we can't go to r down here we can only go to a because the second position within this try now is a and before we move over to a remember we need to convert this to a hash so that we don't go back to him we go to a with dfs at a we can't go this way because we've converted e to a hash we can't go to a up here we can't go to k down here we can only go to t because the next value in that try is a t so we check at t does this have a word property yes it does so we can push in that value here into our result array and then again we need to clean this up so we need to convert the hash back to an a hash back to an e so that we can carry on traversing through the board so i h k and r if we look at the top level the only one that we can find is r and all its next positions if we dfs in all directions do not equal a so we can move on i f l and v unlocked within this first level either so we can end this and just return our output the result here so that's the basis for solving this problem tonight complexity in this case so say we had a board that looked something like this and we were at this position and the words we have to look for are a and treble a how many steps can we take from this initial position well firstly we need to loop through every value within this board so time complexity is going to be om where m is the number of characters within the board and if we're at position a within the middle here what is the maximum number of positions that we can go to those are inbound and valid it's four so it's going to be four times what is the maximum number of positions say we had extra a's added on down here what is the maximum number of positions that this a can go to well it's going to be three in this case that are inbound and valid so it's going to be three and it's going to be to the power of l minus one l in this case is the length of the words within the try so that is the time complexity so space complexity is going to be o n where n is the amount of characters within the try so firstly we need to create a function called build try which is pretty self-explanatory because which is pretty self-explanatory because which is pretty self-explanatory because we need to obviously create our try so to start off the try we're going to have root which is going to be equal to an empty object we're going to loop through the words we're going to get the current node we're going to pass it as a reference to root then we're going to loop through the characters of the word okay so if current node at the character it's equal to null then we can just say current node at character which is equal to an empty object so we're just creating an empty object that's that current node at position chart otherwise we can traverse through and then once we've reached the end and we built this tryout we need to add the word property and the word property is going to be equal to the word so the word that we've looked through within these words just so that we can return this within our results and finally we need to return root so within the main body of the actual function we need to initialize result which is going to be an empty array we need to create or we need to build out the try so let's call it root and we can say build try and we can pass in words then we need to loop through the board to initialize the dfs so moving through the rows looping through the columns and then within the dfs we're going to pass in the root so the try that we've just created i j gonna pass in board and we're also going to pass in result and pass in board now we need to create the dfs function so dfs we can call the root node i and j can stay the same as well as resultant board so the first thing we do within our dfs function is check whether the position or whether the node has the word property attached to it if it is we know we found a word within the board so we can push node.word the property which we created node.word the property which we created node.word the property which we created down here which is equal to the word that we loop through we can push that into the result array and then we need to set the word property to null and the reason i stated in the solution was because we cannot have duplicates so say we found h here that's gonna have the word property attached to it if there was another oaf within this board the h on that would also have the word property attached to it because it's the exact same word within the try so we need to set that to null so that we don't have duplications within our final result then we need to check whether the value is inbound so if i is less than zero i is or j is less than zero that's out of bounds if i is or if i is greater than board dot length minus one or j is greater than board at zero dot length minus one we can return so these are all out of bound if node board i j is null we can return what this is saying is if the position in the board is not found within the try just return because that isn't a potential path now we need to stop an infinite loop from occurring so we create a reference to board ij and we'll explain what this is for in a second we set board at i j to equal the hash and this is to stop an infinite loop so we don't go back to the previous value which we've already looked at we need to carry out the dfs in all four directions now so we know that c so know that board i j result and board now we can copy this three more times and we just need to change the direction so i plus one i minus one j plus one j minus one okay so once we've dfs for all of the positions and we've checked the board and they've all returned a value we need to reset border ij so that's where c comes into play so board at i j is currently a hash and we need to convert it back to the value to carry on traversing through each value within this board so we just set that back to c and then finally we need to return result that's looking good let's give this a run okay let's submit it and there you go
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
3
So today we will see Longest substring without repeating characters is a good problem and they have two output D. If there is longest substring without repeating characters then it has ABC. Longest ABC is right. If ABCA is not there because there is repeating character then the answer is it has all one. So there is one, there is 3 in it, which is blue, okay, so we will solve this problem by doing dictionary, okay , we will do , we will do , we will do zero, when is it added, we got the string of ABC and we will enter R in it, reset. It is also possible that E may become something else in the future, okay, so once we repeat A, we will increase the alcohol further and bring R back to L, you will also check, okay Remove tempera wala What does it mean, okay, if we have reset it, then what will be the length? Now, whatever is our dictionary, we have not taken a condition in it which would be that the Deputy Collector is never there, otherwise the character will not be lost if it is a reporting character. So it will go into it, ok, submit this correct SIM, this is the solution.
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
153
we are going to solve find minimum and rotated sorted array today this is the medium kind of problem let's look for our problem statement we are given an array of length n which was initially sorted in ascending order then it's got rotated now we have this rotated array with us so what the rotation means if initially we have an array zero one two three four five six seven if we do it for the first time our array will look like our 7 will come up front then we have 0 1 2 4 5 6. this is result after one rotation if again we rotate it will look like so this is our third rotation so after fourth rotation it will look like something like this now we need to note that all the elements are unique in this area and we need to return the minimum element of this array and we need to write our algorithm which runs in four login time telling us that we need to use the binary search because when we use find research then only we can get our time complexity to log in if we can use a linear time it's very simple we are going to traverse whole array and see which is the minimum and will return that element as our result but we need to implement it in login time if we have a sorted array and we try to plot our sorted error in a number range graph of that sorted array will look like something like this it will give us a straight line because all the elements are unique but here our array is rotated by m time so this means now our new array after rotation our number from 0 to let's say rotated by m times so this is 0 to m this is m plus 1 till n now we know how our binary search work basically in binary search what we do we just find the we have a defined range this is our sorted array let's say so this is our left and right and we need to find our target okay target is x so firstly we try to find the mid value after finding the mid we try to compare with the target if our mid value is smaller than target it means that our target will lie in this range from mid to mid plus 1 to right our target will be in this range because this is a sorted array so all the elements from left to mid will be smaller than this mid value and our target is greater than mid so there is no way that our target is going to lie in this range so we don't need to search in this space we need to decrease our search space so what we can do here we can just make our left to mid plus 1 because we know our target is greater than mid now the second case could be our target is smaller than mid this means that our target is not going to be in the range of mid to r because our target is smaller than mid so we need to look for from left to mid minus 1 so we need to update our right pointer to mid minus 1 and keep repeating over this step until we find our target so this is the basic of binary search now we try to modify this condition so that we can find the minimum element in this rotated sorted array so this is our left this is our right that is this is our zero index this is our n minus one so firstly we will try to find the mid value because we are going to apply binary search here so let's suppose our mid life somewhere here so this is our mid then we are going to compare this mid with our right because all the numbers are unique if our mid value greater than right this means that our minimum value will lie in the range of mid plus 1 till out this means that our number in this right part are smaller than the mid value there is no possibility that it could be in the range of left to mid because this left to mid will contain the numbers greater than our minimum now the second condition could be our mid is lying this is our left this is right our mid is lying in this right part itself so when we compare our mid and right our mid value is smaller than our right value this means that the smallest value is not going to be in this range because all the numbers in this range is going to be greater than the mid value so we need to look for the value in the range left to mid so here we are going to set our right pointer to mid so we have just two rules if firstly we are going to find the mid value after finding the mid value we are going to compare with the right value we are going to compare the right hand side value if our right hand side value is a smaller this means that our smallest value is not going to lie in the range left to mid it is going to fall in the range mid plus 1 to right so we are going to shift our search space from mid plus one to right and the second case could be our right value is greater than our mid value this means that our smallest value is not going to lie in the range mid plus one to right so we need to shift our range so we are going to set our right pointer to write is equal to mid okay so it's very simple let's code this problem we are going to apply binary search so firstly we need to declare our range for the binary search so let's get the size of the array and let's declare the range of our binary search now we are going to start our binary search so these two lines are the exactly same as we do in our binary search in normal binary search we check with the target value but here our target value is the minimum value so if our middle value is greater than our right most value it means that our minimum element is going to lie in mid plus one till r it could be anywhere in this range so we need to shift our left pointer to mid plus one otherwise it means that our medium value is not going to lie in the range of mid plus 1 till r because mid plus 1 till r is greater than our medium value so our minimum value will be in the range of left to mid so we need to shift our right pointer so that we can cut our search space now at the last we are going to return nums left so that's our code let's run our code okay so let's run for example test cases okay so it's good to go let's submit our code okay so it's efficient space complexity is also good so yeah that's it for this problem we took login time to solve this problem because it's a binary search and we are not taking any extra space here so that's all for today see you next time
Find Minimum in Rotated Sorted Array
find-minimum-in-rotated-sorted-array
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become: * `[4,5,6,7,0,1,2]` if it was rotated `4` times. * `[0,1,2,4,5,6,7]` if it was rotated `7` times. Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`. Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_. You must write an algorithm that runs in `O(log n) time.` **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** 1 **Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times. **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\] **Output:** 0 **Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times. **Example 3:** **Input:** nums = \[11,13,15,17\] **Output:** 11 **Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times. **Constraints:** * `n == nums.length` * `1 <= n <= 5000` * `-5000 <= nums[i] <= 5000` * All the integers of `nums` are **unique**. * `nums` is sorted and rotated between `1` and `n` times.
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go. Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array. All the elements to the right of inflection point < first element of the array.
Array,Binary Search
Medium
33,154
648
hey how'd our today I'm looking at the questions 648 to replace words so the question is as follows in English we have a concept I call the root which can be followed by some other words so the root is a word the root word can be followed by some other words to form another longer word that's called this word successor so the successor is the longer word that formed by concatenating two words the first word is called root so for example the root and followed by other can form another word I just so happened that another word is another so I think the end here should be prefix the other here is the actual root for this word so I'm just gonna do replace words myself for about this question description I will replace all those roots with prefix so keep reading now given a dictionary consist consisting of many roots many prefix and a sentence we need to replace all the successors in the sentence with the prefix forming it if a successor has many prefix conformant we will replace the word with the shortest prefix we have so that's best what the question is asking looking an example we have the sentence the cattle was rattled by the battery and we have three different prefix cat bad and rat so we'll replace Caro with cat replace rattled with rat and replaced battery weighs bad there is no word with multiple prefix so there is no conflicting about there is no need to see which prefixes shortest or something like that you miss example so basically for this question we're just going to chop this sentence into inch limited individual words and map this wording to some kind of replacement function in that function we're just gonna check the word we are search for I will try to do replacement with the other prefix we have if we do find exactly one prefix that the word starts with then we return that prefix if we find multiple prefix maybe we have CIT C cat or a single C we return this shortest one so for this case whoo if we do have another C as the prefix we return C so if we don't find any prefix we just left and leave the word unchanged just return the original word so we map that they replace function to all the words here and click to the result and pieced them together that would be the approach to solve this problem so the only thing here is that how we're actually going to code this replacement code to have that to be more efficient of course we can do the blue force to just try all the pairs and all the prefix and just try to see if the word starts with those but the a better approaches to create a try for all the prefix so that all we need to do is to just traverse inside to try using the characters in the word so if we do find a try node which with the with a terminal termination flag and a port flag that means we have a prefix that matches the word we are looking for so in that case we will just return the pass in the try that leads us to the termination of lab so if we do have a trial here in this question we will have a pass that's route C 80 if we search for Cairo inside the try would follow the route to node C node a node T and no T we have an end of word flag so with that flag you were indicating that the path from root to that node C 80 or it's just the past we the characters we'll look at from the front the word you know until the time we see the flag is a actual prefix that matches the word so if we use a try it would just be linear time search with respect to the lens of each individual word and for the whole sentence it would just be linear with respect to the length of the sentence that's the run time complexity of use to try so but used Phi we have additional time and space complexity to create a try the try is going to be the size of the input dictionary in terms of both the time to construct it and also the space to store it but with that the search for the replacement in a sentence will be linear with respect to the length of the sentence so if the sentence can be super long using in a try could be more efficient so that's a pretty much the big idea about using try to solve this problem yeah so let's close this off I'm just going to maybe code the bigger idea first and then try to finish the details so we initialize a tri data structure create an object or from the class and just before I would do a little bit change there I think this should be prefix okay I'll code a insert function for the try to insert a pass that cost value to the prefix so that's a that takes that take care of that try search and then we're just going to return space join together all the worst I've been passed into some kind of a replacement helper function so that's the workforce of the workforce for this problem is going to be this replacement function so you will take a word and try to return this replacement so for this we're just gonna traverse inside the try for I character in enumerate over the characters in the word character by character if the character is not in the try node that means the current to pass inside the try is not a valid prefix for the word so in our case we'll just return the word itself we don't do any replacement and this joint here we'll put that back put that work back into the modified sentence otherwise we will just keep reversing once we move to the next node we want to check do we have an upward flag if we do have one that means the path right now is the prefix for this word so since we also have an int index generator here you know we iterating over 2 pairs of index and character so from the beginning towards here is the actual prefix so we just return this so that's the replacement - of course - to the replacement - of course - to the replacement - of course - to facilitate this we have to actually code up at the wide area structure so here our constructor is basically a creative empty root node define this node object inside the try class which I would just stare as my code yesterday are just gonna subclass the default dictionary and we will have a kind of flag that end up war flag for this new so everything has to be false its initial to be false so that's the try node and the constructor for the try all we need is to have this insert function the search function is implemented inside the solution carrots so we basically just for all the prefix we have we will try to insert that into the try and at the end of each prefix we will flag that to be the end of the word so when we actually search for the word if we just follow the character by character in the world if we find it and a wonderful word flag inside the try note we will return the portion of the word along until the point so I guess we'll move this onto the try right so I would just call this search now or replace is fine so or just replace this with South our route yeah so that's so I would just call this tried or replace okay let me see if I have honest problems so this replace function I just gonna start off on the route enumerate over character by character inside this word so it will be something like ca TT le so the first iteration we grab C which the is 0 and we see do we have a C note after the root which we do have 1 so we will just move to that node and test the do we have an end of word flag obviously we don't so we keep in the cube to then move to the next character which is a and just keep going on till we find character t if we find the character T the node would have an end of war flop so we return the portion of the search word opponent in that position so it will be CIT the actual prefix so it looks pilots if I run it I was working not working what's the problem okay I see I should convert this to list I guess so the map object is non type so why is that what's this test case so it's a lot of prefix and the search world are quite long what do my code outputs the expecting string instance forgotten on type so which is the problem here mr. Schneider if I split by space the we do have a bunch of words could it be that after this full loop I'm not returning anything so I don't have neither the end of word or oh it could be that my word is actually shorter than a prefix so that I do have partial March with the prefix but I don't even meet the shortest prefix so the word is actually shorter than the prefix so let's if we have a single character like see here inside this input sentence the replace will return nothing ok so to catch that we just return word in the US that lost the resort so I don't need this map right I don't need this list the conversion right so let's see yeah this time is working so yeah this return here handles the case let's try this okay it's working so that's the twice solution so with the try implementation the code is really simple the rant is that linear with respect to the size of the prefixes we have in terms of bonus time and space to you know to populating the try and also to store the try for the replacement part it's a linear waste of s with respect to the impose sentence size so yeah so that's the try solution to this question 648
Replace Words
replace-words
In English, we have a concept called **root**, which can be followed by some other word to form another longer word - let's call this word **successor**. For example, when the **root** `"an "` is followed by the **successor** word `"other "`, we can form a new word `"another "`. Given a `dictionary` consisting of many **roots** and a `sentence` consisting of words separated by spaces, replace all the **successors** in the sentence with the **root** forming it. If a **successor** can be replaced by more than one **root**, replace it with the **root** that has **the shortest length**. Return _the `sentence`_ after the replacement. **Example 1:** **Input:** dictionary = \[ "cat ", "bat ", "rat "\], sentence = "the cattle was rattled by the battery " **Output:** "the cat was rat by the bat " **Example 2:** **Input:** dictionary = \[ "a ", "b ", "c "\], sentence = "aadsfasf absbs bbab cadsfafs " **Output:** "a a b c " **Constraints:** * `1 <= dictionary.length <= 1000` * `1 <= dictionary[i].length <= 100` * `dictionary[i]` consists of only lower-case letters. * `1 <= sentence.length <= 106` * `sentence` consists of only lower-case letters and spaces. * The number of words in `sentence` is in the range `[1, 1000]` * The length of each word in `sentence` is in the range `[1, 1000]` * Every two consecutive words in `sentence` will be separated by exactly one space. * `sentence` does not have leading or trailing spaces.
null
Array,Hash Table,String,Trie
Medium
208
376
hey guys welcome or welcome back to my channel so today we are going to discuss another problem is wiggle subsequence so a wiggle sequence is a sequence where the difference between successive numbers strictly alternate between positive and negative okay meaning the difference between uh alternate numbers should be alternate so if this is differences if this difference is positive then this difference should be negative then this should be positive this should be negative like this the first difference may be either positive or negative so this first difference like between the first two elements difference could be either positive or negative a sequence with one element and a sequence with two non-equal elements are sequence with two non-equal elements are sequence with two non-equal elements are trivially wiggle sequences okay for example this is a vehicle sequence why this is the vehicle sequence C difference between 1 and 7 minus 1 6 then 4 minus 7 is minus 3. then 9 minus 4 will be 5 then 2 minus 9 will be minus 7 and then 5 minus 2 will be 3. so see these are alternate differences positive negative positive so this whole is a wiggle sequence this is not a wiggle sequence because 4 minus 1 will be 3 and 7 minus 4 will also be 3. so both the differences are positive only so this is not wiggle sequence and this is y not wiggle sequence because the last two elements have different 0 and 0 that is not uh wiggled okay so it is mentioned here so a subsequence we know that subsequence is uh deleting some elements from the original sequence and leaving the remaining elements given an integer array so array is given to us and we need to find out the length of the longest wiggle C subsequence meaning alternate uh difference subsequence the largest length we need to just return in the output the length okay so I hope you understood the problem let's see this test case so here see what would be the maximum length back length what could be that just stop the video uh and try to think what could be the maximum length of this uh sequence where uh maximum length of the uh vehicle sequence the figure sequence so see first we can take one seventeen so this will be positive then we can take 5 so this will be negative then we can take 10 so 10 minus 5 will be 5 which is positive after 10 we should take 30 no we should not take 13 because 10 13 minus 10 will be positive 13 minus 10 will be 3 so that is positive and positive we should not have we should have alternate so there is no benefit of taking 13. so we can take 15 no can we take 10 no we should take 5. why we should not take 10 because then it will be 0 and we saw that we cannot do right so 5 we will take this 5 so 5 minus 10 will be minus 5. then 16 we can take 16 minus 5 will be what 11 which is positive and then 8. that is 8 minus 16 will be minus 8 which is negative so see positive negative and what is the length one two three four five six seven so maximum length is 7. output will be 7. all right see this test case output is 7. so I hope you got some idea uh see I'll give you some idea that how you can approach this problem as we see saw this test case right what we were checking see let's try run again let's uh again see how we can do it uh how we just find found out this length what we did was initially we have we were taking this one so we had taken this one and then we have taken the 17 and we saw that okay their differences positive so the next difference we should take should be what negative right obviously because this is positive so next difference which should take as negative so previous difference previous was positive right now we should take negative so if we have 5 here what will be the difference it will be minus 12 which is negative so we can take this 5 right so we can take this 5. now the previous difference will be what negative so here the previous difference is now negative similarly now the next difference we will uh find we will we should consider is positive because the previous was negative right it was negative so we will take this 10. because 10 minus 5 will be what positive 5. so now the previous will be 5 because we have taken this 10. right positive similarly now we will take we will now we will find a negative difference so should we take 13 no should we take 15 no because 13 or 15 will give us positive difference so we will not take 10 also so we will take 5 because 5 minus 10 will be minus 5 and we will we should because previous is positive right so now we should take negative and we found negative so something this we should do right based on the previous difference we should find the next difference okay so dry you do one thing try to Now using this approach try to dry run once think of the uh like this was the idea think of the approach what you can do using the previous difference so now let's dry in this approach right a very easy approach C what I will be doing right I will be taking two variables total three variables I will be taking one variable will be to store the count or you can say the length of the subsequence current one different one will be the previous what was the previous difference like the was it negative or was it positive and one will be the difference like this is the current difference to store the current difference okay so first of all see at least there should be two elements right at least two elements will be there so at least two will be the answer because 1 17 right or one like a single element or two elements so if there are two elements answer will be two if there is only one element so answer will be one right so this is simple okay so this is one thing now what we will do right at least see if there is if the length of this whole subsequence whole sequence right is more than two it means at least 2 will be the answer count will be at least 2 because we can take any two elements we can take this or this right no not this and this or this so if the if there is if the length is more than two at least 2 will be the answer I hope this is clear so initially count value I will take as 2 and what I will be doing is this is 10 uh so what I will be doing is uh here previous will be what previous will be this difference between nums of 1 minus nums of zero so nums of 1 is 17 minus nums of 0 is 1 so this will be what 16 so previous will be 16. difference right so this previous will store the previous difference and this difference will be the current difference so right now we will start our Loop right we will Traverse we will start reverse because we have taken these two so we will start traversing from two index that is from here so every time what I will be doing uh will be let me remove this so I will be doing these steps what are the steps first of all I will be calculating difference is what nums of I minus nums of the last element that is numbers of I minus 1. okay this is I right this is I so 5 minus 17 this will be what minus 12 so current difference is minus 12. so should we take this 5 right how we will decide should we take this 5 or not previous was 16 that is previous difference was positive 16 is positive right and the current difference is negative is this fine think previous difference was positive this is negative so it's fine right we should have alternate so we will take this 5. so if difference what is difference current difference is negative if difference is less than zero and previous is greater than 0 right 16. in that case we will do what count plus because this is fine right alternate this is alternate so we will increment our count that is we will take this subsequence so count will become 3 and what we will do now we should update the previous why because now this will be the previous difference so previous what we can do simply we can assign the difference value to previous that is for the next further iteration this will be the pre this now this will be the previous difference so that is difference will be equal to difference will be assigned to previous right so now what we will do 16 minus 12 will come here okay and I will move forward all right so I hope you got this thing now let's again do the same steps first of all we will find out the difference so what is difference 10 minus 5 so 10 minus 5 will be what five the difference is positive previous difference was what negative this previous difference is What minus 12 which is negative so again if difference is what positive greater than 0 and previous is less than 0 which is negative so is it fine yes it's fine these are alternate so we will again do the same thing count plus and now difference will be assigned to previous because now this will become the previous difference the difference was what five will be assigned to minus 12 here 5. okay and also I forgot to increment the count all right I will also move forward now I will come here now let's find out the difference 13 minus 10 will be what three so difference is positive previous difference is what again positive is it fine no this is not fine these are not alternate so we will not do anything that's not satisfy this condition does not satisfy this condition so we will not do anything and what we will do we will just move forward I will increment again we will find out the difference 15 minus 13 which is 2 so difference is positive and previous difference is what again positive these are not alternate so we will again increment again this will be what 10 minus 15 right 10 minus 15 so now what we will do um this will be what minus 5 right this will be what we are doing here 10 minus 15 so this will be minus 5 so current difference is what negative and previous was positive so this is fine right so we will increment count and we will assign the current difference which is -5 here difference which is -5 here difference which is -5 here to previous and we will increment so I will come here now 5 minus 10 will be What minus 5 this is negative and previous was also negative so this is not alternate so we will move forward now what we will do now again we will find out the difference 16 minus 5 which will be 11 so this is positive previous was negative so it will it is uh this condition this one so count increment assign previous so current is 11 so we will assign this to previous now we will move forward okay so I will come here 8 minus 16 now it will be minus a so current difference is What minus it's negative minus it in previous was positive so this is alternate so we will this will be set this is satisfying this condition so we will increment count 7 and we will assign this difference minus 8 to previous so out we have traversed the array whole array and the output is 7 count is seven so this is our output so I hope you understood the problem and the approach let's see the code once very simple problem just we have to keep a record of the previous right so if the size is less than 2 that is the answer we will find out the previous count we will keep and then we will Traverse this array okay and we will find out the difference and if it's see these are two conditions right but the this thing was same right so we have taken these two conditions and we have or in between and we are just doing the same thing and at last we will be returning the count so we have a single traversal right we are doing a single reversal so time complexity is O of n and space we are not using any extra space we are just taking variables so this will be space will be constant so I hope you understood the problem and the approach let me know in the comments if you have any doubt if you found the video helpful please like it subscribe to my channel and I'll see in the next video thank you
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
305
hey guys what's up today the question we're gonna say is 305 the number of islands two right it's basically the question derivative from the question two hundred likes uh the number of islands one if you guys haven't finished that can just try that first and they said that it gives us you know the two degrees uh both you know zero and the one specifically and we uh to initialize we're just gonna give us zero and there will be the parameters m and the n to be represented by the row and the column and also it will give us the positions which means that zero one blah so what are those constraints used for they will be uh the updated operations where we first build zero one means that zero one there will be this one we will replace that into one to you know to philippines into the one and uh here obama means that we have to be one here and one here this is one zero and then zero and every time we will consider them to be connected if they you know the up down left and the right are both you know the same value will be the one right so this kind of you know operations are updated uh to update our board and to see finally uh let's see if you finally have the board which will be like 0 1 y zero one so they will be like quantity four like three because like this is the first one the second one is in the third one so yeah that's basically the uh the whole idea for this question so how are you gonna see that and basically uh before i just saw this question i see that there's one description that's that there will be like the uh any band after each and the land operations so if you guys can see that they will have a constant update of kinetic components so yeah that's basically what are we going to do we first will see number statements we first will register will be considered the unified operation why is that because unified can actually after the you know two different connected components and to merge it and using that efficient way and it's quite useful when you are dealing with you know uh connection and the business component between each part and to make some updates and to get the information that you want so basically we will just perceive using the wf the widget unif file which is the optimized version of union file and we can see that code later uh what's the most intuitive idea for this algorithm the first way we're just gonna uh traverse that and uh notice that there will be the duplicated data which means that we need to avoid those kind of things in our calculations right so the first step will be like how do we use the unified to modify that first i will just gonna um to imitate the process of you know adding these points and first it will be zero y so we're just gonna be here will be one so that one of that but you can define whatever values that you want it doesn't matter it's different from you know the existing uh sales right and that will just be one will be here so we're just gonna have to do that however because first our result said because we want us to return the list of you know integer results first will be one because we only have one connected component right uh after we enter the one point here we will actually we will the value will also be one because like this can be connected by this one and you can know after left and right whenever they have the same value for the one it will just still be connected right and then we're just gonna be like uh go to here one zero which will be this part so we're gonna be becoming well one and we will also to add that to be the one and then finally we're just gonna add the zero which means that we need to add it here so this will be uh zero and we also because those fours are actually connecting together right so basically whenever we just added that we can define the object which is the unified object and it has a count which can be used to you know counter how many components have we left because we usually initialize that with you know m plus n this is a classic problem or unified so that you are supposed to have some kind of background that's running on this knowledge and yeah that's basically the whole idea and also will be uh take this for example three or uh three or one however this will be in the duplicate data so we're just gonna ignore that we will be like here and whenever we you know have the three or one this is here we're just gonna edit that and here we actually rather will be changed to two because that uh this is just gonna be like uh the unique one that uh do not connect it to any of these components right so yeah that's basically the process when we're using the uh the union effect however there are still some details that we that i want to go through with you because that it's kind of hard to figure out and to be honest i have spent some time on this problem so i hope you guys can after seeing this video to save you some time so yeah that's the goal with the second step so how to use that is that we first will define a variable which is www we'll cons we will continue like you can see from here we will actually have those kind of messes for example we will have like union to unite those kind of uh for example union two points this is uh our dividend uh take int and end and also we will have one we will have a fine to find the root because like in the union fight we need to find the root of the you know the point so it's also will be like five operation and also we will just kind of uh have a connection uh connected to charge whether or not there are two points are connected right and also we need to you know uh return the cut we need to get a con so how exactly that is algorithm works first we will define those uh we'll define first the variable and uh yeah just before i start i want to say that my version of unified are derivative from the princeton algorithm that you know the course has really read and my code are really the same from here if i define the id item means that the root of the uh the root of the node and uh say the size will be like because we want the balance tree we don't want in the one tree to be so long and the other child will be just you know this strong so actually using the size side here we're actually to add the uh add the little tree to the bigger one and this used to keep track of uh keep track of the size this side you have to keep our side and wherever we have the union operation we're just going to add a little one into the bigger one in order to make the you know balance tree to make it look nicer right so yes that's basically our operation and for our algorithm that's actually the most important one actually we first will knew the new uh wf right and the second one will be like because we actually we're just gonna transfer that so what are we gonna first of that i'm just gonna first uh because you guys understand one question also i'm just gonna you read that and uh we're all very good we will be like okay this part and uh for this algorithm uh first we were just gonna new the uh wf and with parameter over m plus n because like uh we will convert the two dimensional array into the one dimension by using you know maybe you'll give me the point of zero 3.0 and zero 3.0 and zero 3.0 and i can convert it to this one right so i'm just gonna say convert it from the two different two dimension to one dimension right and yeah and the second step the second thing is that we when we need to go to rest of that we're just gonna four into position and the two uh positions and uh further in this loop we're just gonna check because first whenever we introduce one point in this board we actually because we're here we have a contour right and i'm just gonna using the right counter will be the most important part in our algorithm we first of all define counter to be zero because there will be no component in our report however where we added the zero y so at first we were just gonna uh increase we're just going to increase let's see our increase the counter your contrast pass and then we're just going to see whether or not the up down left and the right are they connected yet if they have already connected we should just you know to decrease counter otherwise the number will be you know are invalid because we have increased that where we increase that we perceive he or she as a unique identity they don't connect with anybody however if we found out you have already connected to you know this particular start so we're just gonna delete that and you can see from here uh i will just you know to check that and after that we are just going to add it uh using our result editor result is a kind of value that we want to return so that it will be like our result editor say our record value so that's basically the organs for that first we're just gonna introduce one union five object and a second we're just gonna go through that and the first we're just gonna increase the contract and every time whenever i just occur uh to find out if you guys have never connected before i'm just gonna connect with that and say let's see because there's one tricky part let's see we have this guy is a guy what do you see uh this guy has already connected and uh they are already connected and we first will go like uh first find the first one and we connect them right so we're just gonna count minus right however wherever we connected those guys and we want to find out this guy and we're connected with them because they haven't planned it yet right so we also need to perform the con minus because we need to eliminate the this energy in order to make the count be valid however wherever you see that because those three bodies are connected already if we see weakness in this guy and we also need to minus that was just going to be a problem so we need to first to examine whether or not this guy and this guy has already connected if yes we are just going to continue that otherwise we are just going to follow this operation and finally we are just going to edit our result into the result set so that's basically the uh the whole idea for this and also there's another part which is called the uh to how to handle our duplicates because never see here if you just go through this logic and we will also encounter the comb miners when we mix the duplicates so they one pro one possible result will be like we can use we can attach that and every time we use the uh to define the symbol which is a string from the x coordinate and y coordinate and the arrow kind of everything encounter the same part for example we can define a variable which is uh this is our headset and we can define the x variable plus our i plus the uh variable this is become our symbol uh as well and uh simple and the arrowhead has been u whether or not has been examined if it does we'll continue that otherwise we will introduce the you know duplicates and if not we're just going to add it to our headset which we can call it uh relative and uh to you know go towards this step one two three and finally yeah that's basically the whole idea for this question and let's go see how could you implement in those kind of steps oh yeah after go through the basic process let's see the uh implication of the code well first we were just going to the union fight and uh the codes that i write are from uh sir princeton the all gold yeah that's all algorithm prison and i believe that the code that he writes are you know really elegant so i'm just gonna borrow from that yeah and uh to be honest i modify a little bit this count and just uh to promote it to be the public and also to remove the operation of the comb minus after we just make the union because like we have another usage so we don't you know follow that rule and uh for our main code we first we're just gonna this is a video that we define the other two y duplicates and this is just a unified the object that we define uh with a parameter of m times seven because we need to convert those uh say uh two array dimensions to one dimension right and also this is simple we need to a y duplicate and we added that and this is actually the most the core part you can see from here we first will just change it to the one because we use one to uh two distinct from other kind of surrounding cells for example zero and which means that it has been you know to added and um yeah and every time we go through this process and do you remember that where we find one that we haven't connected we're just gonna minus one right otherwise we're just gonna you know because sometimes wherever we connect like the first two and uh there will be the possibility that uh the layer two will be connected because we have connected previously so you need to first to find out whether or not it has not been connected if yes we're just gonna uh to minus that otherwise we don't do anything because like you will you if you actually minus four times every time you in the loop you will just gonna introduce the uh duplicates situation which will result in a uh raw number and finally which is gonna result i added and every time we're just gonna edit the console that we will just uh console that we will just uh console that we will just uh this part will introduce us with one entity and we see that whether or not these are connected both up down left and the right yeah that's basically the whole idea and we're just going to return it out so yeah that's actually a great question considering using the model of wf the weighted unified to solve this problem the uh it's actually a classic unified problem and uh yeah that's it for question 305 the number of islands too
Number of Islands II
number-of-islands-ii
You are given an empty 2D binary grid `grid` of size `m x n`. The grid represents a map where `0`'s represent water and `1`'s represent land. Initially, all the cells of `grid` are water cells (i.e., all the cells are `0`'s). We may perform an add land operation which turns the water at position into a land. You are given an array `positions` where `positions[i] = [ri, ci]` is the position `(ri, ci)` at which we should operate the `ith` operation. Return _an array of integers_ `answer` _where_ `answer[i]` _is the number of islands after turning the cell_ `(ri, ci)` _into a land_. An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. **Example 1:** **Input:** m = 3, n = 3, positions = \[\[0,0\],\[0,1\],\[1,2\],\[2,1\]\] **Output:** \[1,1,2,3\] **Explanation:** Initially, the 2d grid is filled with water. - Operation #1: addLand(0, 0) turns the water at grid\[0\]\[0\] into a land. We have 1 island. - Operation #2: addLand(0, 1) turns the water at grid\[0\]\[1\] into a land. We still have 1 island. - Operation #3: addLand(1, 2) turns the water at grid\[1\]\[2\] into a land. We have 2 islands. - Operation #4: addLand(2, 1) turns the water at grid\[2\]\[1\] into a land. We have 3 islands. **Example 2:** **Input:** m = 1, n = 1, positions = \[\[0,0\]\] **Output:** \[1\] **Constraints:** * `1 <= m, n, positions.length <= 104` * `1 <= m * n <= 104` * `positions[i].length == 2` * `0 <= ri < m` * `0 <= ci < n` **Follow up:** Could you solve it in time complexity `O(k log(mn))`, where `k == positions.length`?
null
Array,Union Find
Hard
200,2198
926
Hello hello everyone welcome dandruff exactly edison electronic in this question on thursday a due to increase in subscribe oil olive oil ko hai to electronics and example possible se 0110 neurotic last 2 and will update were 2002 c the tarzan the car ki stock board heart Alert Cases Can Sleep With Long Due To Make It Possible To Subscribe 10 And Subscribe Button And That Unless Ronit The Question Example Of Bird's Logic Wife Viewer Test Cases Subscribe Button Take Care 30 subscribe and subscribe the Bell Icon Subscribe This Is The One Thing But I Will Notice That Unleash You What Is The First One Events During The Previous Protest Starting In Dowry Is Up Till Recently Introduced Into Something 10 Subscribe 2018 201 Number One Adhikar Hai 200 Win This Implies Cafe 20 Tax Unleashed You Don't Witness Forest Wealth Ko Stupid This Trick Paul Possible So If In Pimples Going For Electronic Vid U To 101 60 Convert Into Your Monotonic Increasing Sequence A Possibility Is New Updates 2025 Video Subscribe Button Video Subscribe To That And 231 Rates From Distant View Of Possibilities In More And Two A Novel Which Will Have Been Put In More Money And In The Mid-1960s Subscribe To That Money And In The Mid-1960s Subscribe To That Money And In The Mid-1960s Subscribe To That I Will Pick Up Do Minimum Voting Service To People Didn't Listen To Be Converted From 210 Videos Vidmate Element 2021 Adb School Vid U Mein 150 Sau CC Ek Ansh Do The Best Variable Digestive Want Get Updates subscribe The Video then subscribe to the Video then Main Unferval COD Don't Want But In Doing So Will Lead You To Contest Channel Ko Subscribe And Subscribe The Play List Country To Protest for the shampoo Bihar 2.0 to and the Shravan ko shampoo Bihar 2.0 to and the Shravan ko shampoo Bihar 2.0 to and the Shravan ko and beautiful post my balance 1.138 volts and beautiful post my balance 1.138 volts and beautiful post my balance 1.138 volts and short to waste time subscription that Arvind current account Dr to banaras vansh updated on Thursday cnn-ibn understand what vansh updated on Thursday cnn-ibn understand what vansh updated on Thursday cnn-ibn understand what is the what will subscribe institute of getting Old Subscribe The Channel Subscribe To That Politics And Dancer Option 2000 Updated On One Plate Hour Showpieces Hai Andhra Green Beans Tutorial C That Deposit 1021 Account Dada Becomes Number One Sathya Witness To Offer Report Vansh One Will Update Soon In This Again Play List There are two Next VCD in this video 021 Subscribe to ke din kshatriya hai iss vansh will update same account 1.23 in Ango Informative Bill-2012 subscribe to The Amazing All Bill-2012 subscribe to The Amazing All Bill-2012 subscribe to The Amazing All Videos Subscribe to Play List Talk About a Very Interesting Half Minute Adhir Video then subscribe to The That I Want How To See And Post Element Wale Episode 216 Element In Manya Cases To Subscribe Cr Video subscribe And subscribe The Amazing Lut-Pit Luta Do Subscribe To That Is To And Institute Of Getting 80 Will Update 120 Updates 2120 Donate Subscribe What We will do subscribe to and add account dip account is to the latest update 2021 will do to take off but answer are to day 30 update to subscribe one and will update the same account 238 ki and you will see grade three Lo Urgent To Show The Answer Stills Elements To Accident To Back Once Its Importance Of A Guru Can Update Between 210 Subscribe subscribe and subscribe the Video then subscribe to the Page That Aap Side Effects 200 Gram 10021 Content Is Visible To Deal With Spring Time All My Videos Twist Life In Preventing Start Flu Subscribe 21 2012 Pickup The Phone I Hope That's Logic And Looting liked The Video then subscribe to the Page
Flip String to Monotone Increasing
find-and-replace-pattern
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none). You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`. Return _the minimum number of flips to make_ `s` _monotone increasing_. **Example 1:** **Input:** s = "00110 " **Output:** 1 **Explanation:** We flip the last digit to get 00111. **Example 2:** **Input:** s = "010110 " **Output:** 2 **Explanation:** We flip to get 011111, or alternatively 000111. **Example 3:** **Input:** s = "00011000 " **Output:** 2 **Explanation:** We flip to get 00000000. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
null
Array,Hash Table,String
Medium
null
1,171
so guys let's proceed to the question number 1171 remove zero some consecutive notes from link list so basically in this we have to remove the uh zero sums that is for example in this array 1 + 2 = 3 and minus 3 this array 1 + 2 = 3 and minus 3 this array 1 + 2 = 3 and minus 3 is also zero so we will remove Min -3 is also zero so we will remove Min -3 is also zero so we will remove Min -3 and also - 3 + 3 = to 0 so we will and also - 3 + 3 = to 0 so we will and also - 3 + 3 = to 0 so we will remove 3 so the answer should be 1 to one so for this we will create map running Su for running sum and we willay sual to z l star W list node and we will point we will find the next to head Domino equal to head now will sum equal to sum this current value and also uh we will do what we will store current [Laughter] [Laughter] [Laughter] current [Laughter] [Laughter] [Laughter] equal to Sun Plus Su equal to Su plus current value and if Su not find some not equal to do n that means we have ENC counted zero so we will equal to some next current next we will return Dom equal to return so I guess this will be the right solution so we will run it just taking some time in this there is little problem text so if we run it now will property so it is as we want it to run so this is basically code is submitted thank you for watching
Remove Zero Sum Consecutive Nodes from Linked List
shortest-path-in-binary-matrix
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Array,Breadth-First Search,Matrix
Medium
null
71
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem number 71 simplify path let's read the problem description given a string path which is an absolute path starting with a slash to a file directory in a unix-style file to a file directory in a unix-style file to a file directory in a unix-style file system convert it to the simplified canonical path in a unix-style file canonical path in a unix-style file canonical path in a unix-style file system a period refers to the current directory a double period refers to the directory upper level and any multiple consecutive slashes are treated as a single slash for this problem any other format of periods such as three periods are treated as file directory names the canonical path should have the following format the path starts with a single slash any two directories are separated by a single slash the path does not end with a trailing slash the path only contains the directories on the path from the root directory to the target file or directory ie no period or double period return the simplified canonical path so if we look at our examples we're given you know path equals slash home slash and we should return slash home why do we get rid of the slash well remember the path does not end with a trailing slash so we need to get rid of this what about this example slash home double slash foo slash well again we get rid of the trailing slash and we need to treat this double slash as a single slash so we've read the question prompt and we've looked at an example but how are we actually going to solve this problem intuitively let's think about it okay so we read the question prompt and we looked at a few examples but we didn't talk about how we're actually going to solve this problem well the first thing to realize is that the problem tells us that there's really going to be only a few elements that we can see in our path right we're only going to honor you know a single slash some potential like multiple slash we could have a single dot we could have you know multiple dots two of them we could have you know some sort of like directory name and that's about it we can't have anything else in our path so the algorithm that we want to use here is actually going to be to take the path and we're going to want to split it on you know slashes so what this will give us in the end is um you know we're going to split the path whatever we have on slashes so this is going to return to us you know a list which is going to be you know we could have like the single dot we could have you know the double dot we could have you know the directory name whatever it is and then okay what happens when we split on slashes and there's multiple slashes well what ends up happening is that you split them but since there's nothing between them you actually get an empty string so that's going to be the only possible values we can get so what we want to do is actually work with a string builder and what we're going to do is we want to go from left to right of our you know split items here and we're going to maintain a stack which is going to work as our string builder and what we're going to do is we're going to go through our you know thing from left to right here so the elements that we split and okay remember that if we see a dot this represents the same directory so we can actually ignore this because that means that we'd be staying in the same place we don't have to do anything if we see a double dot remember that means that you need to go up one level so that means that we're going to pop whatever's in the stack when we see like a double dot if and only if the stack is not empty right because if we try to call stack.pop on a stack that's empty call stack.pop on a stack that's empty call stack.pop on a stack that's empty we're gonna have um you know an error be thrown so we can't do that so we're only gonna pop if we see a double dot in the case that the stack here is you know non-empty is you know non-empty is you know non-empty and you know if we see some sort of directory name you know it can be something like abc or it can just be like root it doesn't matter it's just gonna be some you know value that isn't a dot double dot or not a um you know just an empty string so anytime we see anything that's not one of those three then it's just a directory name in which case we're just gonna add it to the um the stack here and then you know if we see an empty string we just continue so we don't have to do anything in that case so pretty much that's what we want to do we just want to go through our path here and again if we see a dot don't do anything if we see a double dot pop from the stack if there's something to pop if we see a directory name added in there if we see an empty string don't do anything and at the end you know our stack's gonna be full of like you know directory so this is gonna be you know directory one it's gonna have like directory 2 directory you know three blah and remember that we just need to join these directories together so with like slashes right so it's gonna be like dear one plus dear two plus directory three and you know that's all we need to do and remember that we need a leading slash so we're simply just going to add you know a leading slash to you know this concatenated string here and this is going to be our result so hopefully that's not too confusing if it is we're just gonna go into the editor now and you're gonna see that it's gonna be super clear this problem is really simple so once you see the code you'll be like okay this is super simple i get how to do it so i'll see you in the editor let's solve this problem okay we're back in the editor now let's write the code remember that we're going to stack to basically store our path that we've built so far so let's define that variable so we're going to say stack is going to be equal to an empty list and remember that we need to extract the path items from our original string and the way that we're going to do that is we're going to take the path that we're given and we're going to split on the slash characters so let's do that so we're going to say path items is going to equal to path dot split and we're going to do that on you know a slash here now we need to go through the path items and basically check okay is it a dot is it a double dot is it you know a directory name or is it an empty string which is the case where you know we have multiple slashes together so what we want to do is iterate over our items here so we're going to say for item in path uh items what we want to do is okay we want to check the cases uh where we don't do anything so remember if item equals to a single dot or not item so if the item is an empty string which is the case where you know we had two or more you know slashes together so for example in this one where it's like foo and then or sorry home two slashes and then foo you know if you try to split uh on slash when there's two of them together like that you're going to get an empty string because technically there's nothing in between them so in this case we just continue we actually don't do anything here otherwise we could have potentially a double dot so we're going to say l if item equals to oops double dot then what we want to do is remember we want to pop whatever is at the top of our stack and the reason we do this is because in you know unix systems two dots means you know go to the previous directory so we want to pop from the stack but remember our stack needs to actually have an element in it for us to call pop on it if we try to pop from an empty stack we're gonna you know blow up our code uh and it wouldn't be correct so we only want to pop when the stack actually has at least one element so we're gonna say if stack so basically if it has at least one element we're gonna say stack dot pop otherwise we don't do anything now the last case is that we have a directory name because if you read the problem here you know the only thing that can be in path is going to be a single dot slash uh or you know double dots some sort of digits but these are all just you know the directory name so we don't have to worry about it so the only thing left now is like a directory name so we can simply just append that to our stack so append uh item right and at the end remember that we needed to join our stack together with slashes and we also needed to add that uh leading slash right all of the answers need a leading slash and joining our elements will actually not put a slash in the beginning it's gonna put a slash after each element but it won't add one at the beginning of our string so we need to do that manually so we're going to say oops we want to return you know a slash plus the concatenation of all the elements here with you know a um a slash in between them so we're simply going to join our stack and we're going to simply submit this double check that it works and it does cool so what is the runtime complexity of our algorithm well in the worst case we are you know going to have to basically split our string here right so no matter what we have to call this split so this is going to be a big o of n operation and then we have to iterate all over all the splits here so what that means is it's going to be a big o of n um time complexity because this is going to be big o of n and then this entire process is going to be big o of n so you know our entire algorithm is big o of n also the joining of the stack here is potentially a big o of n operation so you know we've done three big o of n operations but they all happen you know serially they're not nested so the asymptotic runtime complexity is still going to be big o of n and space complexity wise it's also going to be big o of n because you know we need to maintain this stack which is going to be filled from elements in our path here and then the path items um the length of this is going to be dependent on you know the number of items in our path so in the worst case you know we can just have a lot of um elements that we need to use but this is still going to be constrained on path so our time complexity is going to be big o of n and our space complexity is going to be big o of n so hopefully that makes sense like i said this problem is pretty simple uh even if you haven't seen it before you can pretty easily derive this one so hopefully this clears up any confusion if you needed to watch this video to understand the solution or even how to do the solution in the first place um that being said if you enjoyed this video please leave a like comment subscribe let me know if there's any questions that you'd like me to do i'd be happy to make the videos for you guys just let me know in the comment section below and i'll do my best for you guys so that being said happy coding and i'll see you next time
Simplify Path
simplify-path
Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**. In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names. The **canonical path** should have the following format: * The path starts with a single slash `'/'`. * Any two directories are separated by a single slash `'/'`. * The path does not end with a trailing `'/'`. * The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`) Return _the simplified **canonical path**_. **Example 1:** **Input:** path = "/home/ " **Output:** "/home " **Explanation:** Note that there is no trailing slash after the last directory name. **Example 2:** **Input:** path = "/../ " **Output:** "/ " **Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go. **Example 3:** **Input:** path = "/home//foo/ " **Output:** "/home/foo " **Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one. **Constraints:** * `1 <= path.length <= 3000` * `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`. * `path` is a valid absolute Unix path.
null
String,Stack
Medium
null
1,876
hello today we will be doing the problem number 1876 that is substring of size three with distinct characters so like to dislike youtube so we'll be doing it today the problem statement here is a string is good if there are no repeated characters given a string s return the number of good substrings of length 3 in s note that if there are multiple occurrences of same substring every occurrence should be counted a substring is a contiguous sequence of characters in a string so the input statement here given is x y z a and z so we will be taking three contiguous statements that is x y and z and we'll check if there are any repetitions of any characters let me just write this in a whiteboard x white that set x y xyz said he said sorry for the bad handwriting uh so first we will check we will be using the sliding window technique here to find the uh if there is any repetition characters in the substring so this uh total substring here is xyz that is that the substring size is one two three four five six so the substring size here will be five uh n minus one of course so first we will check in this sliding window xyz if it does have any repetition no so we'll count so we'll increase the counter t by one so we'll be increasing the counter by one then we'll be checking through this sliding window and the question here it is mentioned that uh the sliding video should be three let me just show it yes return the number of good substrings of length three in s so the sliding window given here is three so we will first then we will check in y z so we are seeing that here we have two occurrences of z so the count will still remain one then we'll be checking from z a will be incrementing the i and we'll be checking the third uh contiguous subsequent contiguous substring so that's that a we have double z here so again we'll be skipping this part and we'll be checking from z a z which is our last configure string that is that and see we are getting here the z twice so the count remains once and we'll be returning this one and let's see yes the output here is one so let's see the code let me just enlarge it first we will check if the size is less than or equal to one uh if it is less than or equal to one will be returning zero and this here is the base case will be iterating from size uh from 0 to size minus 2 by size minus 2 since we'll be iterating from here which is this point the point this point is zero and will be iterating till here so as to avoid the index out of bonds let's check the a follow which is we will be iterating till n minus 2 then we'll be checking s of i is equals to s of i plus 1 or i plus 1 is equal to s of i plus 2 or i plus 2 is equals to s 5 let me just explain it here so s of i is x here and s of i plus sorry i plus 1 is z y here sorry and s off i plus 2 is z here so first we will be checking between i and i plus 1 if they are equal or not they are not equal then we will be checking if s of i plus 1 and i plus 2 is equal or not they are not equal and then at last we will be checking s of i plus 2 and s of i is equal or not which is not equal so we will be implementing the count to one let me take one more example of this the second iteration and let me just release this so this is uh released yes let me take the pen yes so the second subsequence will be y z and z here the eyes value is now one so we'll be taking the string y z and z s of i is what y s of i plus 1 is that and s of i plus 2 is that first we will be comparing i and i plus 1 y is not equal to z clear then we'll be comparing s of i plus 1 which is z and s of i plus two which is again said so this will just dominate and skip to the next iteration which will be two i shall move the iteration two and it will be going till n minus two times and we'll be here taking a result variable for the counter and yeah that's it we are done with the code so let's just submit it the font size yes so it is getting accepted and 0ms which is 100 percent faster that's it so hope you guys uh learned something new today thank you for watching
Substrings of Size Three with Distinct Characters
map-of-highest-peak
A string is **good** if there are no repeated characters. Given a string `s`​​​​​, return _the number of **good substrings** of length **three** in_ `s`​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** s = "xyzzaz " **Output:** 1 **Explanation:** There are 4 substrings of size 3: "xyz ", "yzz ", "zza ", and "zaz ". The only good substring of length 3 is "xyz ". **Example 2:** **Input:** s = "aababcabc " **Output:** 4 **Explanation:** There are 7 substrings of size 3: "aab ", "aba ", "bab ", "abc ", "bca ", "cab ", and "abc ". The good substrings are "abc ", "bca ", "cab ", and "abc ". **Constraints:** * `1 <= s.length <= 100` * `s`​​​​​​ consists of lowercase English letters.
Set each water cell to be 0. The height of each cell is limited by its closest water cell. Perform a multi-source BFS with all the water cells as sources.
Array,Breadth-First Search,Matrix
Medium
null
93
Hello friends today I'm going to solve with problem number 93 restore IP addresses so in this problem we need to construct a valid IP address from a given string s so what's a valid IP address uh it consists of four integers which are separated by single dots and each integer can be between 0 to 255 inclusive and cannot have any leading zeros for example this is a valid IP address because none of them have any leading zero however this has a leading zero so it's not a valid IP address this is also a valid IP address however this is not a valid IP address because it has value greater than 255 and in this case it has an um a symbol which is other than an integer and a DOT value so it can only have a DOT value which separates integers which are between 0 and 255 and each integer there are four integers in total so now given the string as we need to construct a valid IP address and we are going to construct like return as many valid IP addresses that are possible to be reconstructed from the given strings so we are given this example let's see how we could solve this problem so from this example let's see what are the valid IP addresses that we could get from this example so first of all let's check the length of the IP at of this string as so for an IP address what do we need is four integers separated by dot right for integers and Dot so what would the minimum length of an IP address be the minimum length would be if each IP address has integer of only length 1 and each are separated by a DOT so this is of length one and separated by dot so if we are constructing this IP address from a string then what is the length of the string if string only has integer values and we are actually inserting dots in it so basically length would be 1 2 3 and 4. so the minimum length of the string should be four what about the maximum length so each IP address can have values from 0 to 255 right and 255 means if each integer is offline 255 then it's of length 3. and since we have four such integers so the maximum length is 3 times 4 which is equals to 2 valve so the length of the string should be between 4 and 12. so this will be our base condition if the length is less than 4 or greater than 12 then we cannot construct a valid IP address from our string so this is one base condition that we found now let's see how we are going to solve the problem so let's look at the length is it valid so we have three plus three six plus three nine plus two which is equals to 11. so since the length is equals to 11 so it falls up in within the range right and then so we move on to the next step that is to construct an um to construct a valid IP address so how could we construct a valid IP address um well one way is to start as a um start from the first digit so what are we going to do is we look at the very first digit here so the first is it is to and we try to add a DOT after that uh just that the first integer is of single digit the next integer is 5 and then we put a dot again the next integer is five we add five and we put a dot again and the remaining integer since there will there must only be four integers so this the remaining uh value should be the fourth integer right but is the land between the range the given range the valid range well it is not it's greater than that right so we cannot form our IP address uh with this uh in this way like by only taking one integers at a time so what we do is now we actually backtrack so we backtrack from this section from here and what where we reach is 2 5 dot so now foreign so now we have raised this step and what we do is now we check uh if we can take these two integers together as our third integer so we take these two and then we add a DOT and then we look at the remaining integer and it's still great so we again backtrack and then we take these three as our third integer and now if we take these three the value is greater than our given range so again we backtrack now we are backtracking since the length is greater than 3 so we are backtracking from where we are backtracking from this position to this position now here so since we backtrack we have we reach where the value only with only first integer and then now we take two integers between 55 and then we take the second integer and then the remaining is again greater so we keep on doing unless and until we take like 25 and then 52 and then 5 55 and then again this whole big integer so we again backtrack and then our 25 and then we take 52 and 551 it's again greater than that so we backtrack we take this three it's greater than 255 so we're working backtrack and we take these three integers and then what we do is we look we again keep on like taking only individual integers unless we get this whole big in number with backtrack there we take these two values and then again these values still greater so we backtrack now we take these three values but now these three values greater than so we take we backtrack to this point and then we take these two values and then we again take a single value and we still have this whole big number so we backtrack and we take two values and this is still greater so we backtrack and we take three values two digits and now when we take three digits it's greater than 255 right so we again backtrack from there and we take these three values and then in that way we end up with our valid integers that would be uh one would be this value and this value the other would be these three digits and the last two digits so now that we understand how we could solve this problem let's uh start coding so what we need is um let N close to the length of the string all right and then we need our result array to store our result and we are going to create our DFS function since okay let me not let me Define these at back tracking function which text value so what are the values it would require well we basically need to keep track of where we are like um in the string so we need the index of the string indexing this string and then we also need to keep our IP address right keep track of the IP that we are forming and we also need to keep track if we are at we already have four uh digits if we have like not four digits but four integers if we have already formed four integers or not so we'll keep track of the count of the integers and let me just create our calling function so we are going to pass zero and the IP address would be um an empty string initially and the count would be equals to four because there should be four integers and we are going to return our result now here um in the back tracking function we check the base case okay we actually check the base case here so if the length and is less than four or n is greater than 12 which means that the range it would be between 4 and 12 right if it is greater uh it doesn't fall in that range then we are going to return an empty array because that is the case where we cannot form a valid um valid IP address all right now once we have reached our function so in the function what's the case when we are going to push uh the IP address to our result well it's the it's rain um we have found all of our four integers and uh this the length of this string is uh equals to zero so is equals to zero because we will be slicing our um string to form our IP address so see both of them should be equals to zero then we are going to push to our result array push our IP address and if in case the length is not equals to zero which means that it would be the condition where we have 2 5 and then which means we have two five and the remaining integer values is this much and this integer value is uh basically we can only take maximum of three right and the remaining would be this value and since the length is not equals to zero however we already found our four integers uh that's not a valid case so in that case also if C is equals to zero we are going to return now what we'll do is we will Loop over um the value of our Loop over this string starting from its first index in isopylis then the length of the string at plus so what are we doing here is we are actually doing the iteration so let's just see so one of the strings that we formed was a valid IP was this one right the another is valid IPA we could form is these three values these three digits and these three and this the last two right so how we're going to form that well basically uh in the substring uh so this would be our substring so we choose these uh only length of one only first fact is it in the next case what are we going to do is we are going to choose these two slice the first two digits and then similarly slice the next uh slice one plus so that we form our IP address so that is what uh we'll be doing so we are going to create a sub IP equals to slice um from index 0 to the index I plus one and value of the sub IP address should be in the range should be less than and it should not have any leading zeros so we are going to check if the sub IP the first value is equals to zero then we are going to return um call our backtracking function with index I plus 1 and our sub IP address being uh increased being appended by our sub IP so we append our sub IP but we are going to paint based on where we find the sub IP if this sub IP is the very last integer then we do not need to add the value C so if the value of C is equals to zero then we are just going to append it um actually if it's the very first I very first uh integer in this in our IP address so we are just going to append it without any leading dot else we are going to add a DOT before the sub IP and then C minus one now um talking about the sub IP comparison with this value so since sub IP is a string we need to convert it into an integer so we are going to pass it through integer values and this would not be an and operated this would be an or operation and we are going to also check if the sub IP length is greater than 1. so by length is greater than one and the first uh element first digit in the integer is equals to zero that is when we return also we need to check if the length of I is greater than the length of the string if that is greater than length of the string that we need to return back because um it could be the case that the length of string is only one and basically it will only run over the value of 4. now let's try to run our code and let's see what the result is okay something went wrong all right so these are the final changes that I made to my code now let's try to submit this great
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"192.168@1.1 "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
130
hello friends today let's of the surrounding regions probably given a 2d bode contain the X and O the letter or capture all regions surrounded by X a region is captured by sleeping on earth into X in that surrounded region less is this example we sleep these Rios but we do not sleep this or why because the surrounding region should shouldn't be on the border that means ending all in this folder we will not flip it so let's think if there is no these restorations we can just do a simple DFS or PFS or a unified or just iterate this border and when we find oh we will do DFS to find the author also contact connected to this all in a flip data to the X right and mockito as VT but the TIF the only difference is that if this all can connected to all on the board we will not flip all these O's so how to solve that I think there we can just start from these four borders we check this for border if there is a all we will do a DFS to mark all this chart owed to the victim and all the O's connected to this all will also be marked admitted then we just do a single iteration on the inner region like we start from here and the as it oh and we have an ability the before we just mark it at X and there we do the FS that you mark all these also chooser X so let's see these algorithms first we check the bode are actually is a powder if the Buddha IJ coccioli mock although connected to this or to Vegeta and here we do a depth first search and now certain establish iterator from the Row one to row and minus one from column one who callin a minus one if both IJ go to this all and we have the video before that means it doesn't technically the chili powder will flip the old to the X and also we do a depth first search here so you see this example we first checked the full powder and there we find that here is all we mark it and eat it and there unfortunately there are no oh connected to this all so we just a magazine Oh to the video then we iterate their inner region and both a 1 equal to O we flip either to X and we keep find on video connected to this all and we mark will flip all these oz to the X so this example and the extra weekend combines into their first search just use one function that is the boat and the current row count current color and the video array and also use a boolean variable flip to mark whether we need that you flip the current Oh if the flip is true when we meet all we change it to true X and Mark littell visitor which means we are in there in the region otherwise just mark it a date that means we are on the border so ok let's write the code now we first do educate Shack if boat or yacht you know or for the door lens you go to 0 we return otherwise we kept the rows equal to both the lens colors equal to both zero dollars and we use a visitor there will be food in rows Collins then we first checked the folk folder we first checked the first and the last row so there will be J less then called a : so there will be J less then called a : so there will be J less then called a : j plus so if the boulder 0j e kochu oh we do that for such we pass both current row index is zero and current calling that J and the past is visit and the currently we do not need to flip so it has a force and if the error will be the last row there will be rows minus 1 j e ho - OH j e ho - OH j e ho - OH with also do a depth first search both rows minus 1 there will be J we did force okay then there will be the leftmost color in the rightmost color so I call to zero unless then the rows I plus so if both there will be i0 the leftmost column you got you oh we do their first search there will be both there will be I 0 and the revealed sedum there will be a force okay then for the rightmost : there will be Colin's minus rightmost : there will be Colin's minus rightmost : there will be Colin's minus 1 equal to oh we do therefore search fold there will be I Collins minus 1 related and the force finally we do we iterated there in the region so I will start from 1 I less than rows minus 1 I plus and there jo21 jealous and collins minus 1 j plus if the forward i j equal to or and we haven't read here before the I J we do DFS enter Oh i jz it's it this time we mark it at you because we need to flip it so now let's implement this avoided DFS there will be charged boat intro in the current korean VHC them and there will be food yet sleep we first check if the index is valid if Rho less than 0 or : less than valid if Rho less than 0 or : less than valid if Rho less than 0 or : less than 0 or Rho great them powder tolerance minus 1 or : course import $0 minus 1 we minus 1 or : course import $0 minus 1 we minus 1 or : course import $0 minus 1 we return if we visited before we return if the board row : equal to X we return the board row : equal to X we return the board row : equal to X we return otherwise we check if the flip equal to true we need to flip the current or to the X otherwise we just mark it to visit it so there will be true then we do the four directions def for such there will be Rho plus one called eat it and flip the FS board Rho minus one called bility to flip and the FS food row column plus 1 DT to flip then would row : 1 DT to flip then would row : 1 DT to flip then would row : - what they did sleep okay sorry - what they did sleep okay sorry - what they did sleep okay sorry yeah singer finish it ah yeah this is a typo okay thank you for what you see you next time
Surrounded Regions
surrounded-regions
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`. A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region. **Example 1:** **Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\] **Explanation:** Notice that an 'O' should not be flipped if: - It is on the border, or - It is adjacent to an 'O' that should not be flipped. The bottom 'O' is on the border, so it is not flipped. The other three 'O' form a surrounded region, so they are flipped. **Example 2:** **Input:** board = \[\[ "X "\]\] **Output:** \[\[ "X "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is `'X'` or `'O'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
200,286
322
hi everyone I'm Dr surjit Singh today we'll talk about the lead code problem coin change let us begin we are given a list of coin denominations and a Target amount we are to find the fewest number of coins that will make up the amount bottom up solution of the problem is iterative we are given a list of coin denominations we will use the minimum number of these coins to make up the given amount in the bottom up dynamic programming we will find the solutions for all the amounts from 0 to 11 we Define an array named DP to record the number of coins requ required for each amount to begin with we assume that for every amount we require infinite number of coins we do not need any coin for amount zero so we assign Zer to DP 0 we Loop over all the coin denominations first one is a $2 coin denominations first one is a $2 coin denominations first one is a $2 coin denomination let us see how many solutions are possible with this a takes all values up to the Target amount however as the $2 coins cannot generate however as the $2 coins cannot generate however as the $2 coins cannot generate amounts less than two we start with a equal to 2 and not with zero as we select $1 two coin amount zero as we select $1 two coin amount zero as we select $1 two coin amount increases from 0 to two it means that adding one coin to the empty bin gives us an amount of $2 so we replace our solution for or $2 so we replace our solution for or $2 so we replace our solution for or amount two with one coin it means that just one coin is enough to get the amount equal to $2 next value of a is $2 next value of a is $2 next value of a is three present solution for an amount of $3 requires infinite coins we can get $3 requires infinite coins we can get $3 requires infinite coins we can get three by adding a $2 coin to amount three by adding a $2 coin to amount three by adding a $2 coin to amount equal to 1 however AAL to 1 itself needs infinite number of coins so there is no use adding another coin to it we leave the result for three unchanged and we move to a equal to 4 we can get four by adding a $2 coin to 4 we can get four by adding a $2 coin to 4 we can get four by adding a $2 coin to amount equal to two our DP table tells us that amount two needs one coin so four needs two coins which is much less than the earlier requirement of infinite coins so we replace it with two we can get amount five by adding a $2 coin to a equal to five by adding a $2 coin to a equal to five by adding a $2 coin to a equal to three however both of them require infinite coins so there's no change in the result we can easily deduce that odd amounts cannot be produced with $2 coins amounts cannot be produced with $2 coins amounts cannot be produced with $2 coins further we can easily check that to produce amounts 68 and $10 we require produce amounts 68 and $10 we require produce amounts 68 and $10 we require three four and five coins at the end of the inner for Loop we get these DP entries we obtain all these by using $2 coins now let us see these by using $2 coins now let us see these by using $2 coins now let us see the refinements in the solutions by including coins of $3 including coins of $3 including coins of $3 denominations minimum amount that this can generate is dollar three if we add a $3 coin to empty bin we get a equal to 3 $3 coin to empty bin we get a equal to 3 $3 coin to empty bin we get a equal to 3 with just one coin this is less than infinite coins needed in the existing solution so we replace it with one for amount four we must look for previous result for a equal to 1 but for amount one we need infinite coins so the present result for a equal to 4 that requires two coins is good enough for us we do not change it we can get amount five by adding a $3 we can get amount five by adding a $3 we can get amount five by adding a $3 coin to a equal to 2 we get amount two with one coin so we can get a equal 5 with two coins and therefore we replace dp5 with two existing solution says that we can get amount six with three coins let us see if we can improve upon it for amount three we need one coin if we add a $3 coin to it we get $6 with just two $3 coin to it we get $6 with just two $3 coin to it we get $6 with just two coins so we reduce dp6 from 3 to two we can get an amount of $7 by adding two we can get an amount of $7 by adding two we can get an amount of $7 by adding a $3 coin to $4 DP table tells us that a $3 coin to $4 DP table tells us that a $3 coin to $4 DP table tells us that we get $4 with two coins so we need we get $4 with two coins so we need we get $4 with two coins so we need three coins for making $7 that we now record in DP table $7 that we now record in DP table $7 that we now record in DP table amount 8 is achieved by adding a $3 coin amount 8 is achieved by adding a $3 coin amount 8 is achieved by adding a $3 coin to a equal to 5 so we don't need four coins for eight we can make it with three coins remember that our aim is to reduce the number of coins for amount nine we need just three coins as seven is possible with three coins 10 is possible with four coins and 11 also with four coins we will now further revise the counts using $ do further revise the counts using $ do further revise the counts using $ do coins we start with a equal to 5 amount five is now possible with just one coin and we replace the old count for five with one coin AAL to 1 requires infinite coins so there is no improvement for the amount six AAL 2 requires one coin so amount 7 is possible with two coins eight Now does not require three but two coins for nine however remain three five is possible with one coin so 10 is possible with just two coins a equal to 6 is possible with two coins so 11 is possible with three coins with this both the for Loops end keeping a record of previous Optimal Solutions in DP helps Us in making immediate decision for every amount without trying all combinations and their subc combinations for the final amount we now have the best solution for every amount up to 11 we may notice that the amount of $1 is not possible with the amount of $1 is not possible with the amount of $1 is not possible with the coins available to us we return three as the optimal solution that involves minimum number of coins for amount 11 in case the desired amount needs infinite coins we return minus1 as the answer let us assume that n is the length of the coins list total iterations in the two for Loops are n times the target amount a Time complexity is therefore n * a space complexity is therefore n * a space complexity is therefore n * a space complexity is the size of the DP array that is equal to the required amount thank you for your time I hope you like the video please stay tuned for more such interesting videos
Coin Change
coin-change
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`. You may assume that you have an infinite number of each kind of coin. **Example 1:** **Input:** coins = \[1,2,5\], amount = 11 **Output:** 3 **Explanation:** 11 = 5 + 5 + 1 **Example 2:** **Input:** coins = \[2\], amount = 3 **Output:** -1 **Example 3:** **Input:** coins = \[1\], amount = 0 **Output:** 0 **Constraints:** * `1 <= coins.length <= 12` * `1 <= coins[i] <= 231 - 1` * `0 <= amount <= 104`
null
Array,Dynamic Programming,Breadth-First Search
Medium
1025,1393,2345
371
hi there so today I'm looking at a little bit manipulation question which is 371 sum of two integers we need to calculate the sum of two integers a and B but we are not allowed to use the addition and the subtraction operator so we have to look into the binary representations for those integers and see what's actually kind of happening in the binary level when we do the addition so let's just take the very first example we have 1 &amp; 2 so add those two example we have 1 &amp; 2 so add those two example we have 1 &amp; 2 so add those two together for simplicity purpose we're looking at four bit unsigned integers we have four positions one is 0 1 2 is 0 1 0 and the result is 3 which is 0 1 basically this result is the one can obtain this by doing an exclusive all rip between 1 &amp; 2 and then looking at some between 1 &amp; 2 and then looking at some between 1 &amp; 2 and then looking at some other examples for simplicity we're looking at something simple again 1 plus 1 notice that the 1 &amp; 2 there are no 1 notice that the 1 &amp; 2 there are no 1 notice that the 1 &amp; 2 there are no there is no carry about the you know the digits that you need to do so let's just look at 1 plus 1 which deliberately force us to looking at the carry overs so 1 plus 1 the result it's 2 and the binary is 0 1 0 so we can see we find those numbers have a 1 bit in the ones position so that suggests that we have to carry over that to the per tooth position so we can do an end operator between this 2 number to find the position we need to do the carry over and the to carried over to the next position it's done by doing a left shift so this is how we obtain this so let's look at a some example that will actually involve both of this step to do this calculation by doing bit manipulation so simplest example is just 1 plus 3 we get a 1 a 0 1 3 is 0 1 so we do so we take a look at the exclusive all which is 0 1 0 and the carry is going to be doing an operator we have the 1 bit to the ones position from post number so similar to here we do an end operator to extract that and shift towards left which is 0 1 0 so that's shifted their version of the end so the question essentially becomes 2 + 2 we just essentially becomes 2 + 2 we just essentially becomes 2 + 2 we just continue this procedure so look at the exclusive all and the shifted version of the end operation the exclusive all here is obviously 0 because the number 2 numbers are the same so it's 0 the we shift of the end it will be 4 so we translates this summation question into basically we decompose the summation into a series of exclusive all and shifted the end operation the exclusive is that for that digits we don't have overflow we don't need to do the carry and the end operation is basically to extract the bit positions where we do have a / follow we need to where we do have a / follow we need to where we do have a / follow we need to deal with and the shift to left by 1 is 2 you know get the carry in their right position then we just resume to this calculation until one of the result from either exclusive or the shifted version of the end becomes zero then we just add those one last time doing exclusive all between those two numbers one last time we can get the final result which is four and that's what we be looking for so right now using the positive in the lumbers it's all looking fine the problem here is just that the actually have negative numbers so that's a little bit funky let's grab a binary for negative two and we know that when we actually shifted the negative number towards left at least in the signed version that's undefined it's a problematic usually a the workaround is to convert that into a no sign but the thing that I want to do before actually just do the conversion is to just verify it's just a sort of simple example that actually okay to convert into unsigned because when we convert to unsigned and do the left shift the sign bit it's basically going to be truncated so we need to I guess at least to do some verification that this truncation would be okay so looking at negative two plus three so we definitely have a flip of the sign bit three is this so we do the exclusive all it will become 1 and the end coming over is going to be a 1 0 so then I continue doing this procedure we do exclusive all 1 0 1 the end operation shipped over its a 1 0 and then we do the just continue doing this exclusive all we get a very get a single one at the very end and when we do the end operation we get 1 in the sign bit and when we shifted that over by left by one we need to truncate that out and we have the 0 so the result is 0 la so if we use the unsigned version left to shift it just discard the one that's being shifted towards left and the result is actually ok so just a quick not proof but verifying that it's okay to use end operation and let the shipped by one you know casting that into unsigned to utilize this procedure to solve the summation of between negative numbers and positive numbers another verification I think I should do is to check out the other kind of extreme we have two negative numbers that's adding together so the case that we should consider is that if we have something like negative seven negative four which are you know sort of like you know it's only a larger side in an active regime and when we do the you know negative eight and negative seven when we follow that procedure we will get a whomp it in the end when we do the exclusive all the end operation and the shifted out towards left if we disregard that we're gonna have just a one and that might be problematic but I guess you can argue negative eight and negative seven you we wouldn't really expect it to have those two numbers as input if we're looking at the 4-bit as input if we're looking at the 4-bit as input if we're looking at the 4-bit signed integers because those two when we add two together it's gonna overflow so but following this procedure we pretty much gonna return positive one so you know so you might be problematic maybe we should just testing should test the two negative numbers has to be less than half of the maximum possible like less than or equal to otherwise we would just throw out some arrow I guess but if we just following this procedure for this negative eight and negative seven cases it's going to be automatic but nothing in the code nothing in the procedure will actually handle that yes so that's potentially some problematic Singh yeah so let's say let's just code this cook this solution up I'm actually interested as to see what it sees if I put the inter minimum there okay so we have something like the exclusive all let's just call this diff and another variable for the carry so the logic has just while the one of those is not zero we can just have a Charlie chose B actually because when we should choose B because we should just a carry thing and we should choose the carrier while the carry is not zero and we're gonna basically assign a to the diff to a exclusive all to a carry to be in this procedure so that when we determine whether we are terminate or not we just check whether B is nonzero what whether B is there when B is there or the a must have the also that we want so just going to do the death which is the exclusive or between this two number and the carry is going to be by casting by custody the end operation into a sign unsigned integer and then after that was shifted to the left by one and obviously we casted that back to integer so we basically truncate out the one I guess if we cast this 232 unsigned 32 integer when we do the leftist shifter you will already be to do the truncation so when we convert that back it's the truncation up and actually happens in the lattice shift and then we're just gonna assign those things back to a and B in the end we shall return a that's the sum of those two numbers so we just brought some examples yeah this is a hard coding example that I put there let me actually try something that's larger oh no it's so it's not for bit so how big is to new to the oh no sorry so one to the Saudi one okay I'm stupid this number so I'm just gonna throw this maybe a little bit smaller copy this price it's actually working why is this what is this number anyway it's a it's definitely overflow there and actually accept overflow ulcer so if we're looking at negative 7 and negative 7 when we do in the 4-bit negative 7 when we do in the 4-bit negative 7 when we do in the 4-bit version which we when we do the end operation and the shifted towards left and disregard the 1 carry we get one plus one and we actually result in some positive number which it doesn't make sense but yeah this actually where is my console there's actually but that's just how I think in the back end of their judge system it's actually doing this similar to this so yeah I would think that they will actually sell some arrows but apparently it's not anyway so that's the question yeah just doing exclusive all to add those that don't need to add those bit positions where you don't need to worry about the carry and using an operator to find that the little the position where you want to do the carry to put the carries on to the right position we left the shifter that were slapped by wand and to deal with the case that when we actually got shifted the negative numbers we recast that into unassigned and yeah this have undesired properties so I guess whether it's on a sign or signed better not to do the left shift so yeah that's pretty much it the question for today all right
Sum of Two Integers
sum-of-two-integers
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`. **Example 1:** **Input:** a = 1, b = 2 **Output:** 3 **Example 2:** **Input:** a = 2, b = 3 **Output:** 5 **Constraints:** * `-1000 <= a, b <= 1000`
null
Math,Bit Manipulation
Medium
2
344
hey everyone welcome back to my channel before we get started don't forget to click the Subscribe button if you want more videos about coding interviews so in this video we'll be solving the problem lead called reverse string so let's get started the problem is that they give us a string as an array of characters and the task here is to reverse this input array of character in place so for example if we have this input array of characters the results should start with the last character and so on and what we mean by in place is that we must reverse the characters and the array without using auxiliary data structures or we can say and constant space memory but in this video I will show you multiple way to solve it using the stack data structure and also without using it so let's start by the first solution let's say we have this input array of characters the first way to solve this problem is by using a data structure which called a stack and as we know the stack their structure is something called less and first out or we can say levo so the first thing we will do is iterate throughout the array of characters and at each iteration we're gonna add characters to the stack so once we add them all to the stack we're going to implement the lifo technique and we're gonna start popping from the stack and add to the output array so the time complexity for this solution is often where n is the number of character and the inputs array and the space complexity is often because we are using auxiliary data structure the stack list to store the characters and the input string so the second way to solve this problem and the best way and the easy way to solve 90 percent of array problems is by using the two pointers technique and the two pointers technique is an algorithm that involves iterating over an array with two pointers at the same time so the basic idea is to have one pointer that starts at the beginning of the array and another pointer that starts at the end of the array and we're gonna use those two pointer to swap the elements pointed to the start pointer and the last pointer and after that we move the star pointer to the next character and the last pointer to the previous character so until the start is equal to the end pointer or the star is bigger than the end pointer and that's how we're gonna reverse the array of character and place by using the two pointers technique so the time complexity for the solution is often where n is the number of character and the input array and the space complexity is all fun because we are not using any accelerate data structure to store the result that's it guys so let's jump at code in the solution so the first solution is by using the stack data structure so I start by initializing a stack and we iterate throughout the input string at each time we append or we add the character to the stack list so after that we set another loop that iterate throughout the input string and each time we pop from the stack the character and we assign it to the current index of the input string the second way to solve this problem is by using the two pointers technique so we'll start by initializing two punchers start at the beginning of the array and the end pointer at the end of the array then we set a while loop that iterate well the start is less than the end so inside the loop we call the function swap to swap the character at the start and the end pointers and after Double increments start monitor by 1 and we decrement the end pointer by one so let's define our swap function so the swap function take three argument the start pointer and the end pointer and the array of characters so the function swapped the character at I index and G index and we don't return anything because we are modifying the input string in place so at the end we'll have an output array reverse and place or we can write it in one line by using a method in Python called reverse which is an in place method that reverse the order of elements an array and have a Time complexity of often and space complexity of off one because it does not use any auxiliary data structure to store the result that's it guys thanks for watching see you on the next video
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. **Example 1:** **Input:** s = \["h","e","l","l","o"\] **Output:** \["o","l","l","e","h"\] **Example 2:** **Input:** s = \["H","a","n","n","a","h"\] **Output:** \["h","a","n","n","a","H"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
Two Pointers,String,Recursion
Easy
345,541
1,952
all right so this question is three divisors so you are given the integer n so return true if n has exactly three positive divisor and I'll just write return false so a divisor is actually like you I mean you can assume an equal to K times n and K is integer and it's also integer and then m is actually the floating number between the 1 to n so um let's briefly talk about like if n equal to two the divisor is what one and two right so there are two only so you return false why so you say uh two more by one this is what or two more by two mobile two this is zero and two mobile one this is actually what uh zero right like every single number more by one is always zero right and two more back to the two divided by two the remaining is actually zero right two divided by one the remaining is zero so uh you know no this is straightforward enough so uh let's talk about the next one so for the next one uh don't equal to four right so 4 divided by one right this is for the remaining is actually zero four divided by two this is two remaining 0 4 divided by three this is one dot three right so they are remaining so you don't count this one and fourth divided by four this is one remaining section zero so we just do get a little remaining and this is our list of the answer three and you return two so uh let's just know like we assume one is always about it then I have a deal with one D represent divisor so I have to make sure my return is D equal to three right so when it Traverse I have to Traverse from the two and all the way to the what all the way to the end and also my I'm going to assume my P is inside my full condition so D less than equal to three and I plus so if uh if the earn more by I is actually equal to zero you increment your divisor which is e and this is pretty much a solution so let me run it at time and space and this is straightforward a space is constant time is all of them and it's actually a little on right and yeah you break all the value earlier then you save a lot of time but whatsoever so this is the solution so if you still have question uh just leave a comment below subscribe if you want it and I don't think you need the bar for this one this is 34 enough and I'll see you later bye
Three Divisors
minimum-sideway-jumps
Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`. An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`. **Example 1:** **Input:** n = 2 **Output:** false **Explantion:** 2 has only two divisors: 1 and 2. **Example 2:** **Input:** n = 4 **Output:** true **Explantion:** 4 has three divisors: 1, 2, and 4. **Constraints:** * `1 <= n <= 104`
At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane.
Array,Dynamic Programming,Greedy
Medium
403
459
Ko Hi I am Aayushi Rawal and welcome to my channel today will gather September light to turn on this death problem repeated sub skin problem give this can be constructed by taking subscribe and multiple co subscribe till take English letters in chief output bullion true that your will see Multiple approach to this problem flu positive one ok are putting a easy that I will declare substring in this app let's you be easy a plus calculate the length of the input spring dels 49 will channel there string in ranwal I will be 0n fennel I will Be Always With Strangers Hey Baby Now Wicket And Minerals String With Easy Repeating In Loop subscribe The Amazing 999 2515 Will Be Result Will Be Amazed I Will Multiply subscribe The Channel Petai 10th Result Match The Thing This Vitamin Loop Returns True For Results For Example In Chief It is not possible to make a string with co subscribe abcd is form subscribe bc affairs for time and even with abc d abc akash roy ok knowledge video like subscribe and subscribe kare length offer initial input singh naav allu nor will calculate that alcohol play the length of the substring next will calculate that resulting substring meeting copy e that girl looted 5850 result in sub string and input stringer exactly this show will return as that this control below this line number for damini Hai one return truly dot in decade that they have not found subscribe search net banking ko subscribe pendi extra strength so in that case will return forms and a hua hai mein knowledge immediately koan a loot lo a dozen roy ok kya idli oo ko natural natak hai I have knowledge and such a meeting, take loot, another principle is a friend you for watching my video please like share and subscribe my channel they are true victims
Repeated Substring Pattern
repeated-substring-pattern
Given a string `s`, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. **Example 1:** **Input:** s = "abab " **Output:** true **Explanation:** It is the substring "ab " twice. **Example 2:** **Input:** s = "aba " **Output:** false **Example 3:** **Input:** s = "abcabcabcabc " **Output:** true **Explanation:** It is the substring "abc " four times or the substring "abcabc " twice. **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters.
null
String,String Matching
Easy
28,686
928
okay let's do this question this questions give me a hard time so you're given a network of nodes represented by this adjacency matrix so one if the nodes are connected and a zero if the nodes are not connected and those are corresponding to the index within this matrix and you're also given this vector of initial nodes which represent nodes infected by some malware and if two nodes are directly connected to each other then they're both and one of them are in the initial vector then both nodes are infected so we want to find out if we were to just remove one node from initial which node should we remove so as to minimize the total number of infected nodes so there is a very tricky case here so for example if you take say one is node zero node one is connected to two which is connected to three and we also have a node zero here that's not really connected to anything and we have that node one is infected so three is infected and node zero is infected so we have 0 1 3 is our initial nodes so which one should we remove from initial such that so as to minimize the number of total infected nodes so if we consider all nodes are in the network or infected nodes the number of infected the resulting graph will have all nodes infected because 2 is connected to 3 and 2 is connected to 1. so if we were to move say 1 for example the number of infected nodes we remove is one from because two will still be infected because it's still connected to three same case if we just remove a three in the same case actually if we just move zero all of them are still infected so what do we do here which one do we remove since all of them kind of remove the same number of infected nodes in the resulting network then we should return the node with the smallest index so we should return zero in this case let's consider another we have one two three and two four and we have that let's say two is infected and three is infected and we have three is also connected to five so the obvious answer is three right because if we move three then we get to we get two less nodes infected in the final resulting graph when we remove a node it also removes the edges as well that are connected to that node so that means four and five will no longer be infected in the resulting graph so we kind of see you can see that the number we if we can count the number of nodes that belong to an infected node that uniquely belong to an affected node is the highest for then we remove when we then we select that node to remove so for example three is connected to four and five there are two nodes that uniquely belong to three and one is uniquely belongs to two now what now let's see what happens if two and three are both connected to a node six here since six belongs to both two and three they both connect they both can be touched by six by two and three then six doesn't uniquely belong to two and three so we don't count six because and that kind of makes sense because if you remove two six will still be infected so if we move three six will stimulate affected because two is still there and the other thing to note is if three is when we try to find what nodes uniquely belong to three um we can't find one because to go to find one we would have to go through this infected node so we try to avoid going through other infected nodes to find other nodes yeah and that's basically it so what's the time complexity of this solution what we're doing we can do a dfs from each infected node and we could mark we can have a counter for each node and just increment a count and so that's so eventually two this one here will have a count of two uh four and five will have a count of one and one will have a count of one and then we have to do a device for all infected nodes again and just count the number of nodes that we see that have count of 1 and if we see a count of 2 then we just stop if you see a count of greater than 1 then stop there you know it's like a return condition so dfs to go through this graph is like a 300 by 300 matrix so the n goes up to 300 so that's like 300 squared to this 300 squared edges and dfs is complexity of dfs is v plus e where v is number of vertices and e's number of edges and we have to do this dfs for all the initial nodes and initial nodes can go up to n as well or let's just say it can go up to n so that means our final time complexity would be something looking like this n cubed well 300 cubed is like 27 million and assuming that the time complex the time limit is one second or something like that we should be able to solve this problem in time i mean fast enough why because if we take the rule of thumb that 10 to the power 8 is the number of operations that we can do in one second then then 2 to the power of then 27 million is a 10 let's say times 10 to the power of 6 that's definitely less than 10 to the power of 8 so we can do this in one second all right so let's start creating this up to check if the node is affected or not it's best to have this initial node in some kind of an ordered set so we can figure out if a node is infected in constant time um saying infected and go all right so for ins i in initial affected insert i you also need to keep track of the count of the vertices so vector and count and we need to go through a df and do a dfs on each of the infected nodes and make sure we need a scene array so we don't a time symplexy doesn't go overboard um maybe a boolean we can say maybe keep track of n as n is equal to the graph dot psi so graph the size is the number of nodes then we can take count is equal to a vector hence size n and starts at zero and we also have the scene to be equal to the vector of booleans okay so we need a dfs that will increment the count for a particular node for a particularly particular infected node starting at say v and we also need access to the graph so if we've seen this before it should be a vector of boolean so if we've seen v before then return turn otherwise set scene to equal to one true what else count of v should be incremented and then we have to go through each of the connected nodes so for nt i is equal to 0 i less than n plus i going through each of the infected nodes so the graph of v at i if that is the one right then do a dfs on this node which is i which might say u c u is better okay cool but uh so this has to be done for each of the initial nodes so for into you in initial oh and also i don't if it's if the note is infected so if u is infected then skip it so i could skip it up here if um you can skip up here just keep it down here it doesn't really matter so if infinite dot find so trying to find u is equal to oh does not equal to end so infinite end that means yeah actually i want it down here because if i put it down up here then that means i want the first one that i pass in won't be uh would exit immediately then now i want to continue cool and then here i want to go through for interview initial so for each of the initial nodes i want to do a dfs on that passing the graph and you yeah and that should initialize the counts for me and now i just need to return account and that takes in vector graph into v so let's do we're doing a dfs so we probably need to every stage clearing out the dfs so fill and fill the scene vector so begin let's seeing end with false so i haven't seen it yet and do this and you go through all the nodes so all the infected nodes again and keep track of the best answer so the answer is answer and let's say the number the count is equal to minus one initially and we do dfs count uh max count here so you can say into count is equal dfs count on graph with v which is actually should be you okay so if the count is less than it's greater than if the count is greater than max count or um the mac all the count is equal to the max count and u is less than the answer then i want to update the answer to be equal to u and max count to count at the end return the answer so now this part makes sure that we're training the smallest index and here i need to do it if scene v return so here i'm doing dfs so i need to make sure i fill do this line here because i'm doing another dfs how to do this again and let's go through here if i've seen it return otherwise i've seen it so set it to scene and also for so go through all of the loans and can all the connections if it's an infected node continue again and also if the count of u is greater than one continue um i need to count right so let's say end count is equal to zero initially my count is one because i'm counting the current node and it turned count plus equals to dfs of count for the graph at u then i'll return my count here okay there's probably a lot of bugs here but we'll give this a go defense of u takes in the graph as well somewhere so 34. uh oh wrong answer all right oh also if you could check if they're actually connected or not that's kind of important there we go okay and yeah this solution got me took me a while i haven't actually solved this question yet so i'm hoping that i've solved it this time around had so many wrong attempts let's uh let's try on one of my failed test cases oh my this one almost passed i tried dsu before it didn't work okay i'm like 70 percent confident with this solution yes awesome it's so slow though so the other i think i'll try again with dsu some other time
Minimize Malware Spread II
surface-area-of-3d-shapes
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\] **Output:** 1 **Example 3:** **Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length < n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Array,Math,Geometry,Matrix
Easy
null
1,732
guys uh so welcome to my legal serving section the easy part so 1 7 32 find the highest attitude uh sorry finding the audit sorry not 82 sorry so uh there is a bike going a road trip and the pro uh triple count has m plus one points at different uh altitude uh the bike the biker is starting his stop on po zero the rd is equal to zero right so basically okay you should i mean you can call height okay so there is so starting from height zero and go to high one high to high three up to high in so total we have uh high end plus one so we have high n plus one points and the height zero is zero okay so you are given an integer array so you are already right issue right it's a ray and each element is integer of length n uh where again i is the net gain it means that at right that gain attitude the altitude will hit the point i plus one and return the highest of a point okay so again it's minus five one five zero say uh minus seven or negative seven so i start from zero right the node start from zero and add negative five so negative five and i add one negative four and uh plus one because we add five got one we get at zero one and negative six and height is 1. okay now this guy is 0 okay so now we see the idea is very easy right the idea is that we just you know explanation just for our explanation we just create a list of these oh of this guy and we've tried to find a maximum of it try to find the maximum of this list okay so the idea is that we know the length of the gain right so we create at least which is start on zero and the length of m plus one okay so uh so that means i initial i initialize the list which is zero as this yeah for example if i use example one and i start from one and the length n plus one i just use the first guy added uh so i so the second guy is just the first guy at the game the first guy in the game and the second guy just the previous guy added the game right so basically at least i the ice guy is the i minus one guy plus the gain i minus one so for example if i is one then means least one is the least zero is zero plus the again zero right so this recursion formula will just give you the at least one so let's maybe print uh prints uh one example and around the test code to let you guys see uh this list will exactly be this guy right exactly the same sorry and then we finally return the max okay so this guy this will be just the answer so since you guys know the trigger right so yeah the rest is distributed okay uh but i mean we can still we still solve it right so okay so i will see you guys in the next videos be sure to subscribe to my channel thanks
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119