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
424
in this video we're going to look at a legal problem called longest repeating character replacement so we're basically given a string and a integer value k and we want to find the longest repeating character after we can be able to replace k characters right if we were to have the chance to replace k characters in a string what's the longest repeating character right and we want to return the length of the longest substring containing the same letter right after we perform uh these operations right now in this case we're only contained with uppercase english letters right so the string we're given is only contain uppercase english letters and we want to return the longest substring right so in this case you can see here in this example we'll just have to replace either a or bb to return us four which is the longest repeating character right and uh in this case you can see also we have another example like this we can be able to uh replace one character in this case we if we replace this b right here right this will give us four a's if we replace this a right here this will give us 4b right so we're not interested which character we replace we just return we just want to know what's the longest repeating right consecutive characters after we replace k number of times so how can we be able to solve this problem well to solve this problem we had to do is we had to use the sliding window technique and the reason why we use lighting on the technique here is because we want to find the longest repeating uh character after we perform k-number uh character after we perform k-number uh character after we perform k-number operations for the character replacement right so whenever we want to find the consecutive right the longest window or longest size or longest uh length of the substring right for a certain condition we always try to choose something using sliding window right so in this case um for our sliding window technique we basically want to expand our window if our window continued to satisfy the condition right so in this case what's the condition that we're trying to satisfy is if the number of operations right if the number of character replacement right if so within our window right if number of character replacement is less than or equal to k then that means we're still satisfying right that means we can still expand our window because the next character could be the most frequent character that we have in our window so we can continue to expand so let me show you an example here right so you can see this is our string and in this case what we can do is that we can try to first expand our window right so now we have a and then what we're going to do is we're going to continue to expand our window because right now this is the most frequent right so once we reach the b okay so now we have k so in this case we can perform uh we can be able to replace two maximum two characters in our window right to get the maximum to get the longest repeating characters so in this case we still have it right so number of character replacement right we have one number of characters replaced in this case just b once we get a that's still good once we get the b right here this right here is still okay right because we can continue to expand because right now we can only replace two right in our window we place two already right so we have this b and this b we're going to replace that to a right because a in this case is the most frequent characters right so what's going to happen then is we're going to have to expand again so once we realize that okay you know what um b uh we're going to replace either three a's or three b's which is bigger than k that means we have to start to contract our window so what we're going to do is we're going to start contractual window right so now what's going to happen is now you can see we just have to replace two a's to match this condition but if we but while we satisfy the condition if we keep track of the longest repeating character length right before that right before if i go back like right here right while we looping through our window right while we're sliding our window we can keep track of the length the max length right in this case it uh in this case is five right and then what's going to happen is that once we expand to here we don't satisfy the condition now we have to shrink our window so in this case we move to here and then we realize that now we satisfy the condition we check to see if our current window size is bigger than the max length in this case it doesn't so it's still five right so then we expand again so same situation happen right so in this case we have three a three b's so in this case we all we have to do is we have to shrink our window again so now we shrink our window now our windows balance right satisfy the condition so what we had to do is we basically just going to update the max life in this case the max line didn't change right so that's basically how we're going to solve the problem but the question is how can we be able to get the number of character right how can we find number of characters to replace so well there's a couple ways we can do it right so one way we can do is we can basically have a table just like how we did it in the sliding windows playlist series right we can use a table right a hash table keep track of how many characters appearance right there in uh each and every single character's appearance right so maybe like when we're here right we can keep track of there are three a's in our table and one b's in our table one b in our table right so once we get to here okay so what's going to happen then is that if i want to know the number of characters that we're going to replace first what i have to do is i have to find the um the maximum right the most frequent character in this case is a right a appears three times and the size of our string so four minus three will basically give us the number of characters that we repli that we're going to replace right in this case it's just one degree which is b right even though if let's say there is more than one right let's say there's a c right it's still going to work right so now our size is five and five minus the most frequent which is basically just going to be two right so those are two characters that we're going to replace right so that condition is still satisfied right so in this case all we have to do is we basically going to loop through our table right we basically iterate our table and then we trying to find the maximum frequent character and then use that to find out number of character to replace and then we can be able to use that to satisfy the condition right but in this case what's going to happen then is that this will give us a time complexity of big o of n times 26 right in this case we have to iterate through the entire table which has a size of 26 because like the question mentioned right there's only going to be uppercase characters so we're assuming that there's 26 characters so n times k 26 will be our time complexity right so how can we be able to avoid that how can we be able to bypass this iteration right how can we be able to improve the time complexity well to do that what we can do instead is we can do similar but having a variable called max frequency right that basically keep track of the maximum frequent character because all we care about is if we satisfy or don't satisfy the condition we don't care about um if the most frequent character uh the most frequent character or yeah the most freaking character number um is most up to date right so we can do is that right out of the start right because just like i mentioned when we expand our window we're not only going to update our table right for example if we're starting here a is one right and we also have to update the most frequent so the most frequent initially zero so once we see that this character appear one time so we update them the most frequent in this case is one right and then we try to see if it's satisfying good condition and this is our condition that we check right we check the size of our life right just like i mentioned we want to know if number of character replacement is less than or equal to k right if it's less than or equal to k is good but if it's bigger than k then what we have to do is we have to start shrink our window right so this is what the condition is checking right now so if it in this case it doesn't right because case two and then the size of the our window is one y minus one is zero right so we continue so we add one we change that right and of course before we go to the next iteration we have to update our max length in this case one right so once we get to once we expand our window right now a is two right and then in this case we calculate this so in this case is basically uh two minus two right because the most frequent noun is two right so it's basically zero right so now we expand our window again so now we have b we put b in our window so in our table and then we basically see if most frequent is bigger than the number of appearance for b in this case most frequent is bigger than b so we don't change the most frequent and then uh we check to see right in this case of course we update the max length in this case max length three and then number of character replacement in this case is basically just one right so we're replacing just one so then we continue right so we move to a so we change this and then we and then for the most frequent character it now is going to be three right and then in this case we check to see if this condition is satisfied in this case it doesn't so we don't shrink our table right sorry we don't shrink our window right so we continue to move our forward before that we have to update the max length so now we have four okay so we move one to the right so in this case b appear two times and then most frequent is still three right and then we check to see if it can satisfy the condition in this case it doesn't right in this case the this is five minus the most frequent is basically two and two is not bigger than k right k is this right so we continue then we have b then what's going to happen is that we update b um sorry we have to do this nope we don't do this yet um yeah should we do this um and then basically what's gonna happen is that we know that the size is six minus the most frequent which is three bigger than k so therefore we had to shrink our window so what's going to happen then is that we basically move the left pointer we overwrite this right we change the value of a in our table and then in this case we don't really have to change the most frequent right because in this case if even uh after we shrink our window right we don't have to change the most frequent because all we care about is if we if this condition satisfy right so now we know this condition doesn't satisfy because in this case our size of our um our size of our window right is first of all smaller right so therefore in this case it basically um basically it will bypass this condition right so now we don't have to shrink our window again right because our size is smaller so then we continue right so if we realize that our max frequency is bigger than this number then we have to change the max frequency so in this case we expand so let's say in this case it in this case is b right so let's say this is b so then we expand and then we change b to four okay so now the max frequency now is four right and then what's our max what's our life in this case is going to be uh in this case we're going to have six right six minus the most frequent is four right so therefore it's two here so now you can see we don't have to iterate the entire table to find the most frequent character right so in this case in the code it's very simple just like how we did it in the other sliding window questions we have our window we have our max life and most frequent uh variable to keep track of the most frequent um character right appearance so first we basically iterate right so we first expand our window and we update the most frequent um in this case we check to see if it's most frequent or the current character's frequency right so we should only shrink our window if we need to replace more than k character right so in this case which is basically uh want to know um if the number of characters are we going to replace is actually bigger than k if it is then we had to shrink right so in this case this is the size of our window the most frequent uh character's appearance and then in this case if this condition is satisfied we have to override them we have to change the map and then we have to move the right of the left pointer one to the right and at the end once we have our window satisfy the condition right once the window it um does not satisfy this condition does not we don't have to shrink our window anymore then we update the max length and then we move the right pointer one to the right so just like how we did it in other sliding window questions this is very similar and the trick is that we have to be able to use a most frequent variable to keep track of the most frequent uh character's appearance right so basically you can see this is how you solve the problem and this is how we bring the time complexity down to big o of n where
Longest Repeating Character Replacement
longest-repeating-character-replacement
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times. Return _the length of the longest substring containing the same letter you can get after performing the above operations_. **Example 1:** **Input:** s = "ABAB ", k = 2 **Output:** 4 **Explanation:** Replace the two 'A's with two 'B's or vice versa. **Example 2:** **Input:** s = "AABABBA ", k = 1 **Output:** 4 **Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA ". The substring "BBBB " has the longest repeating letters, which is 4. **Constraints:** * `1 <= s.length <= 105` * `s` consists of only uppercase English letters. * `0 <= k <= s.length`
null
Hash Table,String,Sliding Window
Medium
340,1046,2119,2134,2319
1,306
hey everybody this is larry this is day 29 of the lead code november daily challenge hit the like button hit the subscribe on drum and discord it's almost to the end so you know make sure i don't know you finished the month in a strong way and this is jump game three okay so which variation is this so given an array you're at start and you're trying to get any index of zero okay so it seems pretty straightforward maybe i think the only tricky thing is thinking through their psychos um and what i mean by that is that you know let's say you have to use one and one right um you have someone like this you will jump back and forth from the ones and that's not going to help you and you know when the infinite loop however the key thing to make an observation is that um when you start at the start um you know it doesn't make sense to go to back to place where you've been because well one is that's not gonna be the shortest path so you can find think about it in terms of shortest path um and i think that may be it because if you have to go back to the place that you've been to then that means that you've already visited right so i think from that we can just do a um a breakfast search and yeah and that's what i'm gonna do let's do a breakfast search um to kind of go you know start from the start and let's see if we could reach any index with uh or any array element with um you know n right uh with zero value uh i don't i actually now look at the complexity just to make sure uh it's gonna be of n um because for each element we only go either left or the right so the only two edges so they're gonna be all n edges as well so that's why i don't really think about it because i knew that this one is going to be off and um so i didn't need to worry about the constraint but let's get started so we get started on the queue let's have um yeah like a scene type thing and as you go to the length of the array a scene is just we haven't seen it yet from to map this to the array element and then now we go scene of start as you go to true we uncue it so append start and then that's and that's pretty much it uh and then we could just do our standard breakfast search you can also do that first search if you want to be clever about it but um i think that should be okay so you're careful about handling the visited states so yeah so the way that i read it is that now as you go to uh or maybe just call it indexes you go to the first element we pop the first element and and yeah so if array of index is equal to zero then we return true right if we go all the way through the end then we return to oops we turn force the cycles don't help us as we said um so yeah so now we just have to check the two things right which is um yeah for next in the oops next index i can spell next index and let's just say uh what am i index plus array of index or index minus array of index uh check that if next index is between 0 and n if it is and oops and not it has not been seen yet then well we set it to scene and then we appen the next index and that's pretty much it i believe let's give it a go i'm just scrolling up to put more test cases in two i don't know just add another one i have to think about zero cases and stuff like that uh maybe not let's see i guess that won't work so okay from zero to zero only what does that mean maybe i misspelled the constraints but uh hmm is that a oh i see i did not realize that constraint but uh but i think we're still mostly yet done uh despite me wasting some time here on just double checking let's click on submit let's go yep uh and as we talked about we look at each cell once uh so it's gonna be o of n because for each cell we only look at left to right so that's o of two uh or of two which is all one obviously um with constant amount of operation or this is all one so yeah and in terms of space we use a deck and we have a scene boolean uh array so it's going to be also organ space um yeah so this is it ends up being a straightforward by rush let me know what you think hit the like button and subscribe and i will see you at the end of the month tomorrow bye
Jump Game III
minimum-absolute-difference
Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0. Notice that you can not jump outside of the array at any time. **Example 1:** **Input:** arr = \[4,2,3,0,3,1,2\], start = 5 **Output:** true **Explanation:** All possible ways to reach at index 3 with value 0 are: index 5 -> index 4 -> index 1 -> index 3 index 5 -> index 6 -> index 4 -> index 1 -> index 3 **Example 2:** **Input:** arr = \[4,2,3,0,3,1,2\], start = 0 **Output:** true **Explanation:** One possible way to reach at index 3 with value 0 is: index 0 -> index 4 -> index 1 -> index 3 **Example 3:** **Input:** arr = \[3,0,2,1,2\], start = 2 **Output:** false **Explanation:** There is no way to reach at index 1 with value 0. **Constraints:** * `1 <= arr.length <= 5 * 104` * `0 <= arr[i] < arr.length` * `0 <= start < arr.length` a, b are from arr a < b b - a equals to the minimum absolute difference of any two elements in arr
Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array.
Array,Sorting
Easy
2248
1,057
hey what's up guys John here so this time let's take a look at another lead called problem 1057 Kemper spikes a very interesting problem I'm gonna give my own vote here so there's a campers represented as a to degrade and on each of the coordinates here they're like some bikes and some workers each often will be represented as a coordinates x and y right and then you need to assign the workers each worker with a bike and the way your sign it is the you have to assign basically you have to sign the talk you need to choose every time you need to choose a pair right a working by worker and the bike whose host distance the distance is my heart in distance which basically deal the absolute value between the x-coordinates plus the absolute value of x-coordinates plus the absolute value of x-coordinates plus the absolute value of the y-coordinates so every time the of the y-coordinates so every time the of the y-coordinates so every time you need to sort do a sorting and you need to choose the shortest distance for all the unsigned workers and bikes right basically that's what do you know I'd ask you to do for example here right and we have a we have two workers and two bikes right so add a big added fur at the very beginning right see the distance between workers 0 and the bike 0 is 1 plus 2 is 3 right history and workers between and the distance between the worker and the bike 1 is 3 plus 3 is 6 right and how about worker 1 the distance between worker 1 and bike 0 is 2 right and then the distance between worker 1 and bike 1 is 3 so in this case so the first assignment will be between the bike at 0 and 1 right because 2 is the smallest distance among all the distance at this moment right basically for a bike for worker for workers 1 will be assigning bike 0 so the return result will be the indexes of each worker that the bike index of each worker it will be assigned so in this so the first one will basically will assign the worker 1 with spikes 0 that's the 0 and second one will be will sign the worker 0 with bike 1 right so basically that's the that's this problem right and oh and if there are like more than one ways you can if that if the there's a tie between the distance we also restored by the worker first and then the bike second right the index of worker and the bike so okay so that's the description of the problem right so I think it's obvious that in order to get for each time the other to get the smallest shortest Mahajan distance we have to calculate basically we need to maintain the distance for each worker to all the bikes right and then what and then we once we have the distance and when we do the meet with the assignment we will be using a priority queue right so basically we'll put added we're using a priority queue to maintain how should how can we a wish I mean among all the workers and the smallest distance the smallest bikes for that workers which one we need to be performed first right because with that we need to pick the shortest Manhattan distance for all the workers right and then we will be assigned that worker first and then the second and so on so forth and till we assign all the other workers to a bike with a bike right so okay let's try to code this thing right so let's see first thing we need to have a distance array right to store all the other the distances for the workers and the bikes right so we do a I X workers and XY right in enumerate numerate work workers right and then we do so for each of the workers will be creating a new array to store the out distances for current workers right so we'll be having like a bike right distance gonna be a array right so 4j this is going to be a X bikes right and why bikes here's why worker in enumerate bikes right so what do we do here so for each of them we do a bike dot distance and that app and right basically we add all the distances for current or current worker to this bike distance gonna be what so that's going to be at Apple right since we are so since we first will be sorting by the distance but if there's a tie between distance will be will store the bike the index of worker and the bike that's why we need to have a topo here and the first one will be the Mahajan distance where it's gonna be X workers miners X bikes plus absolute value of y workers miners y bikes right and then that's the first element second one will be the workers index and if this one is the same we sort by the bikes index right so at this moment I'm sorry so in the end we will be adding a distance that depend this thing to a bike distance right basically here this is like the list of each worker each workers this tends to are the bikes right okay oh sorry before we are a pen this thing to that the distance well we need to sort this thing right because the reason we need to sort it is the among offered okay so for the same for the specific workers we always try to get just we always try to get the shortest the closest the bike for this worker right that's why we sorted and it was sort it by now we can sort it reverse or we can just assorted to a like regular sort and then at mu when we get that when we got the try to get that's the first element we can do a pop 0 right I think so yeah or we can sort it in a reverse order and which to a regular pop I would do every you know one out of a sort here so remember so now this the first a diamond is this is the closest bike right for this current for this a worker right now like we said we need to have a queue priority queue right to store to maintain right to maintain the which worker we need to assign a bike next right so at the beginning right sings okay so now we have a distance right the length of the distance will be the size of workers right basically this thing stores each workers bikes distance sorted from the closest to the farthest right so now we just need to get for each workers basically work we need to get all the workers shortest I mean closest the bike for that worker right so how do we do that so and then we are we put it into a priority queue how do we do this we do for each of the workers we do for distance in distance right for each of the distance we will be doing a distant dot pop right pop zero basically all right since we are yes so the reason we do a pop here is because so once we put once we pop I find get the current is small our shortest bike for this workers will be remove it removing it from the distance so that later on when we need to find the second one we can just keep doing the pop right or we can maintain it index but that will be for each of the worker which will be too much of a hassle so basically we just every time we do a pop and this priority kill right it will basically it was safe it will be maintaining for each of the workers right the current short is the bike for that work for that worker right and the length of the priority queue will always be the iron assign workers length right so at this moment the length will be the length of the priority key will be the same length of the workers right so and then we just need to sort it basically we neither sorted we just do a heap queue here to heap cute yeah he be fine right there's a function called heapify and we just said to a priority queue it's simply just sorted right we can either sort this thing where we can just a user like heap a heap to maintain the to make sure the smallest one is always on the top right okay so once we have that and then so we need to assign right so now we need to a sinus thing as to what the length will be the workers right the length will be the workers length that's what we are okay so we need to keep doing it until we assign audio to the workers right with a bike right so how do we are how do we mint while assigned by okay so we're gonna define assigned bike set because once we assigned a bike once we sign the back a bike for this worker and that bike may might also be a peer ISM in some other workers right so in that case we need to keep like a set variables to attract the or what are the bikes we had been assigned and then if he's already been signed in with just move it to the next bike for the worker right so and then switch to this I signed bike is less than cleansed up the workers right so that's our stop condition basically Eva if each worker has assigned a bike has a sign up with the bike and we just stop right and then what do we do here right so that's gonna be that distance right so every time right we pop did this like this Q basically that will basically every time we're trying to get the smallest value for this from this priority Q right work her bike right and then he calls to what equals to the heap Q dots heap pop right eeep pop right and then the priority queue right the distance here is not it's not useful we just we can use it or use it like this they stood for that but I'm just doing a distance to make it clear okay so every time right every time we see a bike here right I'm gonna see your bike and look remember we're doing a heap pop here right so each time we pop a thing we know that we're trying to assign a bike for this worker right because remember this is a typo right and first we check right first we check if the bike has not been assigned before right that's the happy path if the bike is not in assigned bike set right what do we simply set the answer right so the answer will be the worker and the bike right and then next we just simply add this bike to the signed bike set right bike okay cool that's a happy part so the house is a little bit tricky here okay let's take a look let's see if a bike has been assigned before right so what does that mean it means I will try to draw something let's say there's a work right here worker 1 right and there's like a worker 2 and workers through here let's say this is our priority queue right and in the priority queue let's say we have these three art apples here and the first one is a priority queue is the workers one at the distance let's say the distance is right let's both of these things - and worker 1 and the bike one right how about - let's see in the priority how about - let's see in the priority how about - let's see in the priority it's possible right we have another thing we have a let's say the worker one worker 2 there they're the closest bike for worker one worker 2 up both bike one so then we'll be having distance - so then we'll be having distance - so then we'll be having distance - worker 2 it's bike one all right we don't care about this dislike what a worker 3 because the water Walker 3 will behave like a hard hire like distance which will be added later at it won't be popped by this a priority queue right so let's assume we have this thing right when we do a pop right into a pop we'll be popping the first one because with the same with the tie here we will sort by the workers first right so in this case the worker 1 did this a diamond will be popped right and then we just assign this buy a bike one to the worker one right and then we add this bike use bike to this assigned bike now this is done right now the second time when we try to do a pop right the worker to the decide this one will be popped right and when we pop this one we see okay now we're trying to assign bike one to worker too right but then we see we can't write because the bike one has already been assigned then what do we do right I think about it so if a bike has already been assigned what do we do in that case right we need to find the next closest bike for worker - right next closest bike for worker - right next closest bike for worker - right because since bike one is not available then we have to find the next closest bike for worker - how right room bike for worker - how right room bike for worker - how right room remember we for each workers we sort all the bikes distance from smallest from shortest to the fourth to the farthest right so in this case I'm gonna do like to stop here next shortest bike right it goes to what we do a basically we'll get the next candidate from this distance right just like what we initialize our priority queue here right we do this thing again right we do a but in this case we know the bike are the workers here right distance the worker is the current worker right but then we need the next bike we do another pop zero right and that big since this one the third the first pass candidates not available and then we have to resort go to the second best candidates right which is the top the first one on the left on the under on this array on the list of the in this distance right then we do what with now we're adding this was in back to this hip queue right we were heap killed out hip push right pushes into hip queue priority queue dots next shortest bike right then because the next one may not be the next available then because the next best next short is the bike for the current worker may not be our next round a pop the next around candidates right that's why we need once every time we have a new candidate we need to do a hip push we ask the hip queue try to sort this thing for us so that the next time we'll have the next available candidates right and in the end we just return the answer mm-hmm end we just return the answer mm-hmm end we just return the answer mm-hmm and it should work see all right cool let's try to submit it cool it works and so okay so let's recap okay so first we restores resource audit for each workers we stores all the distance for that workers all the bikes distance for the for that workers and we sort the distance either way basically we sort the other bikes distance for the worker and then we are using a priority queue to help us decide who is the next worker that needs to be a sign with a bike right and then we also keep maintaining assigned bikes here because the two workers may both have the same bike as the next of as the shortest the bike right so if bike has not been assigned before and then it does a happy path which we just simply signed this answer which current workers index with a colonel bike index and then we add spike to the set if not here's the part we need to take more extra attention here then if the bike has already been assigned which means okay is the current bike is not available for the current workers then we need to go to find its next shortest bike for the current worker and then we push this result to the Q the hip Q again and then the net and so the next time in the wall it will help us find it find decide which one which workers the next one to assign and how can we make sure each of the worker will be assigned with a bike right remember so at the beginning the priority Q each element represents the worker right basically so in the priority queue there won't be any duplicate workers adamant so that's the key things we need to remember here right because when we create this distance for each worker it will have its own element in a distance so that's why from the beginning the priority kill each element is unique for adult for that worker that's why and when we do a heap push and we also pushed the element for the same workers right so which means every time when we assign a workers with a current with the an element from the heap we are always signing that a new right and since we know when we when this hip queue is empty right basically that's when this like assigned bike is the same as the workers right then we know all the workers has had already been signed with a bike okay I think that's the best I can explain so far for this problem yeah and yeah I hope you guys enjoy it like it not it even not enjoyed but don't hate it part of my explanation sometimes yeah out I'll keep him I'll keep improving and yeah thank you so much for watching the videos and obviously you guys soon bye
Campus Bikes
numbers-with-repeated-digits
On a campus represented on the X-Y plane, there are `n` workers and `m` bikes, with `n <= m`. You are given an array `workers` of length `n` where `workers[i] = [xi, yi]` is the position of the `ith` worker. You are also given an array `bikes` of length `m` where `bikes[j] = [xj, yj]` is the position of the `jth` bike. All the given positions are **unique**. Assign a bike to each worker. Among the available bikes and workers, we choose the `(workeri, bikej)` pair with the shortest **Manhattan distance** between each other and assign the bike to that worker. If there are multiple `(workeri, bikej)` pairs with the same shortest **Manhattan distance**, we choose the pair with **the smallest worker index**. If there are multiple ways to do that, we choose the pair with **the smallest bike index**. Repeat this process until there are no available workers. Return _an array_ `answer` _of length_ `n`_, where_ `answer[i]` _is the index (**0-indexed**) of the bike that the_ `ith` _worker is assigned to_. 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:** \[1,0\] **Explanation:** Worker 1 grabs Bike 0 as they are closest (without ties), and Worker 0 is assigned Bike 1. So the output is \[1, 0\]. **Example 2:** **Input:** workers = \[\[0,0\],\[1,1\],\[2,0\]\], bikes = \[\[1,0\],\[2,2\],\[2,1\]\] **Output:** \[0,2,1\] **Explanation:** Worker 0 grabs Bike 0 at first. Worker 1 and Worker 2 share the same distance to Bike 2, thus Worker 1 is assigned to Bike 2, and Worker 2 will take Bike 1. So the output is \[0,2,1\]. **Constraints:** * `n == workers.length` * `m == bikes.length` * `1 <= n <= m <= 1000` * `workers[i].length == bikes[j].length == 2` * `0 <= xi, yi < 1000` * `0 <= xj, yj < 1000` * All worker and bike locations are **unique**.
How many numbers with no duplicate digits? How many numbers with K digits and no duplicates? How many numbers with same length as N? How many numbers with same prefix as N?
Math,Dynamic Programming
Hard
null
382
okay guys so this will be our seventh problem of the late code january 2022 the daily problems and today we are going to face the problem linked list random node its index is 382 and it is the medium type problem of the lead code okay so the prerequisites required to solve such type of problems is like you must be familiar with the probability type of thing and like finding out the probabilities of choosing some set of values from a given set okay and also you need to be aware about how to generate some random numbers for a given in a given range okay so if you're not like habituated to do such type of things then no need to worry about we will explain how we will explain all those things in this video okay so without wasting our time let's begin given a single linked list singly linked list okay and we have to return a random notes value from the linked list okay so linked list will have some size let's say n and we have to return some random node value from this linked list okay so each node must have the same probability of being chosen okay and we have to implement this using these two methods there will be a method initializing the head and get random also that will choose a random node that it will be a totally random from the list and we have to return its value okay and like we need to take care that all nodes should be like have the equal probability of being chosen okay so also there will be some follow-up you can see there will be some follow-up you can see there will be some follow-up you can see over here what if the link list is extremely large and its length is unknown to you and we can solve this in without using an extra space or not i will discuss both these things okay so uh first talk about the constraints you can see it's 10 raised to the power 4 so we would be considering only o of n solution uh oven time and often space okay so there are many ways to solve this problem like you can solve in o of n time and o of n space and the next way is like you are going to solve the o of n time and of one space so using o of one space will satisfy this follow-up one space will satisfy this follow-up one space will satisfy this follow-up okay and for this follow-up you would be okay and for this follow-up you would be okay and for this follow-up you would be considering only stream of characters sorry stream of nodes okay so let's understand this the basic solution for this problem then we will move up to some tricky solutions okay so let's begin so where is my pen okay so let me choose some bolder node so what is given is like we have some nodes being linked over here and we need to find some random node anytime random node which has equal probability of being chosen so we all know that there is a function rand function in c plus or if you're using prepping some other language there must be some function uh some mathematical function that will generate some random numbers okay so now i'm talking about o of n time and o of n space solution okay then we'll move further to some best and efficient solution so what we are going to do is we will store all the node values stole all node values in an array so this will like this will have some this will store some memory but it will like the rand function will work efficiently how we will be knowing the array size and array size at any time if we have been asked to find out the random node we will just find out the random index random modulus and it will give us some random index and we will just return the value present at that index okay so this will work in o of n time y o of n time because we are storing the all the nodes values in an array i trading for n times like the entire linked list and of n space because we are utilizing an extra array to store the values okay and rand function will work in of one time okay so let's look over the code uh yes i've already submitted let's look over this one yeah you can see that you have taken an array and for like storing every values in this array you can see this will take off and time for pushing back all those values and the next will be like in get random function we will just uh finding out the random value like first we will generating some random number then i am taking the remainder of with the number n which is the array size so all the random numbers that any random number will be generated it will be in the range 0 to n minus 1 both inclusive and then we will return the value present at that index okay so this will satisfy the constraints and problems constraints of the problems here so what about the other solution so you can see i have submitted more solutions okay what about the other solution can we do in o of end time and of one space obviously we can do so uh let us understand like this is the like a very little part of the actual problem that i am referring to is the reservoir sampling algorithm okay so let's understand this reservoir sampling algorithm so let me write down reservoir algorithm okay so we will be talking about this reservoir sample so what will happens in reservoir sampling algorithm is like we have been given some reservoir let's say of size k equal to 3 and we would be giving we'd be given a stream of data okay so we've been given a stream of data of some size n okay and uh at each time like we have to report that what is the uh current values present in the reservoir okay so what are the total values present in the reservoir okay so let's say we have n size s5 so what will happen is like we anytime we have to report any three values and some two values also let's say a b c d and e so like the values at now can be abc or any value that can replace like any value from d or e can replace any value among these three elements so the value at any time would be like d b c and it can be like a and e so this is the value present in the reservoir this can be our answer okay so the key point to solve such type of problems is like how to find the like every element should have the equal probability of being chosen okay so if we choose if we have some n length stream of characters then we would ensure that at the current time if we have been asked that what are the elements present in the reservoir there should be three elements right any elements let's say x1 x2 and x3 and the element that is appearing over here in the reservoir should have equal probability that is the probability of coming of a to in this reservoir must be matching with the probability of b coming into this reservoir must be matching with c as well as d as well as e so how do we ensure that this should be done in the efficient way okay so first i will explain that what we are going to do in this algorithm then i will proof it out how this is going to lead that solution okay so let's move on to the uh like what we are going to do in this algorithm reservoir sampling algorithm okay so what we are going to do is like we have a stream of characters stream of values of size n okay and we have to report it for the reservoir of size k okay what is the values random values that can be in the reservoir at any time okay so what will i will do is like suppose n is five a zero a one a two a three a four and a five and k is three so reservoir sampling algorithm sees that first we will stored the first k values from this stream of characters okay so a0 a1 a2 will be filled over here and when a3 comes okay so when a3 comes we will find out the random value between the range this range to this range means a0 a2 a3 sorry a0 a1 a2 and a3 that is from index 0 to 3 any random value in this index okay and let it be i and if i is going to be like less than or equal to the size of reservoir which is here over 2 because i am considering zero based indexing then we will swap out swap value present at let's say the index i would be like array of i swap value present at area of i and the array of current value j where j is now denoting for the element e3 okay so what you are getting from this is like reservoir sampling algorithm says that at any time for n length stream of character suppose i am talking about this and where it is where this value like a5 then what we will do is like we will generate any random number in the range 0 to 5 right and if that random number let's say i is the random number is going to be like less than or equal to 2 which is the result avoid size you can see then i will swap out the value present at this index area of i and a5 okay we will swap out these two values okay and if we have been asked that what is the current state of reservoir what are the elements then we'll report out the current elements present in this reservoir okay so this is the reservoir sampling algorithm so you guys must be wondering that how this solution is going to work and what is the proof of this solution okay so let's try to prove it okay so let's take a reservoir of size k 0 1 2 where k is like 3 okay and we have some stream of characters uh of size n okay so it will like it will include some more characters let's say this one and this one okay so it will be like index three index four index five okay so to prove that this solution would work perfectly we must uh have to prove what you must have to prove that probability of any item let me write down clearly probably the probability that any item stream of i note that any item of stream of i means this item this any atom from this stream of i should be what the probability that it should be included in the final reservoir should be exactly equal to k by n because that each element is going to be like each elements wants that this should be included in the reservoir and there are k spaces so it should be like probability that any item of this stream of i should be included in the final reservoir should be k by n then i can say that yes this method is going to be correct okay so we are going to prove this in two ways so first i will prove for the elements for i belonging to let me use a zero based indexing so i will use the elements for 0 to k minus 1 if i can prove that any element of this stream of i that is in the range from 0 to k minus 1 0 best indexing has the probability to come in the final reservoir as k by n then it's good okay and all the elements like the second part of the proof is like all the elements in the range from k to n minus 1 will also have the probability to come in the final reservoir as k by n then the like the method of generating the random function for this uh like reservoir would be good okay now the difference between this reservoir sampling algorithm and our actual problem is like here k can be what greater than or equal to one okay like in this reservoir sampling algorithm but in our actual problem k is exactly one okay so we can use o of one space to solve this problem like actual problem uh where we have been asked to do that the this late code problem okay so first i am going to prove this part 0 to k minus 1 the probability of any item of this stream of i which is in the range 0 to k minus 1 is going to have the probability as k by n in the final reservoir so let's try to prove it okay so what i am going to do is like probability of any item from this 0 to k minus 1 in the range will be exactly equal to that probability of all the items from k to n minus 1 should not be chosen so why i'm writing this let's understand this suppose we have a ks3 and this is 0 1 2 and there are some more elements right over here okay like 3 4 5 so this is the reservoir right and we want that all the elements like any elements in the range 0 to k minus 1 should occur in the final reservoir exactly over here okay so it means that all the elements right from the index equal to k if you use the zero based indexing from until n minus one should not be included in this reservoir any time like should not be included in this reservoir so how we are going to do this how we are going to find out the probability okay note that i'm talking about the final state of reservoir okay like all the elements from the k to n minus 1 should not be included in this reservoir so what is the probability for doing such okay so let's talk about the stream like element present at the stream of k index so its probability would be what so the length will be k uh total number of elements would be k plus 1 so we would be writing the denominator at k plus 1 like probability that this stream of k should not be chosen in this reservoir okay so probability for doing such would be k upon k plus 1 multiplied by probability that stream of k plus 1 value should not be chosen in the reservoir final reservoir would be there would be k plus 1 values and the total number of elements would be what k plus 2 i think i'm doing correct okay and it goes up to the last one n minus one upon n i think yeah i'm doing correct if we will find out the probability it will cut out all those elements like this l one would be cut and you're going to get k by n okay so probability of choosing any element in the range 0 to k minus 1 for the stream of i would be exactly matching with k by n so this is correct so we would be proving the another part again okay that is this part i have proved like every element should have the probability of k by n so i proved for all the elements which are lying in the range 0 to k minus 1 has the probability as k by n now the second part is like all the elements which are lying in the range k2 and minus 1 should also have the probability of k by n okay so let's try to prove that also so this part has been done so let's move on to the next part okay so we would be finding out the probability of any item in the range k to n minus 1 should have the probability of k by n to prove okay so let's take some reservoir of ks3 and it will be 0 1 2 okay so there will be some more is reversed let's say 3 and 4 okay and here it is denoted by ks3 and this will be final n okay so let me write down n minus 1 over here and n minus 2 over here let me change the color okay so first i will uh what i will do is like first i will find out the probability for the last item p last item means i am talking about n minus one and minus one element okay so e l e m e n t element n minus one element so if i will prove that probability of last item would be k by n and probability of second last item will also be k by n and it goes on up to probability of the element present at stream of k should all be like all the values should be exactly equal to k by n we have to prove that okay so first i will prove for the last element so what is the probability that last element should be included in the final reservoir okay so it should be like one of the key first k indexes so let me write down probability of one of the first k indices should be swapping this last value right so one of the first k indexes should be swapping the last item right then the you can see that this element is going to be included in the final reservoir so what is the probability of doing this you can see there are k spaces and we are total have an element so k by n okay so let's talk about probability of second last element okay so what is the probability of doing this like second last element should be included in the final reservoir okay like we need to find an the probability so we are going to do that so we are going to write down that the probability to choose the second last element would be like probability uh that one of the first k indices peaked in the iteration for this last element um wait a minute let me think out clearly how we can write this uh probability that one of the first k indices yeah probability that uh one of the like same thing i am going to do probability that one of the first k and let me just close this pop-up and let me just close this pop-up and let me just close this pop-up probability that uh one of the first k indices should be like one of the first indices should be swapping the second last item okay so we would be writing down k upon what is the total number of elements n minus 1 okay so we are considering only first n minus 1 stream ok and we need to multiply with one more factor you can see if i will choose any number that is swapping the second last element that number should not coincide with this last element uh that is that number should not coincide with the that number which is being chosen to swap for the last element okay so we would be just writing down the next one n minus 1 upon n why this extra factor comes because this in this element that is being chosen should not be same as the index picked for the stream of last character okay that's why i'm writing this you can see it will cut out this two factor and it will come out as k by n similarly you can do for this third last element would be like k upon n minus 2 and it should not be same for the second one it should be like n minus 2 upon n minus 1 should not be same for the last one n minus 1 upon n yeah you can see it will always come as k by n so the proof is done okay so let's talk about the code how we can code it out you can see this is for the k size reservoir so in our actual problem it should be as k equal to one okay uh yeah actually i've already submitted it uh yes you can see over here your time complexity is of n and space complexity open so i have stored the head of the list now i need to find out the random function like fill out the random function okay so like initially uh i will fill out the reservoir of size k here k is one so rand values will be like current value and i will move out to the next index okay and each time we will just update the random value until we got the stream of size of n values okay because n here is the linked list length okay number of nodes okay so each time i will increment the node count and we'll consider all the nodes from one to this like total number of nodes okay each time you can see stream is going to vary so first would be like a stream of size like if k is there is a reward here s3 then the next element will come so here total node count will be four then the next element will come node count will be five i will have to answer for the node count of n okay that's why each time i'm updating the random value now at the current position generate some random value in the range 0 to node count minus 1 okay as i've already said what does the reservoir sampling algorithm say is that each time you are going to generate some random value up to 0 to i minus 1 okay and if that value lies in the reservoir size like let's say this i should be less than or equal to k some random value position i is the end value position and if that value lies within the position of k we will swap the value okay so if that value is exactly zero because here after the word size is exactly one so if index corresponds to the value as zero we will update the random value as current value okay so i think i've told something wrong we are not going to swap the value this is totally wrong okay we are going to uh assign the value like a reservoir there is a wire of i where i is the rand value position must be exactly equal to array of j if you are talking about the jth character in the stream okay so take care for that okay and i'm going to move out to the next position and finally returning this random value so you can see the runtime is 36 ms i don't know why so if you have any doubts do mention in the comment section of the video and yes thank you for watching this video
Linked List Random Node
linked-list-random-node
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. Implement the `Solution` class: * `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`. * `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. **Example 1:** **Input** \[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 3, 2, 2, 3\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. **Constraints:** * The number of nodes in the linked list will be in the range `[1, 104]`. * `-104 <= Node.val <= 104` * At most `104` calls will be made to `getRandom`. **Follow up:** * What if the linked list is extremely large and its length is unknown to you? * Could you solve this efficiently without using extra space?
null
Linked List,Math,Reservoir Sampling,Randomized
Medium
398
48
hello everyone what's up today in this video we'll be solving this question called rotate image which is one of the most commonly asked questions by facebook as mentioned by elite code and if you like watching these videos then please do consider subscribing to this channel and sharing it with your friends would really help support the reach of the channel so we will discuss the question and then we move on to its explanation part as well as the code so the question says that we are given an n cross n 2d matrix which represents an image so we know images are represented using pixels xmi coordinates and we need to rotate this image by 90 degrees in the clockwise direction so they mentioned the rotation degrees required as well as the direction and also you need to rotate this in place which means we cannot use any extra space to store anything and uh yeah so they have given some examples for example the first row here becomes the last column for 90 degree clockwise rotation then four five six second row becomes the second column and third row becomes the third column similarly for this case and for a single cell matrix single element will simply do the same thing so these are some test cases let's quickly move on to its visualization how we'll do it without using extra space and then we write its code all right so let's start with the explanation part now so in this particular test case i have considered this matrix as the input matrix so it's three four two seven six k and nine one zero and when we rotate it by ninety degrees clockwise so our output is this a dash matrix which is nine seven three one six four zero eight uh two so you can clearly see that this row has become this particular column and similarly the second row is now the second column and the last row is the first column so this is how our matrix will look when it gets rotated by 90 degrees so in order to solve this the first thing you can do is of course something like a brute force approach so you can have an additional matrix let's call it b for example and b will also be three cross three of the same size and what we're doing here is uh simply we're hydrating over all the rows and we are storing them as columns towards the right hand side because we know that we want to rotate it by 90 degrees clockwise so essentially in this case we it was the first row 342 we store it as the column here 342 then we had to over the second row seven six eight so we stored it as the second column and then for the third row we store it as a third column nine one zero and so this b matrix is now a result and we can simply return this matrix as our rotated version of the original matrix so in this method what we're doing is we are iterating over all elements of the original matrix so this is going to be n square time because there are n square elements and space wise also this is going to take uh big o of n square space why because this matrix that we're creating requires n square elements to be stored so this is where the additional space comes in now in this question on lead code we have clearly been told that we cannot use any extra space we need to do this in place so let's discuss that optimize approach now so now for this optimized approach we will need to look at some patterns and identify some common patterns in the question for example uh in this case this is the first row which actually becomes our last column in the resulting matrix right and similarly the second row becomes the second column and so on so this method generally involves two steps first is to take the transpose of your original matrix and then to reverse either some rows or some columns accordingly like whichever rotation you want clockwise anticlockwise based on that so for example if i take a transpose so transpose if you don't know it's basically changing all the rows to the columns so for example in this case the first row 342 will become the first column so three four two comes here similarly second row becomes the second column seven six eight and the third row will be our third column nine zero so this matrix is called transpose matrix of our original a matrix and now if you check these two the matrix that we want and our current transpose matrix you can clearly see that every row is actually reversed in our resulting matrix for example if i reverse the first row i get a 9 7 3 then if i reverse the second row i get 1 6 4 and if i reverse the last row i get 0 8 2. and now this matrix is exactly the same as the result that we wanted so we can simply return this matrix and we realize that we can make changes inside the same matrix itself so this is done in place and for this of course what we're doing essentially is taking the transpose at the first step so this is my first step and then this is my second step where i simply reverse all the rows in this case so depending on the rotation required you have to reverse either rows or columns accordingly so if i talk about the complexities for this one so firstly we are just iterating over all elements and transposing them so the time complexity for that step will be big of n square and also for reversing all the rows you need to iterate over all the rows and reverse every element every column of that row so again that would also be n square so the total time will be big of n square and to talk about the space so in this case we are not actually using any extra containers we are doing this in place itself so the space will be constant which is what was required according to the lead code question and now let's also quickly discuss how to take the transpose uh so what we're doing in the transpose part is we are changing every element for example this is the row 0 1 2 and this is the column index 0 1 2 so let's consider any random element for example this element its current coordinates are 0 comma 1 now all we need to do is replace their x and y coordinates so for this one in the transpose matrix this will be 3 4 2 7 6 8 and 9 1 0. so in this matrix that element comes at this position which is the coordinate one comma zero and this is what we need to do for every element so we will iterate over all the rows and we will make these swaps but one thing that we need to make sure is after we've done for the first half that is the upper triangular matrix we should not make these flaps again because that will again bring the elements back to their original position so we only need to make straps for this upper triangular part of the matrix and this will convert it to its transpose and now let me quickly consider one more case for example if the question was to rotate the matrix 90 degree anti-clockwise that is towards 90 degree anti-clockwise that is towards 90 degree anti-clockwise that is towards the left-hand side the left-hand side the left-hand side so our approach would be somewhat similar but we just need to make sure of the reversals so the first step again will be the same we take the transpose of our original matrix which converts it to this matrix and now for this matrix all we need to do is the reversal of rows or columns so our second step will in this case be the reversal of columns instead of rows because if you look at the resulting matrix for the location towards the left so you can clearly make sense that the first column is actually the reverse version of the first column second column is also the reverse version of the second column and similarly for the third column so once we take the transpose and this one will simply reverse the columns instead of the rows in the same manner so it's time we'll again be of n square and space we're not using any extra containers so it's going to be constant and in this way you can also try to figure out some patterns for any other cases for example if the rotation required is let's say 180 degrees or if it's 270 degrees so in these cases also clockwise or anticlockwise you can consider constructing the actual resulting matrix and then figure out some patterns after the transpose path so either reversal of rows or columns and you'll get your result so yeah that's pretty much it about this explanation uh this is the required space and time so let's quickly move on to writing its code which is going to be pretty simple in this case all right so let's jump to the coding part now so we are giving this function called rotate which accepts vector of vector so if you're using java then this must be arrow list of error list which is called matrix and we need to rotate it by 90 degrees and return it we don't actually need to return anything because uh we need to do this in place so they'll probably call this same matrix later and try to check if it's rotated or not okay so uh before starting first things first let's finalize the number of rows and columns in this matrix for rows i can simply use matrix dot size which is going to give me the number of rows in this matrix and for columns i can use something like matrix of zero which is the first row so the size for the first row which is the number of elements in this column so once we have the rows and columns finalized we can quickly move ahead so as we discussed in the explanation part the first part of this algorithm is to take transpose of the matrix the transpose of the matrix so let's do that first so we will iterate over all the rows first for all the rows what we'll do is uh we'll iterate for all the columns as well but only to the upper triangular part so what i'm saying is we'll android as long as the column index is less than the row index which means for the first row we acted over all the three columns then for the second row only for two columns and then for the third row only for the first column so that is the upper angular part so this is done because uh you don't need to replace the element again because that is going to convert the matrix after being transposed back to its original form so once we are rotating over the upper triangular we can simply replace the elements so for replacement i can simply use the swap function for c plus stl so we are simply replacing an element at the current row and current column by the element for which the row is the column and the column is the row so just change the coordinates and that's it so this is basically replacing the elements also if you're using java so swap function this function is not available in java by default so you'll probably have to use the temporary third variable to make the changes and that's how you can swap after we have the transpose we can simply move on to the second part so the second part consists of either reversing some columns or some rows in this case because we've already discussed that we need to reverse the rows so i can simply call it reversing the rows and what we'll do all here is so for all the rows what we'll do is we need to reverse this entire vector for this row so c plus has this function for reverse which is simply uh using the stl you can simply call for a particular vector so i'm calling for the current row and it takes the beginning iterator as well as the indicator iterator is basically just a pointer pointing to a starting and ending element so these are the iterators which will be passed and this line essentially will reverse my current row and i'm doing this for all the rows so all the rows will be reversed again if you're using java then this reverse function might not be available so you can use a two pointer method to simply reverse the rows using starting an ending pointer and yeah that's actually pretty much it because in this function we are not required to return anything from this and we have done this entire thing in place using constant extra space and i hope the matrix is rotated now so we can try to run this code to check for the sample test cases so yeah it's working for the sample test cases let's try to summon this and yeah it's getting accepted with a pretty good runtime a 100 and the space utilize is also very efficient because we are not using any extra space this is constant in terms of space being done in place so yeah that was about it for this particular question so if you're liking such videos and if you appreciate this effort then please do subscribe it means a lot and please do share with your friends your network and contact so that would be really helpful for the channel and yeah thank you for watching i'll see you very soon in the next one
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
126
hey everybody this is larry this is me doing the day 14 of the august eco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm word ladder too uh also for my usual people i do an extra problem uh because nowadays i feel like every problem i've done before um even though i don't always remember it to be fair because my memory has been owed but so yeah just a little bit more practice so definitely subscribe and check that out uh today i actually did it beforehand because i was trying i don't i skipped doing a hard one um so i just want to make sure i have more time especially since the contest is in about an hour of just recording so definitely if you're doing that good luck as well and wish me luck okay so a transformation sequence of begin and word such that every adjacent is different by a single letter okay uh given i remember this one was i don't know this is the one but there was one where i really hate it um just because it is the definition of depending on the input case right uh someone like this one but maybe i'm wrong but yeah maybe i'm thinking of someone else but in any case the idea will my first incarnation is to do by first search um do you have to oh wait is it maybe i'm thinking of a different one because i was thinking about the one where you have to do just one but here you basically have to do all possible shortest transformations that's not so bad i mean i'm still going to do the shortest path but um there's just about there's just more bookkeeping right and bookkeeping for those unfamiliar with the term is just about tracking things in a good way so that you can you know use them later maybe i use it too generic or too generally but uh yeah is it just me or today i have like a really huge forehead or is that me normally i don't even know anymore maybe it's the angle okay anyway um okay yeah so then let's get started doing it um so the way to handle this is also keeping in mind that um this is similar to the way that i would think about is if you do struggle with this one definitely work on a more simple problem with the shortest path not just the shortest path with respect to getting the length of the shortest path but also constructing the shortest path so understanding that will be i mean i think maybe obvious just because that's you know looking at the answer but it'll help you definitely like you know if you think about progression that would be the progression right work on one where you just have to wait on any shortest path then now work on this one afterwards um i don't know that i have a uh a problem for that off my head anyway because everything is recorded live so definitely check in the comments or if you know one then just leave it in the comments as well and i appreciate you helping but that said um yeah so the idea there is just yeah uh okay breakfast search to get the shortest path and let's get started i think there's some like weird things but okay so um how do i want to do it uh so word list we just can let's just turn it into a set because so that it's like over one lookup instead or it's not all uh it's all one with respect to the input but the input could be o of l for some length l right so um don't apparent that's only five letters so it's pretty good yeah okay and then now we just do a breakfast search um this is standard uh shortest path stuff that i'm constructing so i'm not gonna explain it too much but you know definitely practice this is i mean this is a hard but definitely shortest path comes up especially nowadays every uh on interviews and medium problems uh so definitely check that out um so i have uh and then what i also want is the previous right um and this is just to keep track of um keep track of the best thing from the previous one um and that's pretty much it really yeah i think the only thing that you have to be careful about is that i think we can bounce this a little bit better as well i mean there are things you can do but i'm just going to keep you know a basic thing of a distance just because why not uh and then now we start at begin work i think is there some like weird thing where begin what has to be in there or it doesn't have to be or okay it doesn't seem like it has to be but does the last would have to be there the last one has to be in there okay fine um okay so then now we start by cueing begin word and do oops uh and i guess no it's fine we could you could define it any other way anyway but we don't have to so yeah so wildling this is standard but uh bfs breakfast search stuff and this is basically the couple of the ways you can do it i guess we can take advantage of the fact that length was equal to five otherwise maybe we could take advantage of 500 because then you can do 500 times five what is that uh i guess that's good too shouldn't matter i don't wait so the two ways you can do it is by looking at every word to see you know if this is close to this word the other way of doing it is just by looking at this word and then try every 20 you know every alphabet right so 26 to the fifth is going to be 11 million so let's do the wordless brute force instead right um and maybe we can no i was going to say we could speed it up a little bit but well maybe we can speed it up a little bit let's just say no i guess or we can and we will but let's just say that this will handle it for no is that true what am i doing yeah okay let's just say uh not done is equal to set of word list or something like this right um and then when we pause it we remove this from okay so current word is you go to q dot pop left uh and yeah and not done we remove uh current right and then now we can pause all the other ones by you know word in not done we go and the reason why we want to an extra one is just as the way that i was thinking for it is because multiple words can lead to the same words even before you relax it so yeah okay so basically and since this is breakfast search this you know there are a couple of things as well so that if uh if so basically if um all right let me also write maybe current d is equal to d of current right so basically if current d is greater than uh if current d plus one is less than d sub word or if word is not in d or this if this is the case then we set d of word is equal to current d plus one and then we do the previous of word we appended with this current word and then we append this word right and then we continue i guess and then the other case is if current d plus one is equal to d sub word then we don't do any relaxing but we do want to append this as the previous thing right so that's basically the idea here um all right let's just print it out real quick this is basically a progress check to see if i have any silly mistakes um sometimes i'm more confident sometimes i'm not so yeah um oh because the initial word is in here just in case i guess okay so does that look good so it goes to hit too hot to dog nope hot well it thinks all of this is one so oh yeah but that's because i'm being dumb because i forgot the transformation thing right i have to do um you know the okay so delta is equal to zero for um i don't know whatever a b and sip of word and current if word is not equal to curve oops if a is not equal to b we increment by delta if delta is greater than one right then we contain you right forgot about that part okay so yeah so this looks way better now and that's what i mean by progress check right because you want to write more code and then get confused where your bug is um sometimes and that just depends on your confidence really but yeah this looks okay so then now we go okay if d of n would and if n word is not in d then that means that we haven't reached it so then we could just return an empty array otherwise then we have to construct this right so let's just say answers you go to this and then return answer and we and this is kind of similar to dynamic programming path construction of path reconstruction side so yeah so then it is just we have a function we have a go we have a previous and a current list uh what i want to say okay so just the current word uh and then in a list i don't know i'm doing this way awkwardly but yeah and then we do a go on the n-word and then just like do a go on the n-word and then just like do a go on the n-word and then just like an empty array and that should be fine and then here we go if current is equal to the begin word then answer that append just like a copy of this um though we might have to reverse it i think we do have to reverse it so let's just do it this way um because i'm constructing it backwards otherwise we look at the previous so for uh let's just say p and previous of current we do list dot append of p we go p and then we go list i mean excuse my language didn't mean it that way but anyway i mean that should be good but that's good restaurant i don't do i don't know what to do in each order uh it seems like i forgot the last word i guess i just have to do this but i want to see if i had to return it in any order uh seems like maybe okay i mean i don't know if i just returned what right thing or just like some problems just require you to return in a specific order right so all right that looks okay let's give us a minute and let's see if we get a time limit exceeded like i did about three years ago now okay cool but today i seems like that's okay 866 day streak yay um yeah a little bit slower than last time what did i do last time okay so i pre-calculated a lot of stuff okay so i pre-calculated a lot of stuff okay so i pre-calculated a lot of stuff first uh but the same idea though and i hash the words instead and then i do 27 times i don't know i mean i can't tell which one is faster i guess sometimes it is whatever uh and then i just time them and exceed it by that time then exceed it i don't know i guess it's fine uh anyway i'll show you the beginning of the code again and the end so what is the complexity here right um knowing that when you have to output the i'll put the word list it is going to be adverse let's see what is the worst case i think the worst case is just that um i don't know if i can construct a case i guess you can right because you can construct a case where um maybe it's something like this maybe the worst case would be like aaa aa b aba abb a you know like all the things to b and then all the things to ccc dot and it makes cccdn and then so now each path will have exponential um so then you end up with like i don't know uh like the even like um i don't know just very exponential i guess that's the answer right so i think that's kind of the tricky part about this is that you gotta um like it's let's say we have five alphabets and five characters right you can imagine that well the only 32 instances of between you know aaa to bb bbb and another 32 to ccc say and then another 32 to here so you can definitely like construct it that way and each path will have you know five choices and then four choices and three choices is five factorial and then that's 120 so that would be 120 to the fifth even if you have just five things right um i don't even i don't know if my analysis is quite right but in any case it can be way expensive uh i don't know if that's true maybe it's not maybe i made that up and to scare y'all and my analysis is weak uh we could play around with it though let's see right let's say we want to go to aaa to cccc and then we do aaa i guess we don't need to put that one because it's the beginning and then to do i mean just this part maybe a little bit slow just because i'm you know maybe i could write a code to do this but yeah fine now i mean okay fine but the point um but i guess we can just do this one but i guess that still takes a long time to write out the binary numbers okay fine even this one it should uh yeah even this one you can see that you know as mostly just because i got lazy to be honest that it has one two three four five six answers right um and i kind of didn't really use i guess i used some of these but yeah and then you can imagine that if i added a new one that would be eight or i don't know my point is that it's very exponential and you just have to rely on the input start being dumb i think yeah because you can construct a case that pretty much uh very quickly um because yeah if i had win this out that'd be 120 right i mean we could play around with it i have some time left so maybe this would be a good yeezy anyway so yeah so um for i and range of 32 we want to print uh let's see let's say bin of i we replace zero with a and then we replace one with b and let's see that should work but i am putting in too much stuff but anyway oh well i mean it doesn't work if you put it before afterwards after the code but oops i guess i need at least one case to kick it off right so someone like this except for rep to write practice i suppose but and also i have to do and then i need to see padded things python c pad is a thing right i didn't z dot phil that's evil uh five yeah so then i could do this and then now we can make it into one string oops something like that maybe and close enough right so i could do something like this oh did i how did this happen okay i guess i have to do one more but it keeps on yielding some parts of it um except the auto something yeah okay so this is a very basic uh thing and then we can maybe see you know point the length of answer just to kind of satisfy our curiosity so this is so okay so i did do the math i have in front of you um so you can imagine that if we just do the same thing but to ccc to ddd and this is just for five letters uh five alphabet right and that only is 32 times 5 right so 32 times 5 is 150 so actually 32 or 500 over 32 is what like 12 or something i don't know my math is terrible i guess it's more like 15 16 is 48 right so you have 16 of these and each one of these takes 120 uh gives you 120 answer so it's 120 to the 16 which is going to be too slow so this is exponential as i said um so yeah that's pretty much the idea really i mean i'm sure maybe construct even more ridiculous uh you know commentary exponential uh explosion but i'm just giving you one way to do it right um so yeah so this is my exponential this 120 answer but each of these also contain uh what's it five times six so like there's also a lot of memory and stuff like this but yeah but that's my hand maybe a way of saying this is very exponential so just really just depends on the problem not messing with you um cool that's pretty much all i have for this one let me know what you think stay good stay healthy take good mental health i'll see y'all later and take care bye i'll just double checking to see when i miss some other constraints that might have made it easier but bye
Word Ladder II
word-ladder-ii
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _all the **shortest transformation sequences** from_ `beginWord` _to_ `endWord`_, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words_ `[beginWord, s1, s2, ..., sk]`. **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** \[\[ "hit ", "hot ", "dot ", "dog ", "cog "\],\[ "hit ", "hot ", "lot ", "log ", "cog "\]\] **Explanation:** There are 2 shortest transformation sequences: "hit " -> "hot " -> "dot " -> "dog " -> "cog " "hit " -> "hot " -> "lot " -> "log " -> "cog " **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** \[\] **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 5` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 500` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**. * The **sum** of all shortest transformation sequences does not exceed `105`.
null
Hash Table,String,Backtracking,Breadth-First Search
Hard
127,2276
347
welcome back to algojs today's question is leak code 347 top k frequent element so you're given an integer array nums and an integer k return the k most frequent elements you may return the answer in any order so in example one we have an oms array and we have k which is set to two so we need to return the k most frequent elements within the nums array and as you can see the output is one two and that's clearly because one has a frequency of three and two has a frequency of two now if k was equal to 3 then 3 would be added into the output because that would be k most frequent element now if we look at the follow-up at the follow-up at the follow-up time complexity must be best than o n log n where n is the array's size so let's work out a solution for this so the naive approach would be to create a frequency map and by frequency map i just mean an object which is going to contain each number and its frequency so the amount of times it's occurred so 1 is going to be to 3 2 will be to 2 3 will be to 1 and 6 will also be to 1. then we could essentially loop through this object k times and push into result the largest value so the first loop we push in this value right here we push in the key into results we delete this from the object then we'd look and find the second largest value which would be this one so we push in the key for that and once k is equal to zero we can exit that and just return the result array either that or we could simply sort it and then return the two highest values and this will have a time complexity of k log n so how can we do this more efficiently so if we want to have o and time complexity and space complexity we can utilize what's called bucket sort now this is just a simple sorting algorithm where we bucket the frequency as the kind of key of the bucket and then within each key we can add into the bucket or an array we can push in these values right here so the numbers that occur x amount of times so let me show you what i mean by that so we have the count index as the keys how many of these values occur zero times well that's going to be empty how many occur one time so you've got three and six so we can add that to the bucket of key one so three and six two occurs two times and one occurs three times then it's just a simple case of looping through this bucket backwards and add into results the nums k times so we add one into results k is decremented to one and then we add two into results k is decremented then we can just return this value there is however slight edge kcsa for example we had five ones so rather than one being here we'd have four and five one would be in here in order to get the top two most frequent elements we'd have to loop through this backwards but we'd also have to check whether there is a value within the bucket at particular indexes we can add one into results straight away from five but then when we get to four this is going to be empty so we need to make that additional check to see whether there is actually something within the packet array and that's basically it running at on time complexity and space complexity so let's initialize the map which is going to be an object the bucket and result which are both going to be arrays we'll create the frequency map so we're going to loot through nums if map doesn't have num i then map number i can be equal to one else we're just going to increment that position in map so map number i plus now in order to populate the bucket we're going to have to loop through the map so let num and frequency of object dot entries pass in map so if the bucket at frequency cannot be found then we can set the bucket of frequency and what i'm going to do is store it as a set where we add the number to that set so we need to initialize the set before adding a number to it else bucket frequency is going to be equal to bucket frequency and then we're just going to add that number to it then we need to loop through the bucket backwards so i is equal to the last value in the bucket so if it's all length minus one i is greater than or equal to zero i minus if we find a bucket at position i we push into results a copy of bucket i the reason we create a copy is because we do not want to update the bucket array if result.length is equal to k if result.length is equal to k if result.length is equal to k then we can break right so we found two of the most frequent elements we've pushed into results we can break from this now and just return result let's run it
Top K Frequent Elements
top-k-frequent-elements
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `k` is in the range `[1, the number of unique elements in the array]`. * It is **guaranteed** that the answer is **unique**. **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
null
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
192,215,451,659,692,1014,1919
5
hello everyone my name is raveena welcome to City coder today we are going to solve problem number five that is longest palindromic substring so let's start reading the problem statement it says that given a string s return the longest palindromic substring in s so first of all what is subscript what is a palindrome so palindrome is something so basically let's take an example so palindrome is basically a string when you read it backwards right to left or right left to right it is the same so for example in here you'll see that let me take another example so suppose a b a this is a parent room because if you reverse it if you write a first and then B and then a it is the same so that's what a palindrome is now palindrome can be a single let single letter like this because you know it's equal to itself it can also be this it can also be BB where you know these two are the same so if you write B first and then this one as second character it is still the same as this particular thing particular string so this is what a palindrome is now the question here is asking us that given a string we have to find out a substring that is actually the longest palindrome so in this example that we have we will see that one palindrome is this bab the other palant room we have is actually a b a and I don't see any other palindromes other than that because if we try to do some combinations it will we have this deep it doesn't fit so the longest parallel room that we have is either bab or ABA either of those answers are acceptable so let's see how we can solve this the first Brute Force approach would be to you know start at a particular index so basically suppose I start at B and then I explore all the strings so for example I started P I'll check is ba or palindrome uh if b a b is palindrome if b a is a palindrome or b a d is a parent room then I'll do a second pass of things at that point I'll start from a and I'll check if all these strings are valid room I'll do this for all the characters so for example I'll start with p and then I'll check you know if these two open room I'll start with a I'll check if this is a palindrome so that is a brute force of Brute Force approach and let's talk about the time complexity of that Brute Force approach so what you are doing is you are starting at a particular position and then you're expanding the whole string so that's actually two for loops and that is actually n square right you start from here and then you explore all the other area all the other uh characters now to check if that particular string is actually a palindrome or not it takes oaf in the complexity so this becomes n square into n and that ultimately becomes n Cube I have a better approach that we can take when we are looking for a longest parent room and that is really simple what we have to do is instead of starting from the far left let's see if we can check how we can you know if we start somewhere else will that improve the time complexity so for example if we say suppose start from the middle and then expand around it around the center so what do I mean so suppose for example if I start from here and I check is there anything on the left or anything on the right if it is then I'll keep on expanding so simple example I would say is this if I start from a I'll check are there elements on my right and left of my a yes there are they equal yes okay then I will keep expanding I'll keep going to the right and left I'll keep expanding to the right n to the left and that is the approach that we are going to see today so let's see how we can work with this example that we have so uh there's actually a small use case that you'll see so let's look at the second example that we have the first example we just talked about the second example is really clever they are also taking in the even uh Center so even strings for even strings what should be our Center and that's actually the tricky part it's really important to understand that we also have to think about even substrings even palindromes and not only think about the odd palindromes so for that how will you do it so suppose if we have BB you will have your left and right here and then you'll start expanding things so let's see how we can you know just Implement that so the first thing that I need is my eye pointer that is right here and then what I need to do is I need to keep track of what is my max length at the time all right so initially my max length is actually zero and since I am working through each and every element I received one element and remember Single Character by itself is also a Subs also a palindrome so my max length is gonna get updated my max length is now 1. and I'm gonna check if I can expand to the right and left since if I expand to the left it is out of bounds we'll just stop there similarly for the even length I'll have to pass in I and I plus 1 so that is actually this bed this particular character so I'll pass in b and a the we are going to check if B and a are equal no they are not so there is no point of expanding it further so we are going to stop there and then we just progress our eye pointer so we progress our I pointer i r our eye pointer is now pointing right here we check that okay can I go to the left and right I can go to left and right it's not out of bounds we will check that are those two equal yes those are okay so I just found out my new max length is actually 3 and then my new result that is the maximum result is actually b a b once I do that I'm gonna also check it for even length right so I come in I'll be like okay let me pass in A and B and check if they are the palindrome so I check if a and b are equal no they are not so there is no point in expanding outward so we will stop there and then what we have to do is we have to increment the eye pointer so our eye pointer now is here I'll check if I can expand it I'll go to the left and right I'll check oh yeah a is equal to a so my max length will be it's already 3 so it doesn't really matter it can stay the same and then I'll just update my result would be the new max length that I have is a b a now let's see if we can do this for the even length right so I'll pass in the even length I'll pass in ba I'll check if p is equal to a it's not okay so we don't have to expand further we can stop there and then we will have to incrementer eye pointer so our eye pointer is going to be here I'm gonna expand further I'll check if I have anything on the right and left yes I do it's not out of bounds out of points is basically if you don't have anything on the right or left that's when you get the out of forms error so here B is not equal to D so I don't expand further I just then pass in I check it for the even length I'll pass in a and then D I'll check if a is equal to D it is not okay I won't expand any further so the result that I have is a b a and the max length of that is actually 3. both the results b a b and a b a are acceptable so uh anything is fine lead code is accepting every answer so let's see how we can code this the most important part so the first thing that we need is a I'm going to use a common function that I'm gonna call twice one for even and one for odd since all the programming inside it is the same I don't want to duplicate code so I'll just create a function for it and I'm gonna call it expand around the center expand around Center I'll pass in the string that we are working with the left pointer and then the right pointer now what I'm going to do is I need a substring to keep track of you know what I'm not what is my longest substring till now so I'll need a substring and then I also need a max length like what we kept track of so this is the max and just to check you know if my max length is greater than the existing string that I have to update it now I need a while loop what I'm going to do is first check the bounce so the bounce would be if left is greater than or equal to 0 and my right is actually less than length of the string so these actually are the out of bounds check if that is true and my S of left is equal to my S of right so that means there are things on the right and left and those are equal that what's that's what it means if that is true then I am going to check if my right minus left minus plus 1 so what is this is just basically the length so how did we see a b a that is how you actually calculated the right index minus left index plus 1 we will check if that is greater than max length if it is then we have to update it we have to update the max length so we have to update max length Okay I just keep misspelling it so okay I have to update my max length and my max length is going to be right minus left plus one also I have to update the substring right because that's my result at least for this particular combination so my substring is going to be S off so this is how you write it in Python uh the string it's basically the string and then the index starts from left and it goes still right plus one so I in reality it is only till right this particular right plus one is excluded and that's why I have a plus one here so I create I updated my max length I also updated my substring now what do we need to expand so how will we expand we will decrement my left so I can go left on the string and then I'll increment my right pointer so that my pointer can go right in the string so that the string expands so I can then now pass the longer string and then I just return my substring because that's what I have been calculating now I have my common method in here so it becomes really easy for me I am going to add a result this is the result that I'm going to return and then I'm gonna go through each and every element in my string so that's what we did we had an eye pointer so I in range and then it goes to length of s and I have to check for odd string so I let me just do it like this so odd string is going to be my method so my method is expand around corner so I'll expand around my corner I'll pass in the string that is s and then since it is odd we have to keep my Center as one right we have to keep a center so I'm gonna pass the same element twice and for the even length I am going to call the same function and this time I'm going to pass I and then I am going to pass I plus 1 because we don't have a center for even in the N what I'm going to do is if so I have both my odd length I have my order string and my even string I have to check which one is longer whichever one is the longest I'll just update my result with it so I'll check if length of odd is actually greater than my length of result then I'll update my result to order my length of event is greater than my length of result if that is true then I'll update my result with my even substring so result is even in the end I just have to return my result so let's see if we can run it okay submit code yeah this was submitted um so uh the as you can see the time complexity of this algorithm is actually n Square n for the for Loop and then again n for expanding around the center so that becomes n Square whereas our space complexity is if you look at it we are using a result we are using a substring and then a max length all three of them are storing constants so the space complexity of this particular algorithm becomes constant which is O of 1. if you don't know how to calculate space or time complexity I have a video on that you can refer it I'll drop the link below in the description so the code will be on my GitHub repository and I will add a link to that in the description below if you like my videos please give it a thumbs up comment on it if you want me to solve any other problems please let me know in the comments below you can also now connect with me on Discord I can help you out there if you are preparing for interviews or if you want to take want me to take any mock interviews let me know in the comments below and also you can just connect with me on Discord so thank you so much for watching and I will see you next time bye
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
3
Hello Everyone Welcome Back To Channels Iodine Extremely Well Suitable Also Solving Problems Long Spring Without Reading Practice All Problems Tube Baby Aspirin Gas Any To Find The Length Of The Longest Born Without Revealing Characters For Example Of Giving A String In The Longest Running Without Putting Characters History Laddu Stream ABC Theater Sufferings Will Not Find Any Substance Which Is Land Entry Language Of No Regrets For Best Friend Answer Will Be Difficult Basis Of Which Is Not Repeating Character Celebs Question Is After You In Interview Different Approach Airtel Interview Chhila Hai No Approach Shree Otherwise Prostate Either Generate All This App Brings You Know How To Generate Oldie Sector 29 Withdrawal Warning Hard Mark Generated All The Service On Gautam Video Achhe Mila Yudh Tuesday Hua Tha Unit Jail Me Put Sabse Du To Safar In The City Next Band Selection And Songs E Next And Goals In The Last One Will Win This After 10 Shahabuddin A Stringer 10 Days This And Goals And Elastin This Will Start From This Which Theorem Index Research Center Decided To Supply Chain Delivery Time Complexity Of This Approach S Being Of Incubated Dixit No Approach In Pumik Sham Optimization Da No Approach To Generate Voice Of Dreams And Naveen Co Of And Square Of This Place Complexity Of Bagga Of An Which Will Be Required To Check For Rippleing Character Singh Ka Use Yes Set For That Solid Interview Notifications Co Solution Elastic Optimized Sanyog Man of the Match Approach Every Member Immunity Jumps Into Tears When Solution Because Vote Interview Want to See or Thought Process Metal to Go by The Cockroach Enters Torch Co Goodbye and After Food Key Based Approach All Optimized Approaches Will Take Left Point Arghya Ride Point Amrit Phal Bhi Point Incon 2001 Will Declare MP Set With Character Se 0120 Which Is The Longest River In The Initials R0 C R0 Video not Mid-Range Lord Has No Regrets I Can Do Subscribe Button Minus Plus 120 - Hero Subscribe Button Minus Plus 120 - Hero Subscribe Button Minus Plus 120 - Hero Plus 151 Character Update Updated On Samudra Ride Point Gift Index Nifty Index of Character Beat Video subscribe The Channel Please subscribe and subscribe the Third Character Very Important Points Siddhant Initiate This Character Subha Can Share With Strange Alarm Disturbance Some Repeating Characters For That person fitting it's so let's see what he does will be removed from the site of the left whatsapp wechat na a position to know how to remove a new range played between one to three no regrets and minus one plus one more 12322 of day and subscribe Alarm Set Respected Gangaur 808 Dasha and Caret Kare 24 Hindi Set Rishtey Yeh Character Todenge Is Vivecha Historian Dear Strange Facts From Repeating Characters Thoda Add First Voter's Day Let's Remove It's Been Removed From The Site After Being Well Time When An Eggs In Dishes Note Centers What Means of Birds as a Prayer is Depleted Saver of Remove 10 Pins Select Remove This is Pain After Removing Villagers 2185 One Step Ahead Below Again from 10 M Still Exists in This Is What Means This is the Reason the Train Came Still Has No Regrets Selective Verses Through This Prayer Novel Price Loot India Set I Don't Mind S A PM Who Supported Beam 10 Days You Range Alert Have No Regrets Actor Inside Most Poison Find The Length Of The New Alarm Next One All Don't Updated In Ubuntu Sbco Movie's This Book Remainder * Respect Movie's This Book Remainder * Respect Movie's This Book Remainder * Respect And The Saver Mode This Eight Days Accept By Choosing Ali Baba Review Set Dwivedi Dandruff Soft To New Range Of Alleged Rapist Related To Which Is Not Matter Of This One Should Not Vanish Into Tears Pain Deposit In This Site And Lag Increase And Etc. Next Introduction To CD Deluxe Modified Morning Tools Pay The Rent In Next Substring Is The Best Idea Length Was That Place Not Matter Switch Can Do What They Can Sacrifice At See In Set N Department And One Step Ahead 181 Test Held For PCS Increase Naveen Dhawan Set Hui Haddi Dhundhoon Yaar Range Right From Big B C D Is Alarm Surti Minus Plus One Which It's Something Like This And Pushed Into To BBC Hindi New Movie Aaj Hum Remove This And Simply Slide Celebs At A Selected In Boil When Night Clubs In issues experience na they do subscribe window in the trees which you are sitting on a tree not to avoid topic agree with you should we do something is the length of the best friend ko mein mohad adil next step in my Diary Notes Bundri and Distic Strip Switzerland Aap Straight Length Force Vacancy Dot Villains Frill Do Teen Gates Of Things Which No Repeating Characters Talk Time In Big Guide BCCI Chief Vigilance Investigation Un Nabi Sonth Loot Murder And Moving Employment It's Not Repeating This Movement Musavvar Are You Can Remove Subscribe Creative Vipin 188 The First Art To Grief And Space In This Style Again Took A Big Boss Big B This Channel Subscribe My Channel And Interviews Interview With Truth Interview Subscription Will Be Co Off An Object Solution Introduces You To Do Something Very Difficult To Launch Computer Programming In Black That Idly Learning From Different Educator Lagi Is Education All World's Best Programs Kumar Binttu ICC Board - Programs Kumar Binttu ICC Board - Programs Kumar Binttu ICC Board - All Should Have Won Medals At Noida Samudram And Also Working Hard To Produce Companies Choker Indian Academy Adams Co Select Class 9 Math Platform Se Fry Amount He Along With His Laptop Se Subscription Plane No Inspection Irrigating Interactive Sessions Know This Beans Dil Behaving Like His Wife And Interact With Education Sass Directly Hindi Live Class Alarm Patience Have Instructed To That Dual Behaving Course for Beginners Intermediate Advanced People Tubelight Classes From Dear You Can Join Any Of The Course And Fuel Class Great You Feel To Join And Voice Recording Of The Class So That You Can Avoid Any One Of Any Give Life Class Along With His Father Give's Singh Ss Trains Will Be Clear In Hollywood Celebrity Assets Subscription Come Shopping 12312 Android Apps And Want To Add Additional Desk Top Ten Percent It Depends On Technique Forward Hooda And Dil Equal Hindi Brush Dough Batter Solution Bittu Kal Feder Vinegar White Pointer In This Aspect and also Bittu's Wavelength Children's Weight Follow Difficult Only Problem with Fee Stars RS Dahiya This Chapter Moving Sliding Window r13 Anar Vantey Behave Screen and After 10 r13 Bihar District Now But After 10th October 2017 Problem Solving The Problems That Were Are You End Will have to much going on and we also reduce travel time but I don't feel any point by doing a plus every time I can withdraw time yes we can notification of stringers pay electricity bill no repeat like subscribe now to receive new updates of the last Liar jhal dat le saal se problem is internet addict solve problems loot vidron it's own map and frequency to take you can see it will be a great thing which exists in this is the current events which will be updated 212 institute of putting it was last updated Oh That's A Good Deal Untouched Orphan 10 Questions Also Work 148 323 Length Three Layers In New England The Call To The Last Point To Point Properly Video Me Already As In The Last 10 Top 10 Company Problem Something Strange Alarm 2018 Fix Single News Apni Chal Aav Na Ripping Character Andar Stuffing Us Of The Three Do Length Novel Important Lagan Uday Lal Yadav New String 16 To This Updater Se Vayu Updates Index Of To Index Readers' Choice Index Of To Index Readers' Choice Index Of To Index Readers' Choice Award Winning Moments Of A Change In The 1980s Last Updated On Quest Of Thing Or Spread Swine Flu Repeating Practice Again For Watching This Aryan Update Scheme Well Built In The 4th Next Let's Move You Pimple Acid And This Point To The Character BBC Dot Hindi Math Chapter 20 Present But Means The Meaning Of Life Is In Rains Are No Meanings For The Not Withdraw from Last Year Lasts or Not to Worry About This Thank You All X A little bit you can take whose frank and whose hand length after retirement you towards solid waste days last 380 216 tax rules and regulations free 2019 half singh20 A little bit you rent from 427 lances who can update your words for starting index a word against Due to which district send a defect in next 100 years, peep into engineering, this plus coming example, sex very important instead of eliminate 10 b eliminated 2101 Datsun go to intex dayan se right intact 285 na repeating tractor and update 10 b Bluetooth index of BSP mid-1990s From Six To 9 BSP mid-1990s From Six To 9 BSP mid-1990s From Six To 9 February 2015 16 To 9 4 9 Samudra 600 Units And Traversal Complete Remedy And Find The Length Vivo v5 Bigg Boss Big B Channel Subscribe To Character And Juice And Election 2014 130 computer length of this cream and any civilized imperial length 30 number one of the tower ride point to edison process the traversal boundary time pressure and surrounding content director David content only festival in C plus one laptop loop like half 84 in this budget IS Computed Blenders Pride Minus Plus Actual Reason Traveling And Updated To Length Agree With Any Previous Length In 35.51 Whats 35.51 Whats 35.51 Whats Completed In Time Travel Expense Simply Return Length Time Pro Kabaddi C Plus Solution 24 Hour Cigarette Frequency Map IS Basically A Factor Of 256 Noida 256 Dec Ringtone Weeks Shift This Economic Issues Map Of Characters Kill And Split Your Choice Should Were Initially Electors 0n More Size Of String Of That I Exist Length Initial 2013 Longest Serving Other Witness Tweet Building Last Intake Sorry Shri Chakra FD Character FD Right In The Eggs In The midst of a great idea is class 1o but I don't updated unless a grade one left one whatsapp status lines laptop not noted nurses teaching maths for the way cigarette light accessibility mode on opted for it's not any range alarm or already discussed and after roadways Now Half Quality Index Last in 8th House Map Correct S Bride Was Last Seen or Occupation Updated for the Time Avengers Left and Right Side Find the Length of the Current Affairs Right Minus Plus One of Its Great Country Previous NP Computed IS Simply Updated On the lens of bus whatsapp diet we are hot and right next thing intact unwanted complete raw challenge complete package simply returned all lands which will enter follow angry friend a ajay ko
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
121
hey everyone welcome back and let's write some more neat code today and don't forget to hit the like button it supports the channel a lot so today let's look at leak code 121 best time to buy and sell a stock so if you know a little about the stock market the saying is usually buy low and sell high so in this case we're given an input array now each value represents the price of the of a stock at a particular day and we are given one transaction meaning we can buy on one of these days and then sell on another day and we want a transaction that maximizes our profit and then we want to return that profit in this case if we buy on day two when the price is one and sell day five when the price is six that's what's going to maximize the profit for us so as always i'm going to draw a picture and show you that this problem is actually not too bad even the optimal solution so on day one it was at price seven and then it went down all the way to price one the next day it went from price one all the way up to price five and we could just keep going with this right so next day went down and the next day it went up and the last day it went down again so looking at the picture it's pretty clear that the max profit we can get is simply by taking the minimum here and the max here and if we look at the actual values for that we see that this is one this is six so the profit is gonna be six minus one which is five but notice how we there's actually a greater maximum than this one right like this is six but this is seven so why can't we just do this because then we get seven minus one which is six which is even bigger than five well it turns out we know that time moves in one direction right we can't go back in time to sell at this price so how are we going to solve that problem well there's a pretty common programming technique two pointers so we're gonna initialize a left pointer on day one and our right pointer on day two which makes sense right is gonna be to the right of left and so we're going to see what's the current profit right now from here to here well it's going down right that's not good it's negative and in this case left is going to be the day that we buy and write is gonna be the day that we sell so the first thing you're gonna notice is it's down right it's negative this is not good we don't want a negative profit why would we buy left when we can buy right is less than left why would i pay seven when i could wait one day and pay one so that's basically how the algorithm works since our right value is less than left we're gonna update our pointer left so left is now gonna be on day two and right is gonna be on day three so now we see that the right value is actually greater than the left value but what's the profit in this case is going to be 5 minus 1 which we know equals 4 which is so far our current max profit so for the current max i'm going to put a 4. and in this case since our left pointer is less than our right pointer since we're buying low and selling high that means we can leave our left pointer over here and we only have to update our right pointer now let's compare our left and right so we're buying here we're selling here in that case the profit is going to be 3 minus 1 which is only 2. so if you take a look at our current max it's 4 so we're not going to update our max profit and we notice that our left pointer we're buying low and we're still selling high it's not as high as this but we still don't need to update the left pointer and so now we get to the actual uh result case that we already know about but let's compute it so this is at six this is at one so we found a new max profit six minus one is five so let's update our max so our algorithm is gonna keep going even though we can tell by the picture that we did find the mac so it's gonna end up checking this last case which left we're buying one and we're selling at i think this is four so we know four minus one is three not greater than five so our algorithm is complete we found our max profit of five and if we wanna know the memory and extra space we used we know we didn't really use extra memory we used a couple pointers but no array so extra memory is 01 time is going to be linear because this is a two pointer solution we're not doing any brute force stuff this is going to be big o of and we only have to scan through the array uh one time even though we have two pointers okay now let's code it up so we do have a left and right pointer left is going to be initialized to 0 and right is going to be initialized to 1 just like in our picture we know left is buying right is selling we can initialize our max profit to zero as like the default case and we're gonna keep iterating through prices while our right pointer has not uh passed the end of prices now we wanna check is this a profitable transaction and how do we check that well if prices of left is less than prices of right now if this is profitable let's calculate that profit which is going to be so this is just the math right price is a right minus left and now we can potentially update our max profit but we don't know for sure so we're going to check the maximum of the current max profit as well as the profit that we just computed so whatever the max is going to be assigned to the new max profit but it might not be a profitable transaction which in that case we can update our left pointer now regardless of the conditions we want to update our right pointer and so this is obviously going to keep going until our right pointer is out of bounds in which case we've gone through all of the values and we know that max p has the result that we want to return so i actually had a small bug over here instead of incrementing left by one if the left price is not less than the right price we don't just want to shift our left pointer by one we want to shift it all the way to the right because we found a really low price we found the lowest price that we could pretty much we basically want our left pointer to be at the minimum and you can tell from this picture that if our left was here and our right was over here we don't just want to shift our left pointer by one because then it's up here we want the left pointer to be low right we want to buy low sell high so we would shift our left pointer all the way over here so we'd cross this out put the left here and then the right pointer would be over here and we can see that this would be a super good profit for us and now we can submit our solution and it's over 90 so we're in the clear we found a very optimal solution for this problem i hope it was helpful please like and subscribe to support the channel and i'll hopefully see you pretty soon
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock. Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 5 **Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. **Example 2:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transactions are done and the max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming
Easy
53,122,123,188,309,2138,2144
84
what up this is Jackson Gabbard back for episode 5 of the unqualified engineer I'm going to be real with you people getting a little bit bored with the polite PC delicate episodes that I've been up to recently I'd like to just keep it a little bit more real with you all and so this episode you're gonna get the raw uncut Jackson and that has nothing to do with my parents decisions related to my Anatomy when I was a baby I mean I just want this to be more authentic me coming out and so brace yourselves because I might use some wordy dares got some new markers for my glass very nice best part is when you spray them it looks like blood so for this episode we're going to be exploring an oldie but a goodie the largest rectangle within a histogram problem and while this problem is not super algorithmically complex the optimal solution to it is more surprising than you might expect and drawing straight lines is hard let me try again oh no it so what do we mean when we say a histogram this is something that everybody even knows about I guess a histogram basically is an X and a y-axis histogram basically is an X and a y-axis histogram basically is an X and a y-axis where for every X you have some Y value and for this problem we're going to assume that all of those Y values are positive integers and the goal here is to try to figure out if you have a histogram what the biggest rectangle you could draw with in it would be so you know from the far left side to the far right side where in that histogram is there the biggest rectangle and now if you look at my example here it's pretty obvious straight away that the big tall six by two rectangle is the biggest rectangle that gives you an area of 12 so that's the obvious case but there are lots of other cases that are not obvious at all for instance what if we modify the histogram to look like this so you can see now we've got some real contenders for the largest rectangle case we've got a three by two we've got a three by three but then you'll notice way down here at the bottom we actually have a two by seven which is in fact the largest rectangle in this histogram let's get to the exciting part let's talk about the algorithm for this to brute-force this algorithm you would to brute-force this algorithm you would to brute-force this algorithm you would basically start at every X position and go up through the y-axis of that X and go up through the y-axis of that X and go up through the y-axis of that X and go to the right until you hit something that doesn't fit and then keep that maximum area you've seen across each position in the x axis and that would kind of get you there that would definitely eventually get you to a correct answer but you would do so much work so much unnecessary work because you would in fact spend a ton of your time just recounting the positions in the histogram that you've already seen before so a much better option is one that doesn't require you to do any backtracking or to recount any of the squares in the histogram again and the best solution to this that I know uses a stack and the algorithm for it is pretty cool actually the idea basically is that any time you reach a new height in the histogram going from the left to the right you could be starting a new rectangle you can't no in fact you won't know until you hit a lower height until that until you've reached the terminal point and whatever that rectangle might be and so the algorithm for this works pretty much that way you start from the left side you check to see if here at the first or at the biggest height you've seen so far and if you are at that position then you push it into a stack now we actually need two stacks we need one to store the height and one to store the position and we'll make sure they stay in sync so if we look at this example as soon as we hit the first one we know that we might have a rectangle of height one but we don't know how wide it might be so we'll just push that into our stack we'll keep track of that and then we'll move on to the three now if we're in the three we still have the one going because three is bigger than one but we also might have a new rectangle starting of height three and in fact we know we have at least a one by three because that's the definition of the histogram so we'll push three into our stack as well and we'll keep going now when you get to the two is smaller than three so we know that our height three rectangle is done it can't be any wider than it is because there's literally no more histogram with three in it so at this point we need to get rid of our three but we need to keep track of it because it might be the biggest one at least we don't know that it's not yet but we should be really clear about how we're deciding the size of the rectangle that we've seen now visually it's obvious that it's a high three and with one rectangle but we have to think in the general case here the general case is basically saying we know because of the contents of the stack the we have at one point seen the height three and it was at some position now in this case the position is at position one but we're now at position two and so the only way to know the height and the width of this rectangle is to say what was the height that we saw and then where are we now - where did that where are we now - where did that where are we now - where did that rectangle start so if we're at - right rectangle start so if we're at - right rectangle start so if we're at - right now if we subtract the one from it that gives us one and three times one is three which is the correct size or this rectangle and so knowing that we have seen a size three rectangle we can keep going that's as much information as we need because that gives us enough information to either return this three if it is in fact the biggest rectangle or to discard it if we find a bigger one later now let's talk about how we would proceed forward we want to keep leveraging this stack to make sense of the problem so now we've got two and the immediate question we have to ask is what's on top of our stack we don't have a bigger value than two on the stack and so we need to push two onto the stack so there's actually a kind of a subtle thing here which is that the two doesn't start with itself the two actually started inside the three and so while we'll store the height two in the stack for the heights we don't want to store position two we want to keep position one because that's actually where our rectangle started and so we'll proceed forward from there with the same process and in this case the very next thing we hit is a height one at position three we're going to take everything off of the stack that's taller than height one and we're going to figure out what size rectangle those taller Heights were composing and then figure out if those rectangles are bigger than the biggest rectangle we've seen and that's how we're going to find the biggest overall rectangle so we take our two and then we take the position that it started which was position one and we say okay so two is our height where are we now we're at position three this started at position 1 so 2 times 3 minus 1 gives us 4 and so now all we need to do is choose the maximum value between what we've seen before and what we have now and if we keep doing that we will always keep the biggest value there no matter if it was earlier in the histogram or later in the histogram and now we've done our first real replacement of the biggest tangle at first we thought it was the height three with one rectangle but now we've got a two by two that's bigger it's a bigger area and that's awesome so and so we return to our stack with our current position and the value we have at our current position is 1 well it turns out one is already in the stack and so we don't need to replace it we can just keep on rolling so when we reach the next point in the histogram we find that we've got 2 now 2 is bigger than our one and so we're going to push another position onto our stack we'll put the 2 into the height stack and the 4 into the position stack and so now we're out of histogram we've reached the end the only thing we have left to do is to digest what's in our stack as we reach the end of the histogram we need to tally up the size of the rectangles that we've been keeping track of that we haven't reached the end up yet and in this case we have two rectangles that have been open but not shut so to speak now this height to start a deposition for we're now sort of at position 5 which is to say we're at the width of the histogram and so if this started a position 4 we're going to subtract 4 from 5 we get 1 2 times 1 is 2 so this is just a 2 by 1 rectangle not interesting well ditch that but then what about this one what about this height 1 rectangle well it started way back at position 0 way back in the day and we've been carrying it along since we first started this problem so let's do the math on this the position is 0 and if we're considering the full width of the histogram is 5 minus 0 is 5 so 1 times 5 means that we actually have found our biggest rectangle and this biggest rectangle is a 1 by 5 area 5 rectangle which is clearly bigger than the 2 by 2 that we found before and if you're seeing this thinking what is even talking about like what height 1 rectangle are you talking about let me color it in now you see that fancy wonderful height 1 rectangle that's been lurking there the whole time just waiting for you to notice it all that wanted was your love and you kept it at the bottom of the stack you animal so today we're going to code in Java just kidding we're coding in JavaScript I like most people who code in Java don't know Java now since we're writing in JavaScript we need to carefully consider all both of the available data structures we got the object and we've got the array it would be awesome to have a real stack data structure that we can use for this because it's much more memory efficient and the API that it offers is the correct API for stack operations but this is JavaScript so we'll put away our dreams of memory efficiency with our hope to have a coherent substring API and then we don't have a histogram class either we can just leverage of Anila javascript array because javascript only has two data structures they're both super versatile they have almost as many uses as jquery has overloaded function signatures so we'll represent our histogram as a javascript array within with a positive integer and every position that will represent the y-axis and then the represent the y-axis and then the represent the y-axis and then the position in the array will represent the x-axis so let's call this function find x-axis so let's call this function find x-axis so let's call this function find largest rectangle so right off the bat I can know that we need at least something to address the height that were currently at and something to store the position that we're currently at so today we're going to code using a for loop which is an ancient form of loop used way before there was a for each for everything back before javascript engineers only knew how to do things with callbacks javascript is just so full of callbacks unlike my dating life so we can use an object or we can use an array to represent our stack I think it probably makes most sense to use an array for efficiency's sake you really want to avoid manipulating the data structures pushing popping things like that luckily v8 is done a pretty good job of optimizing the basic array operations like push and pop so even though we're abusing the data structure I think it will be fairly efficient so instead of using a peek method like you would in a normal stack we'll just index to length minus 1 so remember we have two cases here basically we've got the case where we are either at the beginning of our stack or we have a value that's bigger than what's on top of our stack and in that case we just want to push these values this height in this position into their respective stacks and then there's the other case the case where whatever we've arrived at is less than what's on the top of our stack if we're there then we got to do some real work if you remember back a few minutes where we discussed the algorithm for this what we said was when you find a height that is smaller than the height that's on top of the stack you have to pop that item off the stack figure out what size rectangle it was composing figure out if that was the maximum size of rectangle you've ever seen here I'm going to do something a bit creative I am going to take advantage of JavaScript's ability to just put functions anywhere because after all javascript scoping is looser than the Taco Bell shits so my function within a function is called pop that because we're going to pop that off the top of the stack as many times as it takes to get to a height that is the same or lower than the height that we currently have they I have a very specific reason for doing this I'm going to use exactly the same logic in a couple of places in my trial runs I actually ran out of whiteboard space so I'm going to move pop that up here to the right corner to keep it out of the way so just imagine that pop that is declared as a function inside of this function right here and the logic of pop that is actually pretty simple we need to know the height that's at the top of the stack we need to know the position that's at the top of the position stack and because we have access to the enclosing scope we can also know what the current position is and if you remember back to our walk through the algorithm those three things are what you need to determine the area of whatever rectangle we're currently closing and take note I'm not creating the variables that pop that is interacting with inside of the scope pop that I'm creating these variables in the enclosing scope and that's because I want to have one scope where all of my variables exist because as you'll see in a second I actually need some of the results of pop that inside the fine largest rectangle function so really just think of pop that as a four line helper that is completely subordinate to the fine or just rectangle function and once we grab the height and the position that's at the top of the stack we're going to calculate the area of the rectangle that we just finished that we just popped off the stack and we're going to figure out if that area is bigger than the biggest area we've seen that's all pop that is four so after some number of poppings we will have reached a position in the stack where the current height in the stack is less than the height that we care about the height that we're currently at and if that's at the beginning of the list where all the way at the start of the stack you're going to put that back onto the top of the stack so that you don't lose track of where the current rectangle that you're dealing with started and remember to be in the state that we're in at all there had to have been bigger values in the left-hand side of the rectangle that are left-hand side of the rectangle that are left-hand side of the rectangle that are just now coming to a close with our current value which means whatever value we have right now the rectangle that it's composing actually started somewhere to the left so we need to keep tract of that temporary position that sort of earlier position value and push back onto the stack with the height that we're currently at and where that height started another way to think about this process is sort of looking back in time let's say we're at a height - and we've let's say we're at a height - and we've let's say we're at a height - and we've got three things on the stack already then two is now the smallest number that means that this - actually started three means that this - actually started three means that this - actually started three positions ago and so we need to go back in time and figure out what the first value in the stack is that's bigger than two and steel its position because that's actually the start point of our height - rectangle so once we've height - rectangle so once we've height - rectangle so once we've finished iterating over this list we might have a bunch of stuff in the stack that hasn't closed yet that hasn't had a lower value come next and so basically we need to redo the pop that approach but instead of stopping when we hit a smaller number we're going to stop when we hit the end of the stack when the stack is empty we don't yet know what the areas of those rectangles might be so we actually have to do another loop here to purge the stacks to grab each value out of them and calculate the area of the rectangles that they represent and from those figure out what the maximum value would be and with that you can pretty much just mark a drop and walk away because you are the Supreme Lord of code all kneel before me and my insane algorithmic competence but if you did that you'd be up because the first thing you should do when you finish coding an algorithm like this is look at your own code line by line and look at what you up because you did something up so here for instance if we take a step back you'll notice for one I didn't close the array access for Shane Gabbard for shame and so then you can mark a drop in flexed oh I'm the king of all the code ah but if you did that you would still be up because in fact there's a glaring error in this code and it's in the second half of the if-else the mistake second half of the if-else the mistake second half of the if-else the mistake here is the assumption that the stack has to be empty in order to push the value back on top of it and you can see the error of this if you imagine a histogram of the sort of 1 3 2 in that case when you get to the two you will have a 1 and a 3 on the stack already now if you pop the 3 off because you should because that's what the algorithm will do then there will still be a 1 in the stack so the length of the stack the height of the stack is going to be 1 but you still need to push that 2 back in there so this is actually incorrect logic we're just going to kind of magically wipe that out and with that you can declare everyone your royal subject and tell them to kiss the ring that's the American ring not the British ring I hope you enjoyed this episode this is number five of the series and it's going to be the last one for a few weeks because I'm getting ready to move as always if you liked the episode if you hate the episode if you think my JavaScript sucks I mean let's be real it sucks then hit me up in the comments let me know what you think and if there's a specific question you would like to see here also comment with that as always thanks for watching blood
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_. **Example 1:** **Input:** heights = \[2,1,5,6,2,3\] **Output:** 10 **Explanation:** The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. **Example 2:** **Input:** heights = \[2,4\] **Output:** 4 **Constraints:** * `1 <= heights.length <= 105` * `0 <= heights[i] <= 104`
null
Array,Stack,Monotonic Stack
Hard
85,1918
189
hi all welcome to learn code repeat so today we'll be looking at day 15 of the october elite food challenge the name of the problem is rotate array so before we start the problem if you haven't subscribed to the channel please do subscribe to the channel and hit the bell icon so let us look into the problem so the problem says given an array rotate the array to the right by k steps where k is non negative the follow up is try to come up as many solutions as you can there are at least three different ways to solve this problem could you do it in place with o of one extra space so the input is one two three four five six seven that's the num array and k is three so we have to take the last three digit from the end so here it is five six seven and place that at the start of the array so it will be five six seven and then it will be one two three four okay that is expected output the constraint here is nums dot length is greater than or equal to one and it is less than equal to 2 into 10 raised to 4 the values in the nums array can be between minus 2 raised to 31 to 2 raise to 31 minus 1 which is integer dot mean value to integer.max value to integer.max value to integer.max value k can be greater than or equal to 0 and less than or equal to 10 raised to 5. so let us look into this first example so the input is 1 2 3 4 5 6 7 and k equals to 3 right so here what will happen is when k is 1 right we have to move 7 to the start so it will become 7 1 2 3 4 5 6 and then when k is 2 it will become 6 will move to start so it will be 6 7 1 2 3 4 5 then when k is 3 that is in the third step it will be 5 will come to the start so it will be 5 6 7 1 2 3 4 and this is the final output okay this was this initial and this is the final so there are three steps right the first thing that we have to check is k can be greater than the length of the nums array so we can directly do k equals to k mod num start length so that way if let us say k is 30 right so we can check the length is nums dot length is 7 and k is 30 so 30 mod 7 is 2 right so it's same as k equal to 2 right now in this case k is 3 so let's take k equal to 3 now if you observe here right what we are doing is we are placing this 5 6 7 right 2 here right so 5 6 7 is this is 1 and then 1 2 3 4 is here this 2 right so one way to solve this is starting from the first element from the right which we have to move so here the first element from the right is 5 right so if i write down this here 1 2 3 4 5 6 7 so i will do the length minus k value which is 7 minus 3 so it will be four so zero one two three four so first the pointer will be here this i need to move three points right so i will move it in a cyclic way so one two and three so three is here right so 5 will come here now this value which is currently at this position right that again i need to move 3 points so 1 will now move 3 points so 1 2 3. so 1 will now come here now four again needs to move three points so four will move three point one two three so four will come here now seven will need to move three points so seven will move one two three 7 will come here now 3 need to move 3 points so 3 will be 1 2 3 will come here now 6 needs to move 3 point so 1 2 3 so 6 will come here now 2 needs to move 3 point one two three two will come here right now as soon as we are at the starting index right we started with this five and again we are again coming to the same index right at that time we can break so if you see the final output it is same as this ok five six seven one two three four so this is one way this is using one loop we can do it in a cyclic manner ok there is one more way and we will look the code for that which is much more simpler to understand so first what we will do is the number is one two three four five six seven we can directly reverse that number so if we reverse the number you will get 7 6 5 4 3 2 1 correct so if you see here we need the end result as 5 6 7 is present but it is present at the starting three position right which is same as k equal to three ok so if i break this at k equal to three right the first three element and if you try to observe what is the difference between this value and the actual result that we expect right we observe that the first three element it is reverse of what we expect right so if we just reverse this part right and then we reverse this part let's see what will happen so if we reverse this part we will get 5 6 7 and if we reverse this part we will get 1 2 3 4 which is same as exactly what we want right so the step is basically first step is reverse the whole nums array from 0 to let us say n is the length so n minus 1 right length minus 1 the whole thing so once you reverse the whole thing then i again need to reverse the same call the reverse function this is the second step but this time i will call first for this right so it is nums but it will start from 0 and it will be till k minus 1 right i am both start and end is inclusive ok so it will be k minus 1 the third step will be again i am calling the reverse and this time it is only for this right so it will be starting with k right its a zero index so it will start with k till n minus one and in this three steps will be able to solve the same thing here we are going through the entire array so it will o of n that will be the complexity here we are going till o of k minus 1 and here it is k to n minus 1 adding this together is n so this is also o of n together so n plus n is o up to n which is same as in total the complexity is of n so time complexity is o of n and we are not using any additional space so space complexity is o of one even for the cyclic solution right time complexity is o of n and we are not using any additional space so space complexity is also of one ok so let us code this so here first we did a k equal to k mod let us say length is the num start length so let me define length here so k equal to k mod length once we have done that now we will call the reverse function so reverse nums 0 till length minus 1 i am just copy pasting this reverse again and now it is 0 till k minus 1 and then it is k till length minus 1 and i can define the reverse function here so this will be basically while my low is less than high so the way i am reversing is i am swapping the start and the end value that is the low and high value i can simply swap until my low is less than high so that way we can reverse the string or reverse the array right its normal reverse function so i will have a number of low equal numbers of high and numbs of high equal to m and then i need to increment low plus and high minus so this is a simple solution as i said time complexity is o of n so let us run this code so this test case pass let us run for let us see if it is just one element okay this is also fine let submit this code and the code is accepted so that's it for this video please do hit the like button and do subscribe to the channel for future such videos thank you
Rotate Array
rotate-array
Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative. **Example 1:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 3 **Output:** \[5,6,7,1,2,3,4\] **Explanation:** rotate 1 steps to the right: \[7,1,2,3,4,5,6\] rotate 2 steps to the right: \[6,7,1,2,3,4,5\] rotate 3 steps to the right: \[5,6,7,1,2,3,4\] **Example 2:** **Input:** nums = \[-1,-100,3,99\], k = 2 **Output:** \[3,99,-1,-100\] **Explanation:** rotate 1 steps to the right: \[99,-1,-100,3\] rotate 2 steps to the right: \[3,99,-1,-100\] **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1` * `0 <= k <= 105` **Follow up:** * Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem. * Could you do it in-place with `O(1)` extra space?
The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements.
Array,Math,Two Pointers
Medium
61,186
622
hey everyone welcome back and let's write some more neat code today so today let's solve the problem design a circular queue basically we want to implement this data structure a circular queue where the operations are performed in fifo order so as we add elements to the queue we're going to be removing the ones that were first inserted so you know like suppose we added a one we added two we had a three then it's time to remove elements we'd add the first one that was removed then the second one then the third one etc so basically what you would expect from a queue data structure but in this case it's going to be circular and actually the fact that it's a circular queue isn't really going to mean anything the way that we implement it so there's really two main ways that you could implement this problem one is using arrays and that's not the way i'm going to be doing it just because i think it's a little bit more intuitive to do it the other way which would be implementing it as a linked list i think it's just a bit more intuitive to do it this way i think it's slightly more code but it's also slightly more efficient because with an array you're going to have uh you know the size of the queue is going to be an input parameter we're given which is k we're going to have to create an array of that size but with linked lists we don't really need to do that we only need as much memory as there are elements in the queue at any given point in time but just to give you kind of an idea of how it would go with an array suppose you know k equals three then we'd have three elements so our array would be of size three let's say we add a one okay then we add a two then we add a three and then when it's come to pop an element of course we're going to pop from the left side so okay we remove there but now it's time to add another element suppose we want to add the value 4. well there's no space over here but there is space over here so we would add the 4 over here and that's where the idea of a circular queue comes from because now we can add at the other side of it but you're probably thinking now if we have to pop an element are we going to pop the 4 because that's not fifo right we should pop the two and yes we are gonna pop the two if we have to pop a value the way we're gonna implement this by the way would be uh with two pointers so the first pointer would be you know the uh front of the queue and the other uh would be the end of the queue the rear of the queue i guess the rear would not be here in this case the rear would actually be four because four is the last value that we just added so you know let's say we pop the two now okay we pop the two then we would say that this is the front of our queue now if we wanted to add a cue so this is no longer the front the rear of our queue is still over here if we wanted to add another value we'd add it after the rear so we would add the value over here so that makes sense and it's not too difficult to implement it this way but we are going to be implementing it slightly differently we're going to use a linked list so let me show you how to do that so first let me actually run through the operations that we're going to implement and then i'm going to show you how we can efficiently actually implement those so we're going to initialize the circular queue with a limited size of k that's the max number of elements we can have in it we're going to have an operation front which is going to let's say that this left side is the front of our queue and let's say the right side is the rear of our queue front is basically going to return what value is at the front of our queue if one exists if it doesn't exist we would return negative one similarly on the rear of the queue we want to get the value of it if it doesn't exist we can return negative one nq is going to be the operation that adds a value to the end of the queue this is the end of the queue the rear of the queue this is where we're going to be adding values to and if we are if we have enough space to add a value we're going to add it right here and then we're going to return true if we don't have enough space we're going to return false similarly with dq is where we remove elements we're going to remove elements from the front of the queue over here if there is an element for us to remove we're going to remove it and return true if there's no elements to remove we're going to return false is empty and is full or actually helper functions pretty much for us we can actually use these functions for the nq and dq operations so is empty is basically going to tell us are there any elements in our queue if there's not we're going to return true if there is we return false similarly with is full if we have no space left we're going to return true it is full if we have space we return false for that so knowing that we clearly know we're going to be needing to interact a lot with the front of the queue and the back of the queue so the easiest way to do this as i've shown is using a couple dummy nodes if you're not familiar with dummy nodes it's basically just to remove edge cases right as we add values to a linked list and remove values we run into a lot of edge cases what if the linked list is empty well what if it has one value what if it has two values what if the node we're looking at is in the middle of the linked list or at the end of the linked list or at the front of the linked list there's a lot of edge cases dummy nodes remove those edge cases for us because a left node is our dummy node on the left right is always going to be the dummy node on the right so therefore any value that we add or remove from the queue is always going to be in the middle of the queue therefore we don't have any edge cases and also these nodes could be singly linked lists if we wanted to but we're going to make them doubly linked lists because as you can see we're going to need to be reading values from here and also values from here so we're going to need the second pointer okay suppose we wanted to add a value now well we would just create a new linked list node let's say the value of it is one we would say okay the left node which is our dummy nodes next pointer instead of being instead of pointing at the right node because how we're actually going to initially initialize this is going to be like this these two nodes are going to be pointing to each other and there's nothing in the middle but as we introduce a new node like one in the middle we're gonna want to obviously rearrange these pointers we're gonna actually say that this pointer should be now pointing at one and the previous pointer here instead of pointing at left it should be pointing at one as well and of course the pointers from here are going to be pointing at the right node and uh be going to be pointing at the left node now if we have to add another value actually i don't know if i said the opposite earlier but we're always going to be adding values here because it's the end of the queue right so in this case we could add a value you know in the middle here but really where we want to add it is over here so uh we let's say we add a 2 value here obviously this pointer which was previously pointing here is now going to have to point at this node uh this pointer which was pointing at this one is now gonna have to point at this node as well the pointers of this are gonna be pretty simple next and previous and the rest of the operations like is empty is full are gonna be pretty simple for us for is full we're just going to keep track of a counter if we have reached our capacity of values then this function will be easy to determine for front and rear the way we've implemented the solution it will be very simple so right now if we wanted the front of the queue we would just look at our left pointer look at the next node and then take the value of it of course only if the value existed if it didn't exist we return negative one so in this case we would return one if we wanted the rear of the queue we do the opposite with the rightmost node look at the previous node take the value of it and then return two now the last operation the interesting one that we haven't looked at is dq where we're going to have to remove a value this is a mostly straightforward linked list operation so we know that the node that we're going to have to remove is going to be over here but before we even remove a node we would want to make sure that our linked list is not empty if it's empty we're not going to do anything but if it isn't empty then we're going to have to remove a value we would look at our left node this is the side that we're going to be removing elements from how are we going to remove it well simply by updating the pointer so this pointer instead of pointing here since we want to get rid of this we're going to update this pointer as well to now point at the next one similarly this node maybe it exists and if this node didn't exist we would have to obviously use this node because at least we guarantee that we're going to have a node on the right side of it but in this case we do have this node what we're going to do is want to update the previous pointer because this node doesn't exist anymore so we can get rid of this and swap it to be over here so that's pretty much the entire uh operations that we're going to be implementing it's pretty easy as long as you use a doubly linked list and you have a dummy pointer on the right and a dummy pointer on the left so now let's code it up okay so now let's code it up and this is basically you know the data structure that we're given but we know that we want to have a linked list node a doubly linked list node so i'm going to call it list node and the constructor in this case is going to take a couple inputs so self is just a reference to the variable the object itself k is going to or not k value is going to be the value of the list node next is going to be the next pointer of the list node and previous is going to be the previous pointer of the list node so we're just going to basically save all three of these values in variables so self.value these values in variables so self.value these values in variables so self.value self.nextpointer self.nextpointer self.nextpointer self.previous pointer are going to be self.previous pointer are going to be self.previous pointer are going to be assigned to the value the next pointer and the previous pointer so that's pretty simple obviously i could have broken this down into three lines but i don't really care so now we want to initialize our q we're given a value k which is going to be the maximum capacity of the q i'm just going to store that in a single variable which is the amount of space that we have left over right now so that's going to be assigned to the val the variable k and we're going to be decrementing this as we run out of space and we're going to be incrementing it as we gain more space next we want to of course initialize our left and right pointers left in this case is going to be a list node now the value we give it doesn't really matter we're just going to give it a default value of 0. the next pointer is going to be none for now it's going to be null the previous pointer is also going to be null for now we're also going to initialize the right pointer which is also going to be a list node a default value of 0. now the next pointer of it is going to be none but the previous pointer we can say is going to be self dot left because we've already initialized the left pointer that's going to be the previous node from the right also we want to make sure that the next node of the left is also the right node so let's do that with the line below self.left dot next with the line below self.left dot next with the line below self.left dot next is going to be the right pointer so now we've basically initialized a doubly linked list of two dummy nodes so for is empty we know that it's empty if there's no values in the node basically if only the left and right dummy nodes exist how do we know if those are the only nodes that exist well we can literally check that we can check left dot next is equal to the right node uh the right dummy node if that's the case then these are the only two nodes that exist so we know for sure it's empty we technically don't even need the space variable in this case but the space variable is going to come in handy for the is full operation we know that it's full if there's no more space left so basically if self.space is equal to zero in that case self.space is equal to zero in that case self.space is equal to zero in that case we can just return that okay so those were the easy ones now let's get to slightly harder operations like front and rear so how do we get the value at the front of the queue well first we have to make sure that it's not empty because if self dot is empty if the queue is empty what are we going to return well they told us to return a default value of negative one but if it's not empty then we're going to return uh self dot left right the next node from the left and then return the value of it similarly for the rear of the queue we want to make sure first that it's not empty and then we want to return the uh the right rightmost value so we're gonna say self.right and we so we're gonna say self.right and we so we're gonna say self.right and we want the node before the right node so self.write.previous self.write.previous self.write.previous and the value of it so we've almost finished this entire problem but now we just have to take care of the hard ones like nq and dq so adding a value to the queue can only be done if there's enough space so if self dot space is equal to zero that means we don't have enough space so then we have to return and we have to return false because we couldn't successfully complete the operation but if there is space then we're going to add it to the right side of the queue so first we're going to actually create a list node so let's do that the value of the list node is going to be value the next pointer of the new node that we're creating is going to be self dot write the rightmost node what's going to be the previous pointer of the new node that we're creating it's just going to be the current node that's to the left of the right node so we could also say self.right.previous self.right.previous self.right.previous that's going to be the previous pointer of the new node that we're creating so we created this node let's assign it to a variable called cur for now and now we just want to update the pointers of the node that's to the right of it and the node that's to the left of it so we want to say first let's start with the left node and you'll see why i'm going to do that so self dot write dot previous we want its next pointer to be pointing at uh the current node now instead of pointing at the right node so literally we're just gonna do this remember this is the node that's to the left of cur and we're setting the next pointer now equal to cur and after that we also want to update the value the node that's to the right of curve which is self.right and we want to say which is self.right and we want to say which is self.right and we want to say self.write. self.write. self.write. is now going to be equal to ker you can see why i did these two assignments in this order because if i did this one first then uh you know this operation would have been different this would not have been updating the node that's to the left of ker and if it's kind of confusing i would recommend drawing it out yourself just to confirm after we've added a value we can go ahead and return true but before we even return true we also want to make sure that we update the space of the queue so self dot space is going to be decremented by one so that wasn't too bad and we only have one operation left dq so before we dq we want to make sure actually before we even do that i realized here we checked if space was equal to zero but we technically did that in our is full function so just to kind of make this a little bit cleaner let's just actually reuse that function that we already wrote so if is full then we can return false now we want to remove an element now we can't remove an element if our queue is empty so if is empty we're going to return false because we can't complete this operation successfully then but if it's not empty then we can remove the node and we want to remove the node that's on the left side so we can do that pretty simply by saying left dot next instead of pointing at the next node we want to actually point at the node after that so we can literally do something like this it's going to be quite a lot of chain so self.next dot quite a lot of chain so self.next dot quite a lot of chain so self.next dot next we're basically shifting that next pointer to point at the node that comes after it so now that this is pointing at the node that comes after it we also want to update the previous pointer of that node to now no longer point at the node that we're removing right now so this dot previous is going to be set to self dot left i know this is probably confusing because it's kind of abstract that's why i recommend drawing it out if it doesn't make sense to you and remember if we remove a element from our queue then we have to increment the space by one because there's a new free space and we can return true to say that the dq operation was successful so that is the entire code i know it's pretty long that it doesn't even fit on one screen but the bottom stuff is pretty straightforward it's really these nq and dequeue functions that's difficult and the constructor but let's run it to make sure that it works and as you can see on the left yes it does and it's very efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Design Circular Queue
design-circular-queue
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. Implement the `MyCircularQueue` class: * `MyCircularQueue(k)` Initializes the object with the size of the queue to be `k`. * `int Front()` Gets the front item from the queue. If the queue is empty, return `-1`. * `int Rear()` Gets the last item from the queue. If the queue is empty, return `-1`. * `boolean enQueue(int value)` Inserts an element into the circular queue. Return `true` if the operation is successful. * `boolean deQueue()` Deletes an element from the circular queue. Return `true` if the operation is successful. * `boolean isEmpty()` Checks whether the circular queue is empty or not. * `boolean isFull()` Checks whether the circular queue is full or not. You must solve the problem without using the built-in queue data structure in your programming language. **Example 1:** **Input** \[ "MyCircularQueue ", "enQueue ", "enQueue ", "enQueue ", "enQueue ", "Rear ", "isFull ", "deQueue ", "enQueue ", "Rear "\] \[\[3\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, true, true, true, false, 3, true, true, true, 4\] **Explanation** MyCircularQueue myCircularQueue = new MyCircularQueue(3); myCircularQueue.enQueue(1); // return True myCircularQueue.enQueue(2); // return True myCircularQueue.enQueue(3); // return True myCircularQueue.enQueue(4); // return False myCircularQueue.Rear(); // return 3 myCircularQueue.isFull(); // return True myCircularQueue.deQueue(); // return True myCircularQueue.enQueue(4); // return True myCircularQueue.Rear(); // return 4 **Constraints:** * `1 <= k <= 1000` * `0 <= value <= 1000` * At most `3000` calls will be made to `enQueue`, `deQueue`, `Front`, `Rear`, `isEmpty`, and `isFull`.
null
null
Medium
null
6
hello everyone welcome or welcome back to coding chance in this video we are going to be solving the problem zigzag conversion in this problem we are given with a string which is written in a zigzag pattern on a given number of rows like this and we have to then read it line by line so if this is the exact pattern of the given string and then we have to read it line by line a p a h and APL s i g y i r this will be the resultant string after conversion you have to write the code that will take a string and make the conversion give a number of rows okay so we have to we have given with a string and then we are given with a number of rows and we have to uh convert it and get the resultant string so let's take a look at the examples we are given with this ring and the rows PayPal is hiring and the rows as three so this is this exact format will be like this if we read it line by line we get this result n string so we return it and then we have the same string with number of rows as four uh so this will be this exact format and we read it line by line so we get p i n a l s i g and so on so we get that we return that as output if we have the string a and number of rows has one if the number of rows has one we write all the characters in the same room we read it by that row that means the string will remain same so we return the same string so this will be the base condition if we have number of rows as 1 we can return the string directly so let me write that down if number of rows is equal to 1 we can directly return the string in the other cases what we have to do we have to mimic this with exact pattern and find the position get the resultant strings so this looks like an implementation problem there is no data structure or algorithm is applied in this problem we have to just find out the indexes of the characters and place them in the right positions to get the resultant string so let's see how we can do that so let me take this example we copy this and paste it over here next let us take this example as well and paste it over here Okay so let us see so after P we are getting a we are skipping some number of characters to get this in here also after P we get I we are skipping some number of characters to get the next character right um so how many characters we are skipping in the first case we are skipping three characters in the second case we are skipping five characters here the number of rows is 3 and here the number of rows is four so in this case we are skipping three characters and in this case we are skipping 5 characters to get the next character the P index is 0 the index is 4 in between the difference is 3 and here also the same um and again from a the next index is H again we are skipping three characters to get H from H again for n we are skipping three characters uh here as well after I we are skipping five characters to get the next so we are skipping some amount of characters to get the next character uh so firstly how many characters are let us count we are skipping in the first row we are skipping two characters we are excluding p and then we are skipping the rest of the characters so number of rows we consider all the characters in this room which means the number of rows this column so the number of rows minus we exclude P so minus 1 and in this line uh we consider this because we want to get the eighth index so we include a NP we exclude y because we already included before so next number of rows minus one so we can simply write it as 2 into number of rows minus 2. okay um so let us call it as Spica so we skip this number of characters to get the next characters so in three case two into three minus 2 into 3 minus 2 4 so to get the this is the zeroth index and the next character will be at Fourth index and again we do the same thing we increment 4 by 4 to get H which is an eighth index similarly here 2 into 4 minus 2 which V6 so p is 0 at index we add 6 to that index to get I then again to sixth index we again add six to get the next index let's see here when we get to a and then the second row we add 6 then we get one two three four five six we get to S but we here we are skipping the L in this cycle so this middle characters we should find a way to include these middle characters as well this middle characters are present in the middle rows it they are not present in the first row they are not present in the second row in the Middle where we are having this exact pattern there only we have some characters which are getting excluded while following the cycle so we have to find a way to include them as well there should be another formula to see this latest computer formula so what are we doing here so from uh let's take this so from P we are getting let's take this condition from a we are getting yes because there is no middle character here so I have taken the second row uh we are at K and then we go to S so a is these are 0 1 these indexes are 0 1 2 3. the first row will the First Column will have the 0 1 2 3 continuous index is only the row will be the index of the starting character um so firstly we added a so we have the index as one and when we increment it by 5 we go to um what we when we incremented by since then we go to the index seven so what we do J let's cycle then we get this character let's say the rows as I and the call the columns the The Columns as J so we are at a and then we add cycle two when then we go to S how many characters we have to reduce to get L we have to remove s and I to get l so it is nothing but minus 2 so we are at first row and we have to remove minus 2 to get this index if we are at the second row uh second index row which means the third row we are at Y and we go to H in the when we apply cycle and we have to get the skipper character in the cycle so to do that we have to remove one two three four in the third row we have to remove two so in the first we have to remove do and in the second we have to remove four if you keep on doing this then in each row we have to multiply it by two multiply the row number by 2 to get it the sub the index of the row is one and this is second row and this is the third row so in each row we have to multiply this two with two in order to get the row the number of characters we have to skip to get the middle character so this formula will be J minus i k minus 2 into what the row index so row we took the Arrow index as I so this will be the formula to get the middle character so this is the formula to get the next character and this is the formula to get the middle characters in The zigzag rows so let's score it up let me comment this when we code it will get more clear so firstly um let us compute this cycle so it will be one factor equal to 2 into number of flows minus 2. and we have to take a result string so result equal to empty string and then first we activate over the rows so first I equal to 0 I left when number of rows and I plus then we added over this column uh the values in the rows so for that J equal to we start at um here the index of p is 0 1 2 3 which are same as the row indexes so we start with I the row index and we go to string size and each time incremented by cycle and we add it to our result we add the character to our result and next we have to check for this condition as well this is present in the median rows where the zigzag pattern exists so if I the row is not equal to the first row and the row is not equal to the last row number of source minus one and let's compute the formula and in k equal to what is the J Plus 5 curve minus 2 into I so we have to check if this K value exists K is less than s dot size then we add it to our result equal plus equal to S of J and finally we return the result looks good let us run the code it passed all the sample test cases let us submit it passed all the test cases so let us discuss the time and space complexity um the space complexity is splitting here right we are using only variables so the space complexity will be of one if we exclude this result see if we include this result string the space complexity will be of N and what about the time complexity so here we have two nested Loops but if you clearly observe this Loop goes to I less um 0 to number of rows and this Loop goes to uh S size but in cycle If You observe we go to each character only once so even if we have two nested Loops the time complexity will be o of n it's like the DF is where we go to each node only once even though we have a nested array nested Loops here also even though we have nested Loops we go to each character only once so the time complexity will be often and the space complexity will be o of n as well so this is for this video I hope you understood the solution and if you did make sure you hit that like button and do subscribe to codingcharms for more daily videos and see you all in my next video till then keep practicing bye
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
746
hi everyone today we are going to solve the little question minkos climbing stairs so you are given an integer array cost where cost I is the cost of I step or staircase once you pay the cost you can either climb one or two steps you can either start from the step with index 0 it was a step with index one Returns the minimum cost to reach the top of the floor so let's see the example so you are given input a cost like a 10 15 12 output is 15 because you will start at index one okay 15 and the crime two steps to reach the top so total cost is 15. yeah um that means the last index is not the top of raw so yeah this is a very ambiguous description because if I take two steps from index 0 we can this last index directory in that case output should be 10 because the 10 is smaller than 15 but output is 15 so that means the top of the forward is out of bounds brace here so be careful it's very ambiguous description so let me explain how to solve this question before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so I think there are several ways to solve this question but in my opinion the easiest way to solve this question is that iterates through the input cost from the last to in Excel the reason why I iterate through the input cost from the last is that imagine you have a lot of cost in the input array so in that case it's tough to decide whether I should take one step or two steps from current place because we don't know what number is coming next so that's why now fixing the minimum cost from the last is easy to decide Okay so let's think about Alexa 10 15 12. and uh first of all as I explained earlier the top is out of bound place so at first we need to add zero to the last so this is a top place so let's think about the 20 so if I reach the top definitely we can reach if I take a one step from the index 2 is 20. so how about index one so we have two Choice take one step or take out two steps so let's compare the minimum cost so if I take a one step so minimum cost should be 15 oops 15. Plus 20. uh because if I take a one step we did the index two so from index two so minimum cost is 20 so that's why uh if I take a one step from index one um minimum cost uh should be like a 15 plus 20. and uh how about taking uh Two Steps From index one so we can directly reach to the top so minimum cost should be 15 Plus zero so compare the two numbers and then take a minimum cost so definitely this one 15 so that's why minimum cost from index one should be 15. and the how about the index still so again we have two Choice take a one step what two steps yeah a little bit messy so again uh minion compare minimum cost 10 Plus 15. versus 10 Plus 20. so compare minimum cost so definitely uh this one is a minimum cost so 25 so that's why from index 0 minimum cost should be 25. I can take a one step and then take a two steps yeah 25 looks good so at last description said we can either start from like an index Style or index one so that's why we need to compare two numbers like this negative 25 versus 15 and return the minimum number so definitely 15 is a smaller than 25 so that's why output should be 15. so that is a basic idea to solve this question and the time complexity of this solution should be order of n because I get through all numbers one by one and a space complexity is actually a one I don't use the extra data structure and we use the input array itself so that's why space complexity is order of one so with that being said let's jump into the code okay so let's write the code first of all are zero to input array so zero so that is top like a 10 15. 20 0. and then start looping from the last for taking index in length of input array minus four because we don't have to care about these last three numbers because uh we can take two steps so definitely um we can reach the top directory so that's why minimum number should be the number itself like 20 or 50. so that's why we can start educating from here negative 10 in this case so 10 is like a minus one minus two minus three minus four so that's why I put -4 three minus four so that's why I put -4 three minus four so that's why I put -4 here and a minus 1 and the minus one and the current number plus equal oops plus equal and compare two numbers so mean cost current plus one who are cost current plus two and then so compare two numbers like this is a number when I take a one step and then this is a number when I take two steps and the compare two numbers and take a minimum number and add the number to current number then after that so return minimum cost and the cost zero or cost one so description said we can start either index 0 or index one so at last we need to compare two numbers and take a minimum number as our return value yeah actually that's it so let me submitted yeah looks good this solution works so let me summarize step by step algorithm this is a step-by-step algorithm of main this is a step-by-step algorithm of main this is a step-by-step algorithm of main course climbing stairs step one append zero to the input array step two start looping from the last index minus four at minimum cost to current value step 3 compare values of index 0 and the index 1. in the return minimum value after that's it I hope this video helps you understand this question well if you like it please subscribe the channel and hit the like button or leave a comment I'll see you in the next question
Min Cost Climbing Stairs
prefix-and-suffix-search
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index `0`, or the step with index `1`. Return _the minimum cost to reach the top of the floor_. **Example 1:** **Input:** cost = \[10,15,20\] **Output:** 15 **Explanation:** You will start at index 1. - Pay 15 and climb two steps to reach the top. The total cost is 15. **Example 2:** **Input:** cost = \[1,100,1,1,1,100,1,1,100,1\] **Output:** 6 **Explanation:** You will start at index 0. - Pay 1 and climb two steps to reach index 2. - Pay 1 and climb two steps to reach index 4. - Pay 1 and climb two steps to reach index 6. - Pay 1 and climb one step to reach index 7. - Pay 1 and climb two steps to reach index 9. - Pay 1 and climb one step to reach the top. The total cost is 6. **Constraints:** * `2 <= cost.length <= 1000` * `0 <= cost[i] <= 999`
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
String,Design,Trie
Hard
211
1,913
so hello guys my name is arsalam welcome back to my channel and today we will be solving a new liquid question that is maximum product difference between two peers so the question says the product difference between two pairs a b and c d is defined as a into B minus C into D for example the product difference between 5 6 and 2 7 is 5 into 6 minus 2 into 7 is equal to 16 given an integer array number two spot distinct the value w x y z aside that the product reference between two pairs nums W num so X and nums Y and num set is maximized so return the maximum of such product difference so we will be solving this question with the help of python so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel so the question says that we have to choose four numbers here and we have to return the maximum product of those numbers so uh you see that maximum product will be the maximum two numbers minus the minimum two numbers so uh if you see here they are saying that they take two maximum number from here that is my six and seven uh six seven will be my two maximum number in this uh array of nums and my minimum numbers will be two and four so if you multiply into maximum number and multiply minimum number we will get the difference as the maximum difference similarly in here we will be getting two numbers at nine and eight and two are four and then we will multiplying their differences will first we will multiply the maximum and minimum and then if we subtract this value we'll be getting a maximum difference so let's start solving this question guys so this is the Sorting method first of all what I will be doing that I will be creating a sorted uh array here and sorry sorted variable here sorted the numbers is equals to I will sort my array and I will say sorted numps okay so when I saw this num I will be getting this in a form of this I will be getting this in the form of 2 4 5 6 7 so by what I will be taking I will just taking these two values and again these two values or and if I thought the last this one if I thought I will be getting what let me put it here and I will be getting two four I will be getting what I will be getting 2 4 then 5 7 8 and 9. so I will multiply these two values and multiply these two values so the basic ID of this at the maximum value are the last two digit number and the minimum value are the first two digit numbers in an array so first two elements are the minimum number and the last two elements are the maximum number that's the point here let's return 40 norms Ctrl C and we see that I put a break it here and it will have a written something here sort it now maximum will be -1 maximum will be -1 maximum will be -1 into again for Titan ohms minus 2 and this whole will be subtracted so I'll be talking a bracket here and I will put it minus here and I take another bracket here and I will put here this and I will say that 0 into sorted nums one so this was all in the question guys I will run the code now and show it to you that it was this only so let me try it for multiple test cases so that we can be assured of the answer and run for run the code so you see that we have got our answer here so this was all in the question guys hope you have liked the video hope you will subscribe to the channel and hope you have understood the concept here so if you have any uh if so if you guys have any doubt ask in the comment section I will try to help you out so thank you guys for watching the video see you next time
Maximum Product Difference Between Two Pairs
make-the-xor-of-all-segments-equal-to-zero
The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`. * For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`. Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**. Return _the **maximum** such product difference_. **Example 1:** **Input:** nums = \[5,6,2,7,4\] **Output:** 34 **Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). The product difference is (6 \* 7) - (2 \* 4) = 34. **Example 2:** **Input:** nums = \[4,2,5,9,7,4,8\] **Output:** 64 **Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). The product difference is (9 \* 8) - (2 \* 4) = 64. **Constraints:** * `4 <= nums.length <= 104` * `1 <= nums[i] <= 104`
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
Array,Dynamic Programming,Bit Manipulation
Hard
null
171
Yes, hello, I am one of the developer children, Gary Ni. Today's Pro Bowl problem is number 171, the CeCi column number. A string color on the title is given. This is a problem that represents the column that represents the color in the Excel C font. The column number corresponding to this is opened. The goal of this problem is to write a function that returns. Let's take an example. If a comes in, it's 1 day. If b comes in, e comes in, 3's what comes in is 26, if aa comes in, it's 27, and if ap comes in, it's 28, etc. It goes on like this. Well, when jet y comes in, it returns 702, and when it comes in, I do this number l. Basically, solving the problem is easy. Let's solve it. First, basically, to express the numbers from a to jet. I will create a string of sentences that are listed from a to jet. I will call it the alphabet. It is not a question of ab being an alphabet with 26 letters listed in a row. And what I do with d is that I declare a variable called dc. 26 So, the new alphabet of the alphabet is It indicates how many numbers there are. It is easy to think of this string as a hexadecimal number. Just as it is written in binary, decimal, octal, and hexadecimal, this number itself and this letter are called this hexadecimal number with the alphabet in it. It's easy to understand, so let's continue. The column title will come in as a string. First, we'll give it an array, and we'll change each string in the leaf array into a number. And we'll add up all the numbers. For example, a. If it comes, 2a will do this for the second time. First of all, it will be the number of the head to which this string belongs. It will be a hidden plus because the index starts from 0. So, to extract the letter ex of the alphabet, if it is 1 here, it will be from a to g. There will be a response. Next, if you take a closer look at the problem starting from aa is not 27. People just instinctively just 26, and then if z is 26, this studio can fly in and think about it, but why is it a binary number? Just like calculating a decimal, octal, or hexadecimal number, a times 26 to the power of 0, plus a times the 11th place, it would be a times one. Because a number appears in place of a, it represents the mouth, so we can get the number 27. We change each number into such numbers, which is the role of 2 within the map function. That's why ex multiplies gg 3 How many digits did we run to these digits? Index The index with a length of 2 is now 0 days, so we need to change it to 1 0 like this. Therefore, it will represent the multiplier, which is the support force. Subtract the index from the number of the column title and subtract the days. In that case, when the column title is 2 - if the index is 0, then the first digit is 2 - 0. - if the index is 0, then the first digit is 2 - 0. - if the index is 0, then the first digit is 2 - 0. So, the first digit of the 2 is the day. Now, if the second occurrence is like deal, it is 2 - 1. - Since it is one, it will be zero. So, you 2 - 1. - Since it is one, it will be zero. So, you 2 - 1. - Since it is one, it will be zero. So, you can think of it as indicating the index backwards. That's what you need. Then, the first thing that comes in is 26, 1 power, nose digging. It will be the index value represented by this alphabet. So, each one will display that number. 2 After the map function is finished, Liz Let's just add up all the elements with a function. 4 Overwork is important. If you do this, you get an error, but if you look at it, if you do it like this, you have to do 1 There was a mistake. If you submit it, you can check that it passed successfully. If you know binary numbers, it was a very easy problem to solve. That's all for today's video. I'll see you in the next video. Thank you.
Excel Sheet Column Number
excel-sheet-column-number
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnTitle = "A " **Output:** 1 **Example 2:** **Input:** columnTitle = "AB " **Output:** 28 **Example 3:** **Input:** columnTitle = "ZY " **Output:** 701 **Constraints:** * `1 <= columnTitle.length <= 7` * `columnTitle` consists only of uppercase English letters. * `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
null
Math,String
Easy
168,2304
1,594
hey what's up guys today we're doing legal problem number 1594 maximum non-negative product non-negative product non-negative product in a matrix you're given a row times what row x carl's matrix grid initially you're located at the top left corner 0 and each step you can only move right or down in the matrix okay so we're starting from the top left we're moving right down all the way to the bottom right among all possible paths starting from the top left corner zero and ending the bottom corner of rows minus one column is negative one columns minus one find the path with the maximum non-negative product the product of a non-negative product the product of a non-negative product the product of a path is product all integers and the grid cells visit along the path return the maximum non-negative product return the maximum non-negative product return the maximum non-negative product modulo to the nine plus seven if the maximum product is negative return negative one notice that the module is performed after getting the maximum product yes so i have this two-dimensional grid have this two-dimensional grid have this two-dimensional grid we're starting here and we want to end up here and then we're going through we're taking steps and in each step we can either go right or down that's the only possible steps we can take and at the end we'll get to uh negative uh two over here so we'll multiply so negative one times negative two times negative three times negative two that's a possible path negative one times negative two times negative three times negative two that's another possible path we wanna try to find we're going to multiply them along the way and we want to try to find the one that's the maximum product that's also non-negative and if that non-negative and if that non-negative and if that the maximum one is still negative we'll just return a negative one because it's not possible to get the negative product and pi from zero to two so we're trying negative 1 here we have an example where this possible 1 to negative 2 to negative 4 to 1 and that will give us an output of 8. so this one is pretty uh okay it's not that hard the way we're going to do this is like this um at first you want to think of it this way so we have uh either two possible uh approaches we can either go down or we could go right so we can either go down or we can go right so maybe we can uh do this like recursively some kind of um a recursive call where at each step we can either we either go down we go right and we keep track of the cost along the way and by the end of this we'll end up with a possible answer and then we'll say that and then we'll turn it at the end meaning that let's say i go from negative one and then for me i can go either negative two or negative two and so i'll call i'll recursively call like some kind of helper method where i start at this index this point over here and at this point over here as well and i'll keep track of my product along the way and then end of it i'll end up with an answer and every time i get to this corner i'll have a final solution and i'll have a i have a product of that cost of that path and then i'll keep track of the minimum one so for example it'll go from here i have two choices so i'll go also here and then from here i can go to here or here and for me i can go for either from here or here but if you notice now uh when i go from here to here and then to hair as well but i can also go from here to here and here so both times i can end up with this at this point and so from here to the possible solution is going to only be the one best answer right so if i do calculate the best answer from here to the end to the bottom right corner then i can save it right i can say that some way and so from when i go this way i and then from here on i collect the best possible answer and then when i come back here and i start going down this path instead by that time right here i know the best possible cost already because i already went through it when i went this way because i saved it somewhere and so um i can just reuse that so that was the recursively kind of um memoization approach instead we're going to use a dp approach and we're going to do a double for loop instead of having like a helper method that we're going to call recursively and the way we're going to do that is we're going to go through the array like this right and at each step of the way we're going to calculate the minimum cost up to this point and the maximum uh sorry the minimum product up to this point and the maximum product up to each point why are we doing that well first off why was the dp approach gonna work because let's say we did this way and then we went here and then we came here right we're here at this point we already calculated the minimum and the maximum products for the point above for the previous steps meaning the point above the step above or the step whether we came this way so from here now what we're going to do now is we need to find the maximum cost let's say we're going to the end right we need to find the maximum cost of this right a maximum product the maximum path that we could achieve so let's say negative 2 right we have negative 2 over here right so now we know this last answer is a negative number right so this is a good example if to get the maximum product so far then what we need to do is we need to multiply this negative number by the most minimum product behind it so let's just say uh we are negative two now the minimum the most minimum product so far behind it was let's say negative six if we multiply that negative six by negative two it would give us 12 and that would give us a max the maximum product right because every time you multiply a negative to positive the sign would flip right so that's something you need to keep in mind and does this work also if it was positive to get the maximum product we'd also then need to multiply it by the uh most maximum so far right so if it was negative right in this case negative two then we need to apply by the minimum of the most the two previous ones let's just say in this case we know our previous steps which would be six right and that would give us um which would be sorry negative six we'll just say that for example and that would give us 12. and if it was positive then we need to apply the uh maximum of the previous steps and that would be let's just say it's positive six this time and that will also give us 12. so that's something we need to keep in mind that's something i'll explain right here when we get to this step which is going to be a little tricky so the way so we're going to do this now is we're going to have two dp arrays one for the minimums and one for the maximums and then we're going to initialize both their starting points with the uh first uh point which is right over here with g zero or negative one so the minimum so far to be negative one the maximum so we're going to be negative one then we're going to go through the array we have this double foil to go through the array if i is equal to j is equal to zero containing meaning we're skipping the first one else what we're going to do now skip this so far this is going to make sense as soon as we explain this is just to handle the uh corner cases where at the top row or at the first column now what we're going to do now is the maximum of the current product that we're at currently is going to be the maximum it's a little confusing it's going to be the maximum of either this or this and what is this or this it's either going to be what we're currently at multiplied by the maximum of the previous one or currently add multiplied by the minimum of the previous one this is to handle the case where it's negative this is the handle the case where it is positive and same thing for here to find the minimum is going to be the minimum of what we're currently at multiplied by the maximum of what we're at before or the minimum of what we of the minimum of uh the product of a the previous steps right and so this is just the tricky part figuring this out you could also use some if conditions um check if it's negative or not and then handle if the current number is negative not handle that in a certain way of the um kerner is positive or not handled in a certain way but the main thing to notice is that we have four different combinations we have either curry's positive we have cur and we have uh the previous steps right so either we have cur is p or n or and the previous step is either p or n right and so we need to mix and match all those as much as we can so p with p or n with n or p with p we need to have something that handles all that and these will handle all those cases at the end of that we'll grab the final product which is at this uh corner over here if that is still negative we'll turn negative one if it's not then we'll turn the answer modded by the mod that they told us to modded by and that is the final solution i hope you guys enjoyed leave a like comment subscribe and let me know if you have any questions please leave in the comments below i'll try my best to reply to everyone
Maximum Non Negative Product in a Matrix
maximum-non-negative-product-in-a-matrix
You are given a `m x n` matrix `grid`. Initially, you are located at the top-left corner `(0, 0)`, and in each step, you can only **move right or down** in the matrix. Among all possible paths starting from the top-left corner `(0, 0)` and ending in the bottom-right corner `(m - 1, n - 1)`, find the path with the **maximum non-negative product**. The product of a path is the product of all integers in the grid cells visited along the path. Return the _maximum non-negative product **modulo**_ `109 + 7`. _If the maximum product is **negative**, return_ `-1`. Notice that the modulo is performed after getting the maximum product. **Example 1:** **Input:** grid = \[\[-1,-2,-3\],\[-2,-3,-3\],\[-3,-3,-2\]\] **Output:** -1 **Explanation:** It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1. **Example 2:** **Input:** grid = \[\[1,-2,1\],\[1,-2,1\],\[3,-4,1\]\] **Output:** 8 **Explanation:** Maximum non-negative product is shown (1 \* 1 \* -2 \* -4 \* 1 = 8). **Example 3:** **Input:** grid = \[\[1,3\],\[0,-4\]\] **Output:** 0 **Explanation:** Maximum non-negative product is shown (1 \* 0 \* -4 = 0). **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 15` * `-4 <= grid[i][j] <= 4`
null
null
Medium
null
429
hello friends in this video we will solve lead code problem number 429 and array tree level order traversal so first we will understand the problem statement and after that we will approach how to solve this problem and at the end we will see code in javascript and java so the question says that we have given an annihilatory and we need to return level order traversal of its nodes so this is called root and this is called a and all these are children of the root so this is level 0 level 1 level 2 so we need to take all level one in one array list all level two in one error list and all two level in one error list so we can see that one means this one is in one error list this three two four this three to four in one error list and five six is in another list so this is in the two dimensional array list so now let's see approach for this problem so we will use bfs means breadth first search so we will take one queue so and level initial level equal to zero because we are at root so first we will add one into the queue and we will at level zero we have one element so we will track answer it will be our final answer for this first we will remove one from the queue and add it into the our answer and we will iterate through its children's and add into the queue so it's children's three two and four and now level is changed to zero to one so you can change the level so level also we can think of as it represent the index before that we have index 0 so we are added the value 0 so now we will iterate through 3 so in the queue first element is three so we will remove three from this and add into the list at level one after that we have children five and six four three so we will add into the queue five and six now we have two into the list starting means at the start so we will remove from the list and add into the answer at level 1 again we will remove 4 from the queue because it is starting in the queue so we will remove and add into the our answer so it is 4 we had closed because we have travels all level ones here after that at five at the starting so we will remove from the queue and add to it our answer so our level is incremented to two and we will add at our index it is one index so we will add our at two index so it will be five and after that we have six in the starting of the queue so we will remove from this 6 and add it to our answer so this is our final answer for an error list level by level traversing and adding to the answer so how can we track that we need to add one at zero level two at two level we have three elements means three nodes so we can take the size of the queue so first we have size one so we will take one element from the queue and identify the list after that we have three elements so we have queue size of three then we will add three elements at level one after that we have two in the queue size then means two values in the answer at index two so now let's see time and space complexibility for this solution so time complexity will be o of n where n is the number of nodes and each node is getting added to the queue and space complexity will be of n because we are using a queue to track of node we still need to visit the children of that nodes here and also denotes nodes so now let's see solution in javascript so here i am checking if root is equal to null then i am written in the empty answer here i have taken the queue for tracking the root and childs in level order so i had added in the queue level 0 node as root because no root is at level 0 and i have defined result as empty array so here in the while loop i am checking if the length of the queue is greater than 0 means it has nodes in it then i am taking the first note from that queue and after that i am checking its level means at zero level we have root so we are tracking here and up here i am checking if in result we have level at that level we have array or not if it is not then we are initializing the empty array list after that at that level we are pushing that node means level order traversal here and after that here i am adding into the queue and at the end i am returning the result as the answer so now let's see solution in java here i have defined q and for tracking the nodes and after that i have defined error list for returning the answer we will store all nodes at each level so here i am checking if root is null then we are simply returning the empty list here we are adding root in the queue and here in the while loop we are checking if q is empty or not if it is not empty we are taking its size to add into the list so we are titrating to the size of that queue and after that removing from the queue means root we have removed and adding into the our list and we are iterating through its children so adding into the q children means we have visited all the notes at that level at the end we are returning the answer thank you for watching my video please like and subscribe to my channel and click on the bell icon so that you are notified for my future videos
N-ary Tree Level Order Traversal
n-ary-tree-level-order-traversal
Given an n-ary tree, return the _level order_ traversal of its nodes' values. _Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._ **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[\[1\],\[3,2,4\],\[5,6\]\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[\[1\],\[2,3,4,5\],\[6,7,8,9,10\],\[11,12,13\],\[14\]\] **Constraints:** * The height of the n-ary tree is less than or equal to `1000` * The total number of nodes is between `[0, 104]`
null
null
Medium
null
1,640
hi guys welcome to algorithms made easy today we will be going through the question check array formation through concatenation you are given an array of distinct integers and an area of integer array where the integers and pieces are distinct your goal is to form an array by concatenating the array in pieces in any order however you are not allowed to reorder the integers in each array pieces of eye return true if it is possible to form an array from pieces otherwise written false if we see the first example 85 and 85 so we can form this array by using the pieces array and that's why we return true in the second array also we can do the same and so we return true in the third example although the elements in these two arrays are same but according to the condition that we cannot reorder the integers within the pieces of i we are not allowed to reorder these and thus we cannot form the input array arr therefore we return false in example 4 the pieces array can be rearranged such that we can form the array and following the condition that is given to us thus the answer is true however in example 5 the elements differ and thus the answer is false the constraints given to us is that the length of these arrays will be less than or equal to 100 and also the values would be less than or equal to 100. the numbers in both the arrays are going to be distinct always so now let's go ahead and see how we can solve this question now let's take these two examples to find out the conditions that we would need to solve the problem for the first and second array all the numbers in both the list are same thus we can move forward now in the first example the order in which the internal array that is this array 4 and 64 and this 4 and 64 is also in the same order while in this example the order of the elements within the internal arrays of pieces is not same that is 18 comes before in the original array while in pieces it comes after and we know that we are not allowed to rearrange this thus the answer for the first would be true but for the second would be false now with all this in mind we can come up with this thing where we check the indexes when pieces of i contains more than one element in that case we can get an array that cannot be rearranged and that is the case where we will be returning false so now there are two approaches map and array so let's go ahead and code both the approaches and then i'll tell you what is the pros and cons of both the approaches let's first use the map approach we'll take a map and keep all the first elements from this pieces of eye array in it and then in its value we'll keep the whole array so let's go ahead and do that so this will fill our map now we'll iterate over our array let's take an integer i and we'll iterate over array here we check if map contains a key for this element in this array in that case we would check the internal elements from that otherwise we can just return false now here what we do is we take this in an array and we'll iterate over this p array here if n is equals to array of i we do a i plus so that it checks all the pieces in array if this becomes false we can return false now over here this i plus will get executed for one more time than we actually want so we do i minus over here before the loop goes to another i at the end return true because we did not find any case where the condition wasn't satisfied so we return true at the end let's run this code take another variable and we get the right result let's submit this and it got submitted the time complexity for this approach is of n as we are going to iterate over all the elements and the space complexity is also of n as we are using a map now let's go to the another approach that would use an array so let's take an array for indices which would be of length 101 as we are given that this length is going to be 100 in this index array we will be storing the index at which the particular element is occurring so in here we will be storing the index at which it is occurring so if you take this array it would store at index 15 it would store one as it is occurring at first position and at index 88 of this indexes array it would store 2 as it is occurring at the second place now we are going to iterate over the pieces array so for each in for each piece in the pieces array if the index of the 0th element is 0 that means we haven't seen that and so we return false now otherwise what we do is for each element in this piece we will iterate and check whether the index of the this element and its previous element should not differ by more than one so we start from one and we check if this difference is not equal to 1 return false if everything looks fine we return true that's it let's try to run this code and it gives the perfect result let's just submit this and it got submitted so the time complexity for this is also o of n while the space complexity can be said to be o of 1 as we are just using an area of 100 but in that case the previous method would also be the with the space complexity of o of 1 as there also we know that there can be only 100 elements that are going to be stored in the map one thing to be noticed is just because we are given this condition is the reason we can take this array but if you want a generalized approach then the map approach will always work for any given input or any given length of input so that's it for today guys thanks for watching see you in the next one
Check Array Formation Through Concatenation
design-a-file-sharing-system
You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`. Return `true` _if it is possible_ _to form the array_ `arr` _from_ `pieces`. Otherwise, return `false`. **Example 1:** **Input:** arr = \[15,88\], pieces = \[\[88\],\[15\]\] **Output:** true **Explanation:** Concatenate \[15\] then \[88\] **Example 2:** **Input:** arr = \[49,18,16\], pieces = \[\[16,18,49\]\] **Output:** false **Explanation:** Even though the numbers match, we cannot reorder pieces\[0\]. **Example 3:** **Input:** arr = \[91,4,64,78\], pieces = \[\[78\],\[4,64\],\[91\]\] **Output:** true **Explanation:** Concatenate \[91\] then \[4,64\] then \[78\] **Constraints:** * `1 <= pieces.length <= arr.length <= 100` * `sum(pieces[i].length) == arr.length` * `1 <= pieces[i].length <= arr.length` * `1 <= arr[i], pieces[i][j] <= 100` * The integers in `arr` are **distinct**. * The integers in `pieces` are **distinct** (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct).
Try to solve it by keeping for each file chunk, the users who have this chunk. Try to solve it by keeping all the users in the system with their owned chunks, and when you request a chunk, check all users for it.
Hash Table,Design,Heap (Priority Queue),Data Stream
Medium
355
83
Hello friends welcome back to the PM softic Solutions basically in this session we will going to solve lead code problem number 83 remove duplicates from the sorted list so without further delay let's go to the dashboard and try to understand the statement says that given the head of assorted link list delete all duplicates such that each element appears only once return the linked list sorted as well as here you can see the CL definition as well as the function definition is already given so now let's Implement uh this program solution to uh remove duplicates from a sorted link list and return the sorted list we can iterate through the list and remove notes with duplicates value so in previous sessions uh almost two sessions we have already discussed the approach like how we can go through like this problems and how we can solve this type of problems so here I am going to directly implement the code with explanation so you have to watch this session carefully first of all we will going to remove the comment of the list node class so that we can use this class in our program and uh second thing we will going to check if the link list is empty or has only one node so if head is none it means our link list is empty or head. next is none it means our link list has one node then simply we will going to return the head of the link list after this we will going to initialize a pointer to the head of the link list so we will going to create one pointer current and we will going to initilize head Let's uh Traverse the link list so for that I'm going to use while loop file current is not none it means our link list is not empty and current dot next is not none so uh then we will going to check uh if the current node uh has the same value as the next node so for that we will going to use if current do value is equal to current do next. value if duplicates founds then we will going to remove the duplicates no so for that current do next is equal to current dot nextt dot next and uh if duplicate not found then we will going to move next note so for that we will going to use else block else current will simply move to the next node so current will be the current. next and uh finally we will going to return the head of the link list and uh this head will be the modified link list so this is the complete implementation let's run this code you can see all cases has been accepted and passed so let's submit this code also you can see uh this code has been submitted or accepted successfully so that's it for today's session if you have any query regarding this program or anything related to the programming then you have to put your query in the comment section as well as you can also send your query through the Instagram Channel or telegram channel so whenever we will get your query then we will try to resolve your query as soon as possible and uh see you in the next session with a new problem till then keep practicing keep learning
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
390
hey everyone welcome to my channel so in this video i'm going to try to solve this problem do some live coding work at the same time i'm going to follow the general interview steps so first of all let's try to resolve this problem elimination game you have a list of array of all integers in the range of one to end sorted in a strictly increasing order supply the following algorithm array starting from first step is starting from left to right remove the first number and every other number afterwards until you reach the end of the list second step is we repeat the previous step again but this time you from right to left and then the third step is we just keep repeating the steps again alternative way left to right and then right to left until we have just a single number left there so given an integer n return the last number that remains in the array so for example let's say n is equal to 9 then we are going to output 6. so constraint says n is anywhere between 1 to a billion so let's see how to solve this problem so how to solve this problem um one profile solution i can think of is we could just try to mimic the process is like which when i say try to mimic the process is something like we have the real integer array and then we just keep eliminating the numbers from the array or you can actually have like uh a boolean array uh try to mark the number you're going to limit net as false then we are finally we do one pass and find the single number left there but anyway for this brutal solution it is going to be o n uh which is going to be a linear solution so not really efficient so the next thing that comes to mind is um what we could do is we don't really need to actually when we try to mimic the process we don't really need to actually delete the number from the array or mark the number within the array as deleted but instead what we could do is we just keep two or goes one is how many numbers left there so we will keep two variables hat and remain so the remain means how many numbers are there left in the array so if the remaining goes is either one then you just stop there uh and another thing i want to keep is a head the head is um the first number within the array that contains all the numbers left after the step so during the process we try to mimic the process we don't need to actually uh delete the numbers from the array as i said instead we are just going to use some uh intuitive operation to update the head and the remain so in each of the step is going to take one and um because every time you're just eliminating half of a number from the array the runtime is going to be log n because we have logged in with the steps here so this was i think it would be like much more efficient than the previous one so let's go ahead and do some coding work on top of this so as i said we are going to first of all have the head so it is going to start from one and we have the remain as equal to n so and also we are going to have a boolean um so the boolean is going to indicate whether it is from the left or whether it is from the right so at the very beginning it is going to be initialized that's true because we are going to the first pass is from left to right so while the remain is larger than one which means oh we have more than one number left within the array then we are just going to uh do the follow the process try to mimic it so uh the first so it okay so another thing i think i need to keep is a something called stop so i'll explain the step later on so if we are starting from the left for sure we are going to move our head and also if the numbers remain the remaining number if we have even number uh even numbers remaining then we don't really need to uh delete uh the first number from the array but if we have like odd numbers uh out odd numbers uh remain in the array then we will need to actually uh delete the first number so something like if left is uh so if left if we start from the left or if it is not left but it is remain uh multiple 2 as equal to 1 then what we need to do is we need to go ahead and to add a step on top of a head so why do we have the step that is because for each of the paths we are not like escape the equal num equal numbers so for example let's say for the first step you're going to skip one number but for the second um so when i say escaping from escaping one number is something like we just skipped one here but for the second step is it's we are just here we are going to skip two four three four five uh and go all the way to six so every time you're trying to eliminating half of the number so it so which means every step so for each of the process like uh after each iteration we are just going to have the step uh to be like twice as many as before so like for the first one step is equal to one for the second process snap is equal to two for the third process step eight is equal to four so on and so forth so um this is about updating step after that you're going to have remain divided equal to 2 and then step times equal to as well and then the left is equal to not left because uh if left is true you're going to next time you're going to start from the right which means left is good going to be lost for the next time and finally we are going to return had here so that's pretty much it about this piece of code now let's do some testing using this platform okay so it seems to be right let's run some other test cases okay so it seems to be good let's do a submission on top of it cool so everything works well and that's it for the solution and the piece of code if you have any question regarding the solution feel free to leave some comments below if you like this video please help us subscribe to this channel i'll see you next time thanks for watching
Elimination Game
elimination-game
You have a list `arr` of all integers in the range `[1, n]` sorted in a strictly increasing order. Apply the following algorithm on `arr`: * Starting from left to right, remove the first number and every other number afterward until you reach the end of the list. * Repeat the previous step again, but this time from right to left, remove the rightmost number and every other number from the remaining numbers. * Keep repeating the steps again, alternating left to right and right to left, until a single number remains. Given the integer `n`, return _the last number that remains in_ `arr`. **Example 1:** **Input:** n = 9 **Output:** 6 **Explanation:** arr = \[1, 2, 3, 4, 5, 6, 7, 8, 9\] arr = \[2, 4, 6, 8\] arr = \[2, 6\] arr = \[6\] **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 109`
null
Math
Medium
null
1,190
foreign code easily so today we will continue with our stack Series so before moving if you haven't subscribed the channel and you haven't access the playlist access it because we are continuously uh making the videos so in the last video we have seen that how to solve the question for daily temperature using stack so if you really like the video and also like the channel because if it is providing you the important content to you then subscribe it and let's move toward our next question so he here it is given that we have reverse substring between each parenthesis of each pair of parenthesis so here we have a string s and we need to what we need to do here we need to reverse between each pair of paraparentheses so what it means assume that we have a b c d so it is saying that question a reverse between each pair of parentheses so what will be my output will be D C B A and it does not include braces okay it does not include braces this is one this is again so if we have a b c d e f so what will my output so first I will revert this one so it will become d c then if I reverse means the brushes is not required because brushes only indicates that you have to reverse between you have to reverse uh in between characters okay you have to reverse that particular character which is between the parenthesis so yes so reverse f e c d b a yeah I love you let's take as uh I love you okay I love you don't say to anyone okay so this is I love you then what we will do so first I will reverse the love oh we need to reverse that love oh so it will evolve so do I need to write the these parenthesis no it does not require so my simple string right now is i e v o l and U then it is again parenthesis so I need to reverse the between character so it will become e u love I you love I so if it will be you love I then it will give me what it will give you I love you how it will be you then I need to reverse the love then it will be e v o l then it will be I and I need to reverse between because this is parenthesis okay and it will be it will give I love you love I so I hope this is understood now how we will solve so if you have I you love I then just change it let's take a pillar so in the so this is our stack so first I will insert this one then I will insert U and I've been insert again this one I will insert until I do not get the closing desk as I will get the closing brushes I will simply pop until I will not get the first opening brushes so I will pop as a e b o l and this I will insert in one of the list okay now our stack is after popping our strike will remain only this one and this one so when we have popped then I have I need to also write one of the thing that is num of pop because I need to pop I need to remove this parenthesis as well so after moving I have this one then this one now I need to insert I will insert this one to this one so first I will insert until I am not getting until I'm not getting the so first I am inserting until I will not get this one okay if I get this one then I need to pop until I will not get the first opening braces okay then I will append L to stack so first I have this one then I was this one now what my l is Evol so it will be e v o l now I have come at this point because from this one to this one it has been done now I have only I now I have again closing braces okay now the gameplay I will again pop until I will not get the first opening braces so I will pop here I then I will pop l and I will pop o e v so it will be love then I will pop U okay I have popped this one now my stack contain this one so here one of the step I have told you that you need to remove the opening brushes as well so when you do this one then it will be also popped now you will have I love you so I hope this is out clear this is very easy question so let's take one of the let's take first stack then we need to take the I it will give it will go I less than then what I need to do if I if s of I does not equal to the closing places dot app and S of I organize I need to pop until the last element of Stack does not equals to the opening braces so for that I have taken the stack so you can I will take the stack for element okay stack of element so this will be stack of element dot app and here what I need to open here what I need to append uh stack dot pop okay now I have pop so last element is the opening vessel because I'm saying it does not equal so if it does not equal means it is in the it is present so what I need to do here is stack Dot pop okay if I pop then what I need to do I need to append the append our complete list to my stack okay now I just do this one oh then what I need to return simply so I have to return the string so I'm just changing the string to my I'm changing the stack to my string form um if SFI does not equals to this one then okay we need to insert this one if stack okay if it does not equals to this one then Step Up foreign let's try to run because it is not giving me the any error and not giving me the um foreign foreign foreign I will make it big offense solution that is really big of a solution that is that will not going to be because and square solution this is big of n Square so it is bigger of n Square time complexity and bigger of an extra space so I hope you understood guys I will meet in the next video with the next video till then bye and take care and please like the video and subscribe the channel if you really like it thank you
Reverse Substrings Between Each Pair of Parentheses
smallest-common-region
You are given a string `s` that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should **not** contain any brackets. **Example 1:** **Input:** s = "(abcd) " **Output:** "dcba " **Example 2:** **Input:** s = "(u(love)i) " **Output:** "iloveu " **Explanation:** The substring "love " is reversed first, then the whole string is reversed. **Example 3:** **Input:** s = "(ed(et(oc))el) " **Output:** "leetcode " **Explanation:** First, we reverse the substring "oc ", then "etco ", and finally, the whole string. **Constraints:** * `1 <= s.length <= 2000` * `s` only contains lower case English characters and parentheses. * It is guaranteed that all parentheses are balanced.
Try to model the problem as a graph problem. The given graph is a tree. The problem is reduced to finding the lowest common ancestor of two nodes in a tree.
Array,Hash Table,String,Tree,Depth-First Search,Breadth-First Search
Medium
235,236
172
That Agri One My name is Adarsh ​​Mishra And That Agri One My name is Adarsh ​​Mishra And That Agri One My name is Adarsh ​​Mishra And you Urination Ko Dress Today we are going to talk about the provisions of factorial trading scheme on List Ko, this is a very sweet problem and it is a very tricky problem, you people will do whatever simple solution you find. The requirement of the thing is that this problem is going to be fixed by Somi approach, it is going to be very good here and you will not know that the vashikaran that I am giving you will definitely learn something from here, the portion is telling me that you have been given continuation here. And how much do you have to return? Number operating heroine factorial Vishwakarma example, if what is your number, my number is 15, okay then what is factorial? 5.24 second * * * what is factorial? 5.24 second * * * what is factorial? 5.24 second * * * Channel is subscribed, how much do you get in it, tell me here. The idea is that you first turn it on and then after that you tell that if you can take your solution then the login should be done in time, that means see till now we have been seeing that we have some approach and it is square, is n't it us? We advocate it in N logins and then we call it further optimized. It is in N and that's all, we run it and leave it and Admirals, all the solutions get accepted. The big problem is a little of our union, what happens in this? Whatever is there in this, you are requested to accept the anemic solution. It is absolutely right that a good composition has been asked in the interview, either from you or from them. Can you further optimize it? Is it okay then from N. You can do this in the login, only this people will learn that it should be done among the people, okay, then the approach given earlier does not seem to be that straight forward which you will also put and you can easily get into the questions, it is useless, okay. So three * * * useless, okay. So three * * * useless, okay. So three * * * How much sex will go according to Monday's removal, well, there is no 10 in trading, so let us see from here, zero two, a simple, if we drink water, fight in the file, true for into three * * * into three * * * into three * * * 108 in Vansh classes. If the number is subscribed to Ghraan Ghrain Ghraun, then whatever the track number is, run a loot and every time the soil number comes, I will multiply them with each other. Remove the product or if it is gone, keep it somewhere. Is it a vegetable name, meaning site, Twitter. But if we keep it like this, then how can we go, okay, take out some time for sunrise, what do we have to do after this, what is the second task, the account number of Training Shyam Ghrelin is written, okay, so what we have to do is to do two steps up and Whatever is the answer or what will we do after all, we will return the value of our account. Now look at the stars, how much time will it take to do it. We will calculate the factorial. Every number is on that number. We will run the loop by doing the return gift in the token number, so all the numbers from one to 1000. Regarding the time, it means it will take us this time to figure out the difference. Okay, and we will also take almost the end time to clarify the numbers and this and we will If we cut it, then it means we will return the account. Overall, it will take time. On5 Samsung. If you have seen this here also, now you have understood it. Now let's quickly look at the code. What should I do with this? I have been given a number. Regarding the name, I said, I am confused, if my number is zero then return 20, it is simple, just check it here, then yes, it is absolutely necessary, if my number is there, its tutorial comes and goes and there is no less than a hero in it, isn't it? Hero Ton has come, she imposes her first condition, ok, what to do now, what happened to me, to find out the factorial, so how to find out, the name is compact, we have to take courier, its value is one, okay, this is what I will do then, now look, I told you, but If you know it increases then what did we want 121 If we want then three * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * With what did we want 121 If we want then three * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * With what did we want 121 If we want then three * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * With this, I do n't like it at all or not, if it doesn't come, it was even better work. 128 Comment me how many zeros are there in it that my tattoo is coming to 120 so now I have to find out how many more trading are there in it so this method is that every time take out the last digit of this number is ok and after that whatever can be found then If you want the subscribe to divide the appointment of the accused, then do it by putting this in it, subscribe that I do this and after changing this, you comment directly on the same number of numbers, you have used the contra. By using vouchers or you can simply start a program of this channel, there are many options here, now it is just 120 that you have to run the loot, run WhatsApp, what will you do? Subscribe, like, comment, share and share this. Well, this is done and here you have to click on continue, if you want more zero then see if the cases will come out as soon as possible then we are taking maximum time, subscribe here Gyan Appointed, then click on the sub screen here. Any way, if you take out the time, if you do this, you can subscribe like * * * * *, only then I like * * * * *, only then I like * * * * *, only then I can let you all know that this can happen, then share the video, think something, I will do it for you. Patterns Videha Look at the pattern, channelize it, then tell me, like suppose I have three, okay, then there is no control over that, free * * * * no control over that, free * * * * no control over that, free * * * * How much of my answer can be learned and in this we have to give the answer, output. I have to do it, this is not a protest, okay, if we take the karma pipe, then when will my number come, point two, three ** * Vansh, then its point two, three ** * Vansh, then its point two, three ** * Vansh, then its answer will be 120 and there is 10 in it, so we will take my answer one, okay, good. You live like this, we take the tan here, now if we write the tank factorial then 10:00 * 98280 65 * * * * * * Vansh, now the 10:00 * 98280 65 * * * * * * Vansh, now the 10:00 * 98280 65 * * * * * * Vansh, now the value that will come is how many return car festival cases are this, how many will be ours in it? Pass here, that number is 90 A. I will find out this value here and tell you what happens after coming to a hotel by train, what time is the answer in seconds, okay, so 10:00 factorial jewelry, okay, so 10:00 factorial jewelry, okay, so 10:00 factorial jewelry, we are getting it from Google, so that in It is telling 368 that you will get career 6280, some value like this are you ok, how many zeros to 20 will this future give, so just tell me is there anything sensible after seeing this pattern, anything, just all that is 321, ok then My answer is you are ok so it is 54321 so my answer is making and the pattern from tan till the end is full of answer two in it and hence there will be further numbers too no there is some plan answer in calling them too Number and other medical subtitles are not getting far here, I will tell the pattern to the elder. Look, tell me one thing, when does our 0 come? We are sure that if we want to do West ITI, then whenever we give them two numbers. If you comment, then my answer should be zero. If it is zero then only then we will give zero in our overall answer. Think something means that the pen likes any number committee and here if you are getting zero in the house. This means who is responsible for bringing this gang is white and the reason for this is that it is necessary to have a pipe. 5.21 will come, white and the reason for this is that it is necessary to have a pipe. 5.21 will come, white and the reason for this is that it is necessary to have a pipe. 5.21 will come, we will subscribe, 52210 will come, 5124 will come, give the answer, set typing, from knowledge, zero will come, then till I, the pipe is essential, if we find out this. Let's take the first woman * of our entire factorial * how many numbers have come in it, then first woman * of our entire factorial * how many numbers have come in it, then what will happen to us as many numbers and fives have been taken, and if I have this 321 here that I talk about myself, then how many obstacles will there be. And this is where I appointed the battery second here at 5.4 st 121 appointed the battery second here at 5.4 st 121 appointed the battery second here at 5.4 st 121 ok then erase the model tell me how many number from five in this then you have to get 15 in this for your account, here I will say this okay if once you are getting five So this definitely means that all the elements below this will be Cochin, there will be some others, but if any of my numbers is one and that number is divided by five times, what will be the last digit of the number that will come, 90. Do you understand? First you need aloe vera and finally the hero will come like us and so okay here I came to know one thing that here I am getting five once then if I do 5 major with Iqbal then the answer will be 20 that now all these Committee brothers will do day-long Chhath Puja among themselves 1221 Sir, I was feeling strong, day-long Chhath Puja among themselves 1221 Sir, I was feeling strong, day-long Chhath Puja among themselves 1221 Sir, I was feeling strong, you are seeing this is it, isn't it, that arrow or due to some reason, you can get typed that I give you that the number five is the same, we are better than the branch. If I do any proof in case of one tan, then it will have to be written here in a small way 10 * 9828 written here in a small way 10 * 9828 written here in a small way 10 * 9828 2726 * 5243 * * * One Now I asked you 2726 * 5243 * * * One Now I asked you 2726 * 5243 * * * One Now I asked you son Adarsh, tell me how many numbers five send here, then you will say that I will send this here. We have to get a pipe but for 1 minute, here we get this white one. Now you had said that as many numbers as five will be okay, there will be opposition only after landing, then our answer should have been made according to this, it means that you are saying it wrong, now I am suicidal. If you do then our abhinaya never do it with a torch and think, this is 12345, this is seven, eight is nine, tan is okay, what can you write, WiFi, two, nothing, what can you write, three * 31, if you nothing, what can you write, three * 31, if you nothing, what can you write, three * 31, if you can write * * * You can say 272, you can write * * * You can say 272, you can write * * * You can say 272, you can write 7766, you can like 123, you can write pipe people, you can write two into two, you can write three, you can write free, what can you write to oven, if you write this then we have made a series above, it was also factorial. You can take it in this way, I have to write this problem, I am going, yes, I can write, now how many get in it, 12, it means that this funda is fitting right here, there will be two here, so you have not subscribed to the e-channel, two here, so you have not subscribed to the e-channel, two here, so you have not subscribed to the e-channel, now it is ok here, man. He is telling here that the number is five to two, so I will come to the answer key, thank you, reminder to two will come, okay, by the way, tell me one more thing, let us know what are all these numbers, what is A, what is time, what is prime, So, whatever n number is given to you can count on it all its prime factors, whatever number is there, whatever be the number, it is formed by multiplying its prime factors. Okay, it was our time, so how is this? How would this be sexual factorial, how would life be formed, how much time is there in the pipe, power of two into seven, how long is there one here, how much is the power of 10 into three, 1234 3G power point, how different are the tutus, 123456789, it is my birthday. In this way, the prime number is the factor, neither if you do it with such and such power, then concrete will be formed, then give a, as many times as you will come in a plane with the help of failure, I think that if you find it, then it is certain that there will be four at the bottom of the pipe. It will be free, it will be 1, here I will surely get this number, like by taking tips in mobile number, I will get a hero in the village to put it in my hair, so I have approved the number of fame, how many types of numbers will there be, there is nothing in your factorial. You will be strong, it is simple, okay, now the code for this is not written by me, but I am influencing you, well, I am doing this to you, then you will know that some number must have been given, okay, divide it by five, if five In dividing by , the divide it by five, if five In dividing by , the divide it by five, if five In dividing by , the answer is 0r, which means it is a reminder, that is, go to the side and keep doing it, every time that number gets divided, code that value, it is okay and for whatever account it means that many numbers. And there are five inside it and as many numbers as there are five, if the answer goes then how much time did it take for us to login here, which is the question key Radha Kund Barrage solution networks, the condition of dengue among these people and the written complaint were logged in type. Let us explain to you that we have converted their solution into the login solution by using a little mathematics here. You must have understood it completely by now.
Factorial Trailing Zeroes
factorial-trailing-zeroes
Given an integer `n`, return _the number of trailing zeroes in_ `n!`. Note that `n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1`. **Example 1:** **Input:** n = 3 **Output:** 0 **Explanation:** 3! = 6, no trailing zero. **Example 2:** **Input:** n = 5 **Output:** 1 **Explanation:** 5! = 120, one trailing zero. **Example 3:** **Input:** n = 0 **Output:** 0 **Constraints:** * `0 <= n <= 104` **Follow up:** Could you write a solution that works in logarithmic time complexity?
null
Math
Medium
233,809,2222
1,569
hey everybody this is Larry this is me going to do uh the daily problem day 16 of the what month is this June daily challenge hit the like button subscribe and join me on Discord let me know what you think about this Pro and it's a hard one today so sorry that I didn't do it earlier I just got back from a very long trip uh still at um uh element here in Kazakhstan so yeah but anyway let's take a look number of ways to reorder a way to get the same binary search tree okay so uh no drunk today because I'm too tired well I'll get some back so definitely hit that button and go uh with the IG and all this stuff uh yeah on the white tab oh no oh I had the wrong tab then but that's why I was checking give me a second uh okay let me just close out the other type then but that guy caught that one a little bit earlier I was like something's a little bit off okay sorry friends for technical difficulties we'll be right back and I just want the mod stuff because you know my Mud song okay so foreign use the same binary search treat or is this the insertion order Okay so yeah I'm checking n and n is a thousand so we could do an N Square type algorithm um let's see right so what do we get we're given a list of numbers so two one three what does that mean that means that the node that we have now um we will the trio looked like this right so question is hmm so here the thing that you're trying to do is what one is the n is a thousand so it's probably dynamic programming it's just a guess to be honest um and then the second thing is I'm trying to figure out an invariant that we can reconstruct this recursively right so they're really two um hmm oh this is a hard one I don't know I don't have an answer right off the bat to be honest um so let's say you have two right and then what happens and then now two is the root of the tree right and then now we what is the recursion here all the numbers in order on the left and all the numbers in the right are interleaving in the same way right so basically all the orders that are bigger than two have to have the same um order and other numbers bigger than or smaller than two has the same order as well and then it's just interleaving them and I'm checking the distinct frame because I was checking to see because that was the only thing that could go well right so then we set the same thing for example two is that if we have three then yeah if you look at these this is just an interleaving of one and one two the left side and then the right side because that has to be the same and okay I mean so that's fine and then now and then it's recursive right meaning the number of times to do the left and then the number of times to do the right so then now in this case for example we have something like this then this is just the number of left or sorry that's the number right oops right and then left is equal to one two and then now the recursion is how many rays are there right because then the number of ways and then how many ways are there to interleave them um how many ways are there to live in the leaf term I feel like that should be a easy thing but maybe not uh like I mean this part is just recursion so once we my computer is what is my browser I don't know maybe even my Ops my computer is frozen up I don't know if this is recording or you could hear me or whatever uh but basically the idea is damn my computer's clashing I don't know if this is recording what am I doing why is this happening um out there now it's back uh okay sorry friends I was just what happened here hopefully this is recording if not then my apologies okay so yeah so we constantly go okay the numbers of the numbers that are bigger and the numbers of um the an interest of recursion right that part is okay but when it's in the living room meaning that you have okay XX XXX so we have five X's and then now you want to do four of them or three of them right and I guess in this way it is just n or in this case if you have um so this is just should be left plus right choose left or something like this uh maybe plus maybe just plus one mm-hmm mm-hmm mm-hmm uh some someone like this is not quite this let me think about this for a second right because the idea is that okay you have white plus one spaces in between the things right so you have five X's there should be five of them and then you want to choose three of them or sorry left of them right and that should be good yeah because in this case it's not that the items uh interchangeable is that you have no choice in the ordering so it's kind of like uh and replaceable right so this is just commentary stuff and that should give us the answer um yeah I mean that's it I have to be careful about mods and stuff like this but I think that's basically the core idea about solving this problem um yeah I mean this is kind of a tricky one so let's get started then so okay so then here let's say uh count wait I've been away okay I'm just going R right so then now you have left yes right so for x and away left if x is oh no we want R Sub Zero right so current is equal to this number or the root or node or whatever and then here we can just do from the first item on um and then if x is greater than current then we put it to the right otherwise we put it to the left right and then now left count is equal to count of left right count is equal to count of right and then in theory when we have to do some I thought it was going to be dynamic programming around as well but it is still N squared because of you know uh the summation of from one to n type frame but still yeah um and then here uh maybe the bigger is equal to Max of left cow white cow and smaller is equal to Min of this I don't know if this is the cleanest way to write it but that's what I'm going with for today right and then it is bigger choose one uh yeah and of course you have to do this in a mod friendly way right so this is part where you get you could do it with dynamic programming which I would do so yeah so we turn um I don't know comp of bigger plus one smaller maybe and hopefully this is right because I you know maybe I don't know yet right um I think I mean the complexity and stuff should line up so just to yeah um let's see this is old one because we advertise it to DP dynamic programming then the count uh this should be N squared because you can imagine that we just um let's say you have an ordered list and you just keep on taking one of the list and that's going to be n square right um sorry getting weird messages uh so yeah so then now uh was it RNC oh and choose no and choose C I forget to note here and choose R maybe I don't know I don't get that I don't remember the notation and of course that is if you remember your binomial distributions there's just you know n minus 1 or um Plus n minus 1 or minus one I think maybe I messed that up that'd be funny let me just cache this real quick um usually I do the thing about DP but clearly I'm not doing it here um oh yeah if length of R is equal to zero we turn one I forgot the base case oh I also forgot the base case here so yeah if listen ing is this right because this then all can be bigger than n right or did I mess this up huh I usually write it a different way but today I'm tired uh yeah hmm maybe just something like this all right well this is very well I think my combatoric as well uh let me but I want to I mean this is a frame but it doesn't mod right that's why this is wrong but I just want to test this product that's why um before I do it I mean that wasn't going to fix it but okay so two one oh I did know that we had to minus one because we also count the original one so yeah but here um let's see wait let's see maybe I'm off by a little bit let's double check I think the idea is okay but maybe not so then here that you have one and one right so then you have two choose one right so you have one three and then three one so then this should return two right how do I get three our length of zero it is one maybe I'd mix this up foreign maybe the base cases one if it's zero then it should return one right there's no element on hmm if there's no element now we should return zero no still oh then now I can maybe do the minus one thing okay so this is still wrong but ugh this is hard to try to rush through I think the concept is mostly right but maybe not three four five so here you have two so as we said so then now we have Chef six ways right because this is three choose two we have two items maybe I'd oh I'm wrong this is wrong just as well oh God because I assumed that if we have YY then it would just be why and why but actually you can have this as a combination I just messed up what is the end well I don't this is not comatorical maybe um not in this way um really my decisions multiply maybe it's confused no way to do it foreign like we just returned um today my math point is shot like does this work maybe not oh this shouldn't be returning zero then uh hmm why is that returning Zoo oh because this is always just returning one and one um um uh sorry yeah um how do we uh how do I do this hmm so I guess this is just okay so for YouTube why we can put it in no but there has to be an order right so it can the order oh how do I feel into sport the other part is fine but how do I do the math okay so this is wrong I think this is why I kind of did this here so that I don't have to in case this is wrong and it is it's okay save this how many ways are there to do interleaving maybe I don't know okay I mean we could do this recursively right so F of 2 is equal to okay we take one from the X do or we take one of the right and then F of one two which is done now is equal to oh dude right or plus F of 1 I mean I guess we could just write this right it's fine so here then now um maybe I don't have the cell phone in my head we can just write this way so then now we maybe write F Cal of left down right count right and then this is just to recurrence right so huh have count of left right I'm going to skip the caching explanation for today usually I go over memorization and how it works a little bit at least um but if you are under this part then we're just going to skip that for today uh yeah and then as we said what we want is uh if left is equal to zero then we return one if right is equal to zero we also be time one because that means there's only one way left otherwise we can just return F Cal of left minus one right plus Afghan Left Right minus one and we want to mod this yeah hmm why tell me why do um how long am I'm very well maybe this one is instructive because it's going to be true there we go just putting it on stuff trying to figure out what it's doing so okay so one for number if the way is one oh no is this thing so this thing is not quite right this is should be length of love length of right to do the number leave and delivering and then your times this by left Tau times white count for the number of combinations I think uh I'm going to submit it real quick and then if it's right then I'll explain it because if it's wrong then yeah maybe it's too slow stuff that's a little bit slower on this side um Yeah so basically fcam like we said is that we just you know you have a list of length and instead of trying I did try to figure out the formula for a while but instead I was just like okay let's just I mean maybe the people who are you go right or maybe have a better memory than I do maybe they recognize this uh because it seems it feels very familiar but today I am having an off day um but you know when you're able to do stuff with an off day you know that's uh that's not so bad but um but yeah but for this part this is the num this is basically the number of interleaving right and then left count is the number of ways to a number of orderings from the left side number of orderings from the right side um and then you kind of multiply them because that's the number of ways that you can construct that in that order right so that's basically the idea um yeah what's complexity like we said this is going to be N squared just because of the way that this is constructed um this is all also uh n square but it's also advertised right so just N squared plus n Square so this is going to be n Square in total time and in space same thing because of at least how we did the wave thing and I don't know that almost like a pivot type thing right so uh I don't know if you could do it a little bit better than that but yeah um I'm retired sorry friends uh that's all I have for this one so let me know what you think stay good stay healthy to your mental health I'll see y'all later and take care bye
Number of Ways to Reorder Array to Get Same BST
max-dot-product-of-two-subsequences
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from the original array `nums`. * For example, given `nums = [2,1,3]`, we will have 2 as the root, 1 as a left child, and 3 as a right child. The array `[2,3,1]` also yields the same BST but `[3,2,1]` yields a different BST. Return _the number of ways to reorder_ `nums` _such that the BST formed is identical to the original BST formed from_ `nums`. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 1 **Explanation:** We can reorder nums to be \[2,3,1\] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST. **Example 2:** **Input:** nums = \[3,4,5,1,2\] **Output:** 5 **Explanation:** The following 5 arrays will yield the same BST: \[3,1,2,4,5\] \[3,1,4,2,5\] \[3,1,4,5,2\] \[3,4,1,2,5\] \[3,4,1,5,2\] **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 0 **Explanation:** There are no other orderings of nums that will yield the same BST. **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= nums.length` * All integers in `nums` are **distinct**.
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
Array,Dynamic Programming
Hard
null
1,968
O clock is closed, the student has come up with this problem which is last Sunday's electricity don't see problem and related to it and the title of this problem is Affidavit Therewith element is not equal to average of animals problem let's see what it is so it is in this That the first or second number one of you will increase Namaskar of these teachers in which the side will be unique and in the roots inside the face and u12 rearrange elements in every subject every element inside year in which are not equal to the average for these enables so We have to rearrange this exit poll in such a way that send any element, there will be more new elements, there should not be an average of them, support it, I have given two elements, one and two and let's take one more, then edit inside, I have put the number three. If it is there, then let's see by becoming sources, if it is yellow, then it will not be a chat. Let's see separately, what is the address of never 1431, what is the average time till 2, it is in it, so in this way, I will add the debate of Mash 123. The way to do it is that the front and back element beverages around the joint two A fragments in the middle will remain extra, so we also have a way to change the serial, if it is exiting then make sure that some In this way, now this Everest which has happened will not come in the middle, or if it has become an element behind and has moved forward, then 2013 is not an average, so this earring is mango, so we will put some A study like this, let's take an example, there are lumps in it, without that I 12345, whatever you are, but I have given this message on the whole 1234, whatever you do, if this is the element average in the areas around which you worship, then this will have to be changed, okay, let's check, okay, first to later force. So this monk is taking three, that is, this face has to be completely balanced, so for that there can be two, so we can check that if this last one which is increased will come out specially, set three elements, we will one element. We will pick up, we will keep the elements behind it and take the ribbon in front, look at these three elements, if this circle is increasing, it was moved here that it is for sale, and it is a meeting, then we can do a video of how to do a range, A B N Alarm, then whatever lemon I give, the ones next to it will be handed over, they will be folded and the element that is next to it will be completely different, so we have to do it in base English, hi, remind, he will see the limit of coming here. We will check the front and back elements and look at the holidays. If this situation is increasing and decreasing, then we will wait, otherwise we will leave it as it is, this is what we do, then why use the phone, these points, loot, lineage, we take life. Start from, if there is no limit behind then leave it as S, there will be no problem in this, I have to run it near Ajay and Abhishek Bachchan, hello, how are you, do it and what will you do now, set the infinity number and take it here. Root fed from and the people behind it take the treatment available in these texts that are now there, that's why the rising infidelity and do interviews at 1 o'clock or let's slide the sugar yo take it from some current element and take another one from its upcoming For the number because I have to check three numbers or acid increasing is this division if it is then we will turn them over basically all I have to do is whether I have collected the daily point or whether we check that these entries are being made. If there is a degree then let's see first we paste the decreasing, so this access which is cigarette is mandatory i.e. the element behind it, what will be the dedication, i.e. the element behind it, what will be the dedication, i.e. the element behind it, what will be the dedication, this element will be bigger than the one before it, let's chat 220 elements. If he increases it from the front, then it is done by decreasing and what can happen. Episode one was a matter of concern for the test team and the umpire asked in English how will it be increasing which is the back element from green chillies, I get up and will put the end. Because we have to check both the connections and the bar element is smaller than the next one so these two are like this butterfly decreasing and this is done so increasing and condition if it starts then we will just cut it and do this By doing this by doing two by doing this platform will give in this manner, this will be changed, the whole form will go till this element when A that is equal to one, from here till here, first and last next door will be left even because that is necessary. No, it's not theirs, it won't be made anyway, take it as earrings and we will return it to him, but at least he used to make the same mistake once again, so stop commenting. Now this is fake, let's submit it and see if it works. Now if you have understood this a little, then do like and share it with your friends and if you understand anything in this, then do share it in the comments. And if you have not subscribed yet then please subscribe this time. Thank you all Ajay.
Array With Elements Not Equal to Average of Neighbors
maximum-building-height
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`. Return _**any** rearrangement of_ `nums` _that meets the requirements_. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** \[1,2,4,5,3\] **Explanation:** When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5. When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5. When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5. **Example 2:** **Input:** nums = \[6,2,0,9,7\] **Output:** \[9,7,6,2,0\] **Explanation:** When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5. When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5. When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 105`
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
Array,Math
Hard
null
219
So now in this question we will see the contents duplicate, if your problem is easy then let's read it once What is different, whose value is theirs, what is the position of the indices, how small is the difference, it should be equal, okay then. If you see in the first example, one is two, three is one, this one and this one are equal, this condition will be satisfied and what is its position, this is zero, this one is right, which is 3 - 0, this 3 is equal, this one and &lt; is the problem, then our Dictionary, we have to do zero of one in this, it is okay in the dictionary and we do zero of one in this, it is okay in the dictionary and we do zero of one in this, it is okay in the dictionary and we will store it while doing the internet. Okay, if it is already in the dictionary satisfying this condition, initially it is not in the dictionary, then we will do the internet, we will look in the dictionary that it is there. Note if there is right then we will add one. We will go ahead. Okay, so we will directly calculate the difference. Absolute value of P which is current - Have you seen the video? Yes, so we have not yet identified this if it is a value in the dictionary. That value will not be there
Contains Duplicate II
contains-duplicate-ii
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`. **Example 1:** **Input:** nums = \[1,2,3,1\], k = 3 **Output:** true **Example 2:** **Input:** nums = \[1,0,1,1\], k = 1 **Output:** true **Example 3:** **Input:** nums = \[1,2,3,1,2,3\], k = 2 **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `0 <= k <= 105`
null
Array,Hash Table,Sliding Window
Easy
217,220
190
all right let's talk about reverse phase so in this question you're given an integer and it doesn't matter like uh what integer you're giving you just reverse then in this case uh i have a result and i have n right so i will shift left uh for the result but shoot right for the end and how many times 32 times is a little bit so i'm going to shift left by one for result and i'm going to check if the velocity is equal to one if this then i'll add to the result if not i mean zero didn't affect the problem right so uh later on i would just shift right the following shift drive on the end for one bit then i'll just keep doing under until i break my for loop so let's just check so as you see i definitely passed right so let's talk about timing space so um adding the temporary i mean uh integer results shouldn't be much right so i would say oh one and how many times complexity i would say out of 32 which is constant i mean just 32 which is free fast rise and that will be a solution so the complicated is not hard and just think about how you actually reverse right and that would be it
Reverse Bits
reverse-bits
Reverse bits of a given 32 bits unsigned integer. **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`. **Example 1:** **Input:** n = 00000010100101000001111010011100 **Output:** 964176192 (00111001011110000010100101000000) **Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**. **Example 2:** **Input:** n = 11111111111111111111111111111101 **Output:** 3221225471 (10111111111111111111111111111111) **Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**. **Constraints:** * The input must be a **binary string** of length `32` **Follow up:** If this function is called many times, how would you optimize it?
null
Divide and Conquer,Bit Manipulation
Easy
7,191,2238
1,971
1971 find if paths exist in the graph there is a bidirectional graph with n vertices where each vertex is labeled from 0 to n minus 1 inclusive the question says the edges in the graph are represented as a 2d integer array edges as you see in this example this is the edges that is given to us and we have a it's a bi-directional graph between vertex bi-directional graph between vertex bi-directional graph between vertex u and vertex v so what it says here these edges they will build the graph it says zero can c1 so one can zero c zero as well because it's a bi-directional right and then a it's a bi-directional right and then a it's a bi-directional right and then it says one can see two one and two twenty one and two one zero two can see zero can see two right and what is asking us it says we should determine if there is a valid path exist from vertex source to vertex destination so this is the vertex source and this is the vertex destination so we want to see if there is a path between node zero and two as you see here there are two passes because it's a bi-directional two passes because it's a bi-directional two passes because it's a bi-directional right so we can go from zero to two that's the one step past we can also go from zero to one to two and this is a two-step pass so what we are going to a two-step pass so what we are going to a two-step pass so what we are going to do we are going to just return true if the path exists and in the second example as you see we have six nodes and the edges are um like the vertex uh the node zero can c1 and one can see zero this is the uh path between zero and one and then between zero and two and then between three and five and four and three right and these are bar directions so if i three can see five can see three as well so we wanna see if node zero can see node five as you can see it is not possible but how should we do that we should go through the different passes that we have here and see if it is possible for node 0 to see note 5. when i talk about passes and talk about graph and if this question is asking us to traverse the graph uh like bfs and dfs are the best solution what we are going to do we are going to use uh dfs here to solve this problem and the question is saying uh we at least we are going to have at least one node so we don't need to deal with that so just for simplicity what i'm going to do i'm going to say if number of nodes that we have is equal to one so definitely that note can see itself right or if the source and destination that the question is asking us to check that they can see each other if they already exist in the edges so we don't need to go through anything right we can just return true and that would be very easy and done right so if the source and destination that if the question was asking okay if zero can see one so we can see zero can c1 so we don't need to go through dfs or anything complicated we just like return um true here and that would be easy and now we are what we are going to do we need to build a hashmap to um make the key as the source node and the uh other nodes like that key in that node can see as the values so what i mean by that so for this example we are going to have a key zero and we are going to have uh the values of one and two because zero can see one and two and then we are going to have key one and then we are going to have value zero one can only see zero uh i will write down the hashmap code and i will print it out so you can see how it would look like and the reason that we are using hashmap is the lookup in hashmap is constant so it will help with the like um better time complexity so for a hashmap what i'm going to do i'm going to use collections default dictionary so the reason is the default dictionary i can put a default stick sorry dictionary and i can put a list in it so it's going to be very easy so like it knows the values are going to be a list with one item or more right so then i'm going to say for uh like the vertex uh like vertex that we have here for vertex u and v that we have in the edges what i'm going to do i'm going to say hashmap for the vertex u dot append v right so let me print this out it's not this is not done i'm just going to do that to show you how it would look like okay default uh dictionary collections i forgot to put s here collections the foundation so this is the easy one i'm gonna use this because it's a better example let's say here i'm gonna put six here and we're going to see right okay here let's uh print this out and hashmap so you would see how it's going to look like this is what we are going to get for this example just for the presentation purpose illustration purpose i'm going to put this here so as you see here for this example the dictionary is going to be 0 can see one and two three can see five can see four can see three right this is what we are going to use um to uh find uh the path and we are going to use dfs for using dfs i'm going to write a dfs function so i can recall that and we are going to call that recursively because for some nodes we have two passes after going through this path we might find the destination or we might not and we need to um traverse this as well and see if we can find the path using the second connection so what i'm going to do i'm going to say the hashmap is given to you the source is given to you the destination is given to you and also i'm going to have a set that i'm going to store the scene nodes in it the reason it's sometimes we have cycles and if i don't put scene we might get stuck in a loop over and over seeing a node and we get the time exceeded limit error so i'm going to have this scene here what i'm going to do i'm going to say if the source and destination if they are equal right so it means we have seen the node that we are looking for right and also we are going to check if the source that i'm checking if it is in the scene so it means we are stuck in a loop and we should return false and it should be end of the story and then what i'm going to do i'm going to and if it is not one of these two cases i'm going to add the source node in the scene set right the reason that i'm using set is uh the time complexity for uh set is lookup it's constant and then i'm going to stay for the keys that we have in the hash map for the source like the keys like one time we go for one and another time we go for two for cases like these it's gonna be very helpful and then i'm going to call this function recursively and this time hashmap and instead of the source i'm going to give it the key and the destination that we are looking for and the scene set that we know what nodes we have checked so first and then we are going to return true if this if condition is true and um what i'm going to do i need to call this function with an empty hashmap with the source that i'm looking for with the destination that i'm looking for and set empty set it will start like this so let's run this code and as you see it works perfectly so the space complexity for this is uh n because we have the hashmap and we are using um recursive function thank you
Find if Path Exists in Graph
incremental-memory-leak
There is a **bi-directional** graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (**inclusive**). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by **at most one** edge, and no vertex has an edge to itself. You want to determine if there is a **valid path** that exists from vertex `source` to vertex `destination`. Given `edges` and the integers `n`, `source`, and `destination`, return `true` _if there is a **valid path** from_ `source` _to_ `destination`_, or_ `false` _otherwise__._ **Example 1:** **Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[2,0\]\], source = 0, destination = 2 **Output:** true **Explanation:** There are two paths from vertex 0 to vertex 2: - 0 -> 1 -> 2 - 0 -> 2 **Example 2:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[3,5\],\[5,4\],\[4,3\]\], source = 0, destination = 5 **Output:** false **Explanation:** There is no path from vertex 0 to vertex 5. **Constraints:** * `1 <= n <= 2 * 105` * `0 <= edges.length <= 2 * 105` * `edges[i].length == 2` * `0 <= ui, vi <= n - 1` * `ui != vi` * `0 <= source, destination <= n - 1` * There are no duplicate edges. * There are no self edges.
What is the upper bound for the number of seconds? Simulate the process of allocating memory.
Simulation
Medium
null
258
hey everybody welcome back and today we'll be doing another lead code two five eight add digits this is an easy one given integer now repeatedly add all its stitches until the result has only one digit and return it so this is an easy one because um this the process the algorithms which we can use to solve this problem is everybody knows that is just taking the modulo and then taking the modular moduloid by 10 and then adding that value in our current you can say a current variable and then just pop off the last element so that's it we can do this by that algorithm you can say but there is an interesting solution to it so I will be doing it by that so let me explain if a number is equal to 1 then obvious a number is equal to zero then obviously it will go into it we will be returning zero so like this zero returning will be zero so whenever a number is divisible by you can say 9 it is going to return nine you can check 27 is divisible by 9 it is going to return 9 2 plus 7 is 9. and the 81 it is divisible by 9 it is going to return 9. it's 16 63 60 um 63 36 and you know the table of 9. so and whenever a number is not divisible by 9 it is going to return an integer that is less than 9 which is I think self-explanatory by so for example we self-explanatory by so for example we self-explanatory by so for example we have 2 and 7 but they want us to do is to sum them all up until it is until it becomes a single digit for example if we add these three number you will get 10 and if we add these two digits uh we will get one and look what will happen now if we take a model U of this number by nine but we will be getting one so that's it I guess so let's code it down now and if nums is equal num is equal to 0 we will just return 0. in Alice case if num is divisible by you can say 9 and 9 then it is going to return 9. turn 9. and in the else case we will just return num model by 9. and that's it this was the whole code
Add Digits
add-digits
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it. **Example 1:** **Input:** num = 38 **Output:** 2 **Explanation:** The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. **Example 2:** **Input:** num = 0 **Output:** 0 **Constraints:** * `0 <= num <= 231 - 1` **Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
Math,Simulation,Number Theory
Easy
202,1082,2076,2264
399
hey everyone welcome back and let's write some more neat code today so today let's solve the problem evaluate Division I don't know if I'm getting Dumber or these Elite code problem descriptions are getting a lot worse well I guess this is one of the earlier problems but I'm just going to skip straight to the example because it's a lot easier to understand it that way we're given a list of equations where the equations could be given like this and keep in mind that these are strings so A and B are going to be strings and what one of these sub arrays represents is a divided by B so that's what this equation is similar B divided by C so every equation is going to be in this form with some numerator and some denominator we're also given a second array of the same size which actually tells us the result of each of these equations so in this case a divided by B we can see down here it's kind of hard to tell but the value is going to be 2 so a divided by B is going to be 2. B divided by C is going to be three cool now we are also given a list of queries so that's what green is going to represent and those queries are going to be in similar shape as the equation so it's going to be a sub list in this case one of the queries is going to be a c so what we want is to know the result of a divided by C now it's not necessarily going to be true that we'll be able to determine it and if we can't determine it we have to put a negative 1 as the result but if we can determine it then we have to put the value of this equation like what it evaluates to and then we have to build a output array so for each one of these queries we'd have some output value now in this case a divided by C can we determine it well let's not even think about code for a second let's just try to look at like the math hopefully your algebra skills are good enough to be able to evaluate this a divided by B is equal to 2 and B divided by C is equal to 3 well take a look we can kind of multiply these two together and the B over here is going to cancel out the b over here and then we're going to end up with a divided by C and multiplying two and three together like that's the value of these two equations so 2 times 3 is going to be 6. so we were able to determine at this time I have no idea how we would code that up yet but we were able to get the result of this query which is six and that's what they have in the output as well now a quick Edge case worth mentioning is what if some of these equations are the queries like something like this a divided by E well we weren't even given an e character in the input so it's definitely not possible to evaluate this so for sure we would put a negative 1 in the output and that's what they do for this one it's over here another Edge case and this one I think is kind of dumb I really don't understand this take a look at this over here x so we don't know what x is that's perfectly fine but x divided by X should probably be one right unless we have some kind of divide by zero which I believe they mention will never really be the k and we won't have any contradiction so we don't have to worry about that thankfully you would think this would evaluate to positive one but I guess in this case it doesn't over here x divided by X gets us a negative one you can't really see it anymore but it does give you a negative one or at least that's the expected result that's kind of stupid in my opinion but okay we just have to account for that the first thing I personally tried was maybe we can just solve for every single variable and then it'll be pretty easy to know the result of every query because they literally are just a divided by you know some other variable that's the form of every single query my math skills are sharp enough to recognize that we actually can't do that in this case we have in this case two equations but we have three variables a b c so we simply do not have enough equations unique equations to be able to determine the value of a and b it's ambiguous and if you don't believe me let me prove it to you let's just say hypothetically the value of a is two then what must be the value of B to get an output of two probably one okay let's say a is two B is one okay then we get a one over here then what's going to be the value of C probably a fraction in this case one third one divided by one-third is going third one divided by one-third is going third one divided by one-third is going to give us three in the output this is one way of solving this equation you can tell this math definitely works out but now let me change it up let me transform a over here to now be a 4 and transform this to be a two and so that means it's a 2 over here as well and then that means for this to equal three we have to make this two-thirds this is another way make this two-thirds this is another way make this two-thirds this is another way that the equations do work out so what you find is we can't actually determine the value of each variable and clearly this is a very simple example but we could have had a ton more equations and at this point if I gave you this problem in an interview I would definitely expect you to need a hint because it's not very intuitive how to solve this problem but actually it turns out we can transform these equations in a graph representation which will allow us to solve this problem notice how when we have a query like a divided by C we start with whatever we can we start with maybe a divided by B and at this point we need a way to cancel this B so we would look for all the other spots in our list of equations where B is in the numerator spot because then we can get a fraction in this form something in the Dominator who cares it's an X but we can get something in this form where we cancel out like this and we have a divided by X we don't necessarily know we'll ever be able to figure out what a divided by C is but this is our best bet we have to sort of cancel out the denominator because if we multiply this by something else like If I multiply this by D divided by E we're not getting any closer to this are we that's a little bit of the intuition and also notice that when we do this B divided by C we are multiplying the values together so this is a little bit of the intuition of why we want to map every single numerator to all of the possible denominators that it has in any of these list of equations and it could have multiple of course in this case our graph kind of looks like this shape a points to b points to C now it could have been possible that a you know points to something else like an X in this case though our graph is pretty simple so let's just try to understand this itself can I ask you if we start at a and Traverse the graph and end up getting to B what does that represent doesn't that kind of look similar to this like actually multiplying the equations together this is kind of like a divided by B this is B divided by C and what we were doing with these values is trying to multiply them so wouldn't it be kind of good to put the edges as the value of each equation so a divided by B is equal to 2 B divided by C is equal to 3 then the way we formulated the problem a path from a to c multiplying all of the edges together must mean that a divided by C is equal to the multiplication of the edges it's equal to 6 because of the way that we formulated it I know this is kind of a crazy idea that really isn't common in data structures and algorithms you probably haven't seen it before so it might take you a second to really understand it but it's pretty simple what's actually going on here now another question you might have is what if we are going in reverse order C going to be going to a like that's a perfectly valid query what if they instead ask C divided by a well the way I formulated this was a little bit naive now we kind of realize numerators point to denominators sure but shouldn't denominators also point to the numerators as well can't we kind of do this in reverse order okay can't I also say this equation C divided by B which is you know the reverse of this multiplied by B divided by a which is the reverse of this isn't that perfectly valid as well that gives us C divided by a yeah I don't see any reason we can't do that but if we try to multiply the edges going in reverse order we still end up with six so how can it be possible that a divided by C equals 6 and C divided by a equals six I'm pretty sure that's a contradiction and it is and that's when you realize when we go in the reverse direction we should take the inverse of these values because that's exactly what these are the inverses of each other if you don't remember what an inverse is it's basically one divided by this number so what we essentially learned here is that our graph is going to be directed The Edge going in this direction is not going to have the same weight as the edge going in the other direction this one will have a weight of one divided by three and this one will have a weight of 1 divided by 2. so this is basically how you need to formulate the problem in order to solve it is it intuitive not for me but I hope it's starting to make sense for you and I'm a big math fan so I thought this was one of my favorite problems I ever solved okay so knowing all of that how are we actually going to solve the problem well first we're of course gonna have to build this graph essentially just building an adjacency list using these as our edges and we are given the values as well those are going to be the weights of each Edge and we're going to build like the reverse edges as well and then for every single query we are kind of going to do it a Brute Force approach which thankfully is good enough for this problem because it is a medium so I think that should be perfectly fine and by Brute Force I mean on the graph for every single query we're either going to run a depth first search or a breadth first search so potentially traversing the entire graph I believe the time complexity is going to be n for the number of queries multiplied by the size of the graph which I believe is e plus V where edges plus vertices to simplify this I think just having e for like the length of the equations is probably sufficient n times e where this is the number of queries space complexity should just be the size of the graph which is going to be V plus e so now let's go ahead and code this up like I said first step is going to be building the graph in Python what I'm going to do is create a hashmap questions.default is create a hashmap questions.default is create a hashmap questions.default dict where the default value is going to be a list because what we know is we're going to map every numerator or just every number a such that it's mapped to a list of pairs where each pair is going to be B where B is just a variable and the second value is going to be the evaluation of a divided by B if this doesn't make sense don't worry it'll probably make sense as I actually build this so what we're going to do is iterate through every equation but in Python we can do it like this for I equation in enumerate the list of equations reason I'm using enumerate is we not only get the value from equations which is here but we also get the index as well which just saves us a little bit of boiler play and then we can unpack the variables from the equation because we do know it's a pair of variables we know we want to build directed edges so from a we're going to append the neighbor B and what is the evaluation of a divided by B well thankfully that's going to be stored in values at index I you can see why we needed the index I now and we also know we want to do the same thing going in the opposite direction so we might just say B divided by a but there's a bug remember it's not going to have the exact same weight so we want to take the inverse of this so we say 1 divided by that in Python one slash means decimal division which is exactly what we want in this case if you're using like Java I think that'll be integer division so you want to keep that in mind but next we just want to run every query and get the result of it we can do that with a DFS or a BFS I'm going to do BFS the main reason is it's easier to handle cycle detection in and it's possible that our graph could have a cycle so BFS just makes it a little bit easier for us what I'm going to be passing into our BFS is going to be the source and the Target and what that's going to be in this case is if we were given a query like a divided by B then the source is a and we want to find a path starting from a getting to B and once we get to B we just want to multiply the weight of all those edges and return that so that's what this is going to be doing so before I even implement it I like to show you how I'm actually going to be using this so for every query in our list of queries we want to call BFS passing in Q at index 0 as the source and Q at index 1 as the Target and we can use this to build an array but in Python we have a nicer syntax called list comprehension so we can build a list just like this by putting a for Loop inside of it so for every query this is the value that we want to add to the list and it will execute in order as well so this is the result that we're going to end up returning and now all we have to do is actually implement the BFS and before I forget I want to say that remember if any of the source or the destination is not in our list of equations which means it's not in the adjacency list then we want to return negative one immediately even if we're given something where the source and the target are equal like I said I think that's kind of weird x divided by X should always be 1 but in this case they want it to be negative one I guess so if source is not in the adjacency list or Target is not in the adjacency list we return negative one now we have our pretty cookie cutter breadth first search where we're going to need a q and a hash set and I'm going to use a deck and a hash set like this we initialize our queue just starting at the source but I'm actually going to also add a second value because remember we do want to keep track of the multiplication of all the edges but since we're not doing this in like a depth first search way where we might go to A to B to C Etc we're doing it layer by layer we could start at a and then the next layer could be something like a and d and then the next layer could be something like c and e so we want to simultaneously keep track of the multiplication of these edges and these edges so instead of having a bunch of variables to do that we can just use the Q itself every time we add a value from our graph to the Q we're not just going to add the value we're going to add the total multiplication of the edges so far what do you think would be a good starting value for our source node to have for the like multiplication probably just one because it's a neutral value any value multiplied by one will end up being that value and I also like to immediately add to the hash set the source node and then we want to do a BFFs so while the Q you is not empty we want to pop from the cube we're going to append to the right so we want to pop from the left and when we pop we end up getting the node and the weight I'm going to store that in N for node W for the weight and you might think let's immediately just start going through the Neighbors in the adjacency list of the node n but remember before we do that we're looking for the Target if we find the target there's no point in continuing we're not doing this for fun we're looking for the Target so if we get to a point where n is equal to the Target then we can go ahead and return what should we return weren't we trying to multiply all of the weights well yeah but remember when we append to the queue we're going to be appending the multiplication up until this node so w is already the value we want to return so just go ahead and return it here okay we have that handled and we know actually this might not always execute so to be safe let's put a negative one over here it's possible that both the nodes exist in the graph but there just happens to not be a path connecting them in that case we would return negative one but now as we go through every neighbor of this node we remember that we're not just going through the neighbor we're going through the pair which is the neighbor and the weight so the second parameter is going to be wait well not parameter it's a variable and I know this can be slightly confusing because we have two variables referring to the weight but now for this neighbor we want to Traverse the BFS from this node as well but only if it's not been visited so we say for neighbor not in visit if neighbor is not invisit then we can go ahead and append to the queue this neighbor and the new weight how do we get the weight do we just add the weight of this node that's not enough because that's only the weight connecting A and B do we just add the W value nope that's only the multiplication of the nodes before we reached this node we actually want to multiply them together W Times weight and we also before we forget want to make sure this node is marked visited so I believe that is the entire code let me go ahead and run this to make sure that it works okay it's always the simplest things you mess up on I think I forgot to add dict over here this is a default dict and also when I append to a list we're appending a pair but here I didn't really do that so I want to wrap this in a list and this one as well okay now let's run this to make sure that it works and as you can see yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a interviews check out neatco.io it has a interviews check out neatco.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon
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
1,941
uh hello everyone so today we are going to solve this lead code easy tagged problem check if all characters have equal number of occurrences given a string as return true if s is a good string or false otherwise a string s is good if all the characters that appear in s have the same number of occurrences that is the same frequency so here if a string is good then we have to return true and if it is not we have to return false if every character in the string have the same number of occurrences or the same frequency then the string is to be considered good and not good otherwise so what we are going to do we will uh just take an hash map we will count or all the occurrences of each character in the string then we will again Traverse the hash map and see if all the characters have the same number of occurrences or not if they have the same number of occurrences then we return true and if not then we return false so let's consider an unordered map of int sorry of care comma hint let's name this map as car map now we will iterate over the string and count the character occurrences of each character and store it in the hash mark now what we'll do we'll just find out the occurrence of one character let's name that aggress as frequency um CAD map dot begin arrows second this is the frequency of a particular character now we will iterate over the hash map and check if all the characters are having the same frequency or not so for Auto in CAD map if x dot second is not equal to frequency we'll return false and if it is not a turning Falls in or over all the iterations then we will just return true let's run this code yeah it's working fine let's submit it's successfully submitted so
Check if All Characters Have Equal Number of Occurrences
minimum-number-of-operations-to-make-string-sorted
Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_. A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency). **Example 1:** **Input:** s = "abacbc " **Output:** true **Explanation:** The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s. **Example 2:** **Input:** s = "aaabb " **Output:** false **Explanation:** The characters that appear in s are 'a' and 'b'. 'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times. **Constraints:** * `1 <= s.length <= 1000` * `s` consists of lowercase English letters.
Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately
Math,String,Combinatorics
Hard
null
1,029
hi everyone this is ravi and again the lead code problem every s people a company is planning to interview the cost of flying eighth person to city a is okay or a two dimensional cost and the cost of flying eighth percent to city b is the same uh okay return the minimum cost to fly every person to uh to a city such that exactly young people arrive in each city uh foreign 150 plus 17 plus one but it is too much it's too high so uh but it can actually solution in ardena uh maybe like a maximum value at 200 150. and um under sort money class so minus 170 the company value minus 10 and 350. in the ranking system uh meaning uh say 170 responsibility which is in the value 30 and 200 so uh a minus 170 ns and the person uh be confirming abreena it will cost you more so definitely you should send him for a city so in case negative number are the chebrina we will always send that person for city a so uh okay opposition so other number final custody increase a tb can cost 50. so there's a lot money number written uh that will be the minimum charges it's good for this problem initially like ranking system upper on the short bunny alert values in java we can easily make it use me make use of uh sort method with the lambda function so arrays dot sort and first will be the array parts and here is our lambda function a b so initially it will be of zero and d of one uh then enough first two elements 0 minus b of 1 so once everything is done we need to return the minimum cost so we'll create a variable for it minimum cost is equal to 0 50 by two okay so finally let's uh calculate our minimum cost for n tie is equal to zero i less than cos dot length i plus and then inside if i is less than n because psi starts from zero will start from less than the zoning of equal to and either so this will be i and this will be zeroth city column okay else min cost plus equal to costs of i and one okay finally we should return our value return main cost okay let's submit this program bye
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
416
all right this lead code question is called partition equals subset sum it says given a non-empty array containing only given a non-empty array containing only given a non-empty array containing only positive integers find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal so for example 1 the output would be true because we can split it up into one subset that would have 1 5 &amp; 5 into one subset that would have 1 5 &amp; 5 into one subset that would have 1 5 &amp; 5 and that would equal 11 and the other subset would be just the number 11 so for example 2 the result would be false because we can't split it up in a way where the two subsets have an equal value and we'll do this using dynamic programming all right let's do a quick example that's going to help us later let's say we have the numbers 1 2 &amp; 3 let's say we have the numbers 1 2 &amp; 3 let's say we have the numbers 1 2 &amp; 3 what are the total numbers we can come up with by adding up these numbers in different ways like I mentioned earlier we can use dynamic programming to help us solve this so what we can do is we can create a new array and this array will represent the possible totals when we add up the numbers 1 2 &amp; 3 we add up the numbers 1 2 &amp; 3 we add up the numbers 1 2 &amp; 3 different ways all right so before we begin let's do this alright so to reiterate these numbers are answering the question can we come up with these results when using the numbers 1 2 &amp; 3 results when using the numbers 1 2 &amp; 3 results when using the numbers 1 2 &amp; 3 and this is dynamic programming so we need a base case so the base case is 0 we basically just pretend that there are no numbers so with no numbers can you come up with the total 0 yes you can and by the way any time we see a T that means true meaning we can come up with that total and if we have F that means false meaning we cannot come up with that number all right so let's begin with only the number 1 can we come up with the total one yes we can so we'll change this false to a true all right and since we only had one number there we can only have one result so we'll move on so now with the numbers 1 &amp; 2 which totals can we come up with 1 &amp; 2 which totals can we come up with 1 &amp; 2 which totals can we come up with well if we only had the number 2 we can come up with a total of 2 but remember we also have the number 1 so with 1 &amp; 2 we can come up with a so with 1 &amp; 2 we can come up with a so with 1 &amp; 2 we can come up with a number 3 so we'll change the number 3 to true are there any other totals we can come up with the numbers 1 &amp; 2 no come up with the numbers 1 &amp; 2 no come up with the numbers 1 &amp; 2 no so we move on so now we're at the number 3 with the number 3 how many totals couldn't we come up with well if we only had the number 3 we can come up with the number 3 but that's already true how about with a number is 3 &amp; 2 about with a number is 3 &amp; 2 about with a number is 3 &amp; 2 well 3 plus 2 is 5 so we can come up with the number 5 so we'll change that to it true how about with the numbers 3 &amp; 1 &amp; 1 &amp; 1 well 3 &amp; 1 will give us 4 so we'll well 3 &amp; 1 will give us 4 so we'll well 3 &amp; 1 will give us 4 so we'll change for to true is there anything else yep the number is 1 2 &amp; 3 1 2 &amp; 3 would yep the number is 1 2 &amp; 3 1 2 &amp; 3 would yep the number is 1 2 &amp; 3 1 2 &amp; 3 would give us the number 6 so we'll change that also to a true so with that we can say that with the numbers 1 2 &amp; 3 we can say that with the numbers 1 2 &amp; 3 we can say that with the numbers 1 2 &amp; 3 we can come up with again a base case which is 0 but also the total is 1 2 3 4 5 &amp; 6 0 but also the total is 1 2 3 4 5 &amp; 6 0 but also the total is 1 2 3 4 5 &amp; 6 and you can look all the way to the right there's no way we can come up with the total 7 and of course that also means that anything greater than 7 we also cannot come up with because we've already used every number in our original list all right so let's get to the question at hand it's asking if we can break down an array in such a way where the two subsets are equal so for this example if we broke it down like this 2 4 1 5 the two subsets are equal because they add up to the same thing they add up to the number six well what is the number six if we just look at all the numbers in the array one two four and five and add them up together they add up to 12 so in order to come up with equal subsets the subsets would have to equal half of the total of the numbers in the array so once again the total is 12 so the question is whether we can come up with two subsets that both equal six so knowing that what else can we say we can say that if the array totals an odd number then we cannot come up with two equal subsets so we can add up all the numbers in the array if the number is an odd number we can immediately return false all right so using what we learned in the last video we can do this we can create a new array which represents all of the possible combinations of the numbers in our original array except it's not a total of all the possible outcomes and that's because it doesn't need to be if we needed all of the possible outcomes we'd need an array of 0 through 12 because 1 plus 2 plus 4 plus 5 is 12 but that's not what we need all we actually have to try to find out is if any of the possible combinations add up to half of the total sum so let's say we had the numbers 1 2 &amp; 3 if any of say we had the numbers 1 2 &amp; 3 if any of say we had the numbers 1 2 &amp; 3 if any of the combinations added up to 3 we would know that the other subset also equals 3 in this case we only have to see if any of the combination sums add up to 6 because then we know that the other subset also equals 6 so really we only care if this ever turns to true meaning if any of the combination sums ever equal 6 all right so let's begin we start with the number 1 and just to make it easier visually let's cross out the rest of the numbers we're not actually doing anything in the code we're just crossing them out to remind us that we haven't gotten to those numbers yet all right so what we're gonna do is we're going to see if we can get to any of these combination sums with the numbers that we have and we'll do that by starting at the rightmost index of the array and checking one by one all of the target combination sums and see if we can arrive at these combination sums using our numbers in the original array and there's a very good reason that we're moving right to left instead of left to right and I'll show you that soon so our target combination sum is the number six so using the number one can we arrive at the number six the answer is obviously no but how else could we have gotten to the number six using the number one if we only had the number one we couldn't but what if we'd previously come up with the number five in another combination some that would have given us the six we need but we know we haven't come up with the number five yet because we only have the number one the number five though we'll say is the complement we'll say is the number we would need to add on to our current number to get to our target number so we'll actually write that as a rule up here do we have the compliment somewhere so like we said the compliment would be five but that's also false so we cannot arrive at the number six all right let's move down to the next number using the number one can we get the number five no unless we've already come up with the combination sum for the compliment which again is the number four because 1 plus four would equal 5 but we have not seen the number four hence why we still have a false here so no we cannot come up with a number five yet so let's move down to our next number the number four so what we should do actually is to first check whether our target number in this case the number four is a ready true if it's already true we can just move down to the next number if it's not already true then we can check to see if we have the complement so no it's not already true and no we don't have the complement so we just move down to the next number same questions is it true already no do we have the complement No so move down one next can we arrive at the number two how would we know well if it's already true which it's not or if the complement is true which it's not so we finally move down here now can we arrive at the number one is it already true no but can we arrive at it using the complement well yes because we know that we're on the number one and that we have its complement of 0 so 1 plus 0 gives us the one we need so we'll say for the number 1 yes we can come up with it using the number we have and its complement all right so we're at the number 1 and we just checked the target value of 1 usually we'd move down to the next number but there's no reason to because we know that there's no way that we can arrive at the number zero using only the number one so at this point we should move on to the number two but before we do that I'll show you exactly why we're moving from right to left instead of left to right and to do that let us reset all of the values real quick to how they originally were okay so the values are reset and now we're gonna pretend that we're gonna move from left to right instead of right to left so we'll ask the same questions that we asked before we're on the number 1 can we arrive at the target value 1 first we check to see if it's already true no it's not but now we check to see if we can get to it through its complement so we have the number 1 and we have the complement 0 1 plus 0 gives us the one we need so now we can change this false to it true and while we're doing this pay attention to the number 1 so we've already visited the number 1 so now let's move on to the next number let's just take a step back if we only have the number 1 could we arrive at the number 2 of course not right but if we try to apply the rules that we've set forth so far what would happen we would look at the number 2 and say is it already true it's not but now we look at our complement rule our complement is right here it's the number 1 and it is true so we might be tempted to say that since the complement is true that our number would be true but we know that's obviously not right what's happening here is that we're accidentally counting the number 1 twice once as the target value and once as the complement so let's go over that again kind of in slow motion we started here and we said yes we could arrive at the number 1 then we went to the next one and we looked at two's complement which is the number 1 saying yes since it has a complement to is also a true but that's not the case we counted the number one here and then we accidentally counted it again here why does going from right to left avoid that again pay attention to the number one will go by the rules that we've set forth already so here no notice that we're not actually checking anything with the number one at this point the number we're focusing on is the number two at this point the number two isn't true already and it's complement is false so now we'll move over to the number one since the number one has a complement that's true now we can make the number one true so you see how that worked going from right to left we only counted the number one once but going from left to right we would have counted it twice all right so let's reset this in order to move on to the number two let's cross these out just to show that we haven't gotten to them yet and we've just set up the complement correctly since if we have two already to get to the number six the complement would be four alright so let's begin again we're at the number six is it true already no can we get the number six using two's complement which is four no we can't so we move down it's five true no can we get to five by using two's complement no so you move down same questions it's for true no can we get to it using two's complement no now we arrive with the number three it's three true no but can we get three using two's complement well if we look we have the number two and we have it's complement which is one remember again we got it when we were at the number one in this array the first time so yes two plus one is three so we can change this it's a true so we keep moving now we're at the number two is to true ready no but can we get to it through its complement yes because if we look at its complement is 0 2 plus 0 is 2 so we'll change that to true all right so now we can just reset again so our target is the number 6 so have we already arrived at the number 6 we haven't but can we get to the number 6 well we're at the number 4 and we've already come across its complement which is 2 4 plus 2 is 6 so yes we actually can get the number 6 and remember that the entire point of this question was to see whether or not we can get a combination sum of 6 we just got it so we could end right now but it's up to you to determine if it's worth it if you want to put an if statement or something like that in your code that says if we ever arrived at the final number in the array then we can just return true immediately I won't but that's just my personal preference but because I won't that means I still have to iterate through all of the other numbers in the array all right so let's continue so the only thing left to do is to look at the last index in our array and see whether or not it's true it is true so our entire answer would be true meaning yes there is a subset of this array that equals the number six all right let's get to the code what lead code has given us is a function called can partition which accepts an argument nums is the array that we want to determine whether or not it could be split into two equal subsets all right so the first thing we have to do is determine the total that the numbers in the array add up to so we'll say let's sum equals zero and then for every number in it we'll just add every number to the sum and now we'll check to see if that number is odd because if it is we cannot divide the array up into two equal subsets so if it's odd we'll return false so if we get to this line we know the sum is even so we'll divide the sum by two you can imagine the sum now being the target zone we have to get to so if the numbers in our array add up to 6 our target zone will be 3 so can we get a combination sum that adds up to 3 so now we need our combination some array whose length is going to equal some plus 1 and y plus 1 because we also need an index for the number 0 being the base case so we'll say let combos equal no array and the length will be sum plus 1 and what we'll do is make every index false so at this point our combinations array will look like this four slots and we'll fill it giving each index a value of false but like we said before the first index will have to be true so that would look like this and let me just add the indices to make it easier to read so now we'll have to iterate over the combination sums array from right to left seeing which combination sums we can come up with so we'll say for let num of nomes and then for let a equal sum we'll go while I is greater than or equal to num and then I - - so the outer equal to num and then I - - so the outer equal to num and then I - - so the outer for loop starts on the leftmost number in the numbers array and the inner for loop iterates from right to left and keeps track of the totals we can come up with when we add up the numbers in the numbers array different ways so at this point this would be numb and this would be I all right so this line is the one that does the heavy lifting it goes like this combos I equals combos I so check to see if it's already true or combos I - them if it's already true or combos I - them if it's already true or combos I - them and combos I - num is the complement we and combos I - num is the complement we and combos I - num is the complement we mentioned before so to reiterate it's saying look in our combination some array and look at the index we're on so right now we're at index 3 is the index we're on already true if it's already true that's good we can just move on to the next number if it's not already true look at the complement and see if that's true so right now if you look at the top array we're on the number 3 we need to get to the number three in our combination sub array to go from 3 to 3 we would add 0 which is the complement which is right here so have we gotten the complement in the combination in some it actually is true so at this point we can change this to true all right so it's going to do that logic for every number in our combination sub array and then it's going to move to the next number in our nomes array and do the same logic again for the combination sommes array and it's going to do that over and over until it has checked every number and our numbers array so I'll do this part very quickly you all right so all there's left to do now is to return whether the final number in the combination some RA is true so return combos some all right so let's run the code see how we did looks good let's submit all right so our code was faster than about 78% of other JavaScript about 78% of other JavaScript about 78% of other JavaScript submissions and takes up less space than a hundred percent of them as usual the code and written explanation are linked down below also in the description our other good resources for learning algorithms see you next time
Partition Equal Subset Sum
partition-equal-subset-sum
Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,5,11,5\] **Output:** true **Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\]. **Example 2:** **Input:** nums = \[1,2,3,5\] **Output:** false **Explanation:** The array cannot be partitioned into equal sum subsets. **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 100`
null
Array,Dynamic Programming
Medium
698,2108,2135,2162
382
welcome back friends today we are going to solve lead code problem 382 linked list random node given a singly linked list return a random nodes value from the linked list each node must have the same probability of being chosen implement solution class so in the solution class we have been given a head of the list and they say that initializes object with the integer array nums so we created in error nums here and they are saying that git random in get random method chooses a node randomly from the list and returns its value all the nodes of the list should be equally likely to be chosen means it should have equal probability of choosing the element from the list or in this case from the array so what so this is one of the example they have given us uh one two three and so we will be given the head and first what we will be doing is this is the constructor right and we have we are given the head of the list so uh to initialize the array we cannot initialize that directly because we don't know how many elements are there in the list so we are first going to iterate through the list and we are going to calculate this value of i so we will know you know how many elements are there in the list and we will use that number of elements to initializes the nums array here in this case we have to again iterate through the list so we will again point curl to the head and iterate through the list so that we can populate the nums array so here we are populating the nums array so uh here as you say we are iterating the list two times but still it is like a 2 n means it is still order of n so uh when we are actually choosing the when we are getting the like a gate random call then we are going to use a java's random class to generate a random integer so let's take a look at this random class here so this random class is a part of java.util and in this random class we java.util and in this random class we java.util and in this random class we have a method called as nextint so here you can see what that next end is right so i just took that same explanation here so you know it returns a pseudo random uniformly distributed into value between 0 inclusive and the specified value exclusive so for example to test our code i took a test case here which has a element starting from 1 to 10 and on any get random call it should have a probability of equal probability of choosing any of these elements so we will use this next int method and we will just pass a 10 which is the maximum value in that list and or in the array and then it will have a equal probability of choosing the minimum number 0 and the maximum number 9 so y zero and nine because the array starts with zero and uh that's why if we have ten as a maximum value in the like uh ten positions in the array we will go from zero to nine with this next in you know it will return us any value from 0 to 9 inclusive and with the equal probability so that's how we are going to achieve this get random so once we get the random position we will just pass that position here into the nums area and we will get the random number here so let's just quickly you know test our solution here with this uh 1 to 10 and make sure it works so as you can see it generates the you know the random numbers in the equal probability so this can be different than the expected answer the order can be different the main thing they are looking as it should be generated with the equal probability so it's not like only one number is generated again and again but the number should be generated with equal probability which is working fine here so uh the time complexity for this is order of n because we are just iterating two times through the list once we are iterating to get how many numbers are there in the list so we can in use that information to initialize the array and we will actually populate the array at the same in the second loop so we are not using much you know kind of uh any data structure or anything so space complexity should be just order of uh one which is constant so let's just submit the solution yeah so the solution is accepted as you can see so this is how you can do the linked list random node so this you know this class is a important class to remember for this random generation questions like java.util.random and it has a method java.util.random and it has a method java.util.random and it has a method called as nextint so this next in method we will just pass the upper bound and it generates the uniformly distributed random number until that bound so if you like this solution please subscribe to my channel and click on the like button and click on the bell icon so you won't miss any kind of a future videos that i post i often post java j to ee related videos lead code solutions and java j2ee related interview materials so please subscribe if you are interested in this thanks for watching
Linked List Random Node
linked-list-random-node
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. Implement the `Solution` class: * `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`. * `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. **Example 1:** **Input** \[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 3, 2, 2, 3\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. **Constraints:** * The number of nodes in the linked list will be in the range `[1, 104]`. * `-104 <= Node.val <= 104` * At most `104` calls will be made to `getRandom`. **Follow up:** * What if the linked list is extremely large and its length is unknown to you? * Could you solve this efficiently without using extra space?
null
Linked List,Math,Reservoir Sampling,Randomized
Medium
398
83
hey hello there so today I'm continuing looking at link to lists or related questions so I got to question today one the first one is 83 remove duplicates for unsorted list we have a sorted a linked list so they're nodes inside this linked list that there are values are in the ascending order we need to delete all the duplicates such that the element each element appear only once so since that the list is sorted the duplications the nodes with the same value are going to be adjacent to each other so let's just say that we are currently looking at a particularly here in order to remove the nodes that can potentially have duplicate a value with this node that we are looking at all we need to do is to check the next if we just so happen to have the same value on our next we're going to just show that next connection so instead of pointing to my next original next I'm going to pointing to the next sand next so obviously we will want to continue doing this until that you know if this is one we will continue doing this iteration to on until that the node that we're currently looking at is pointing to a node of different value and at that time we can advance to move forward so yeah so since that now the traversal know we were pointing Traverse pointing to the node one that's different than the next then we can actually safely move to move over there so that's a iterative approach of solving this just checking the adjacent nodes if the next is of the same values now or no we're going to short that connection we do so until that I mean exodus of a different value then we can move forward so it will be a linear time algorithm we parse the linked list up from the beginning towards the end and it will be constant space so this is the pretty straightforward iterative approach so we start an over traversal after the head node and while we can still do this comparison meaning that we have a next new that in the sequence we can potentially have duplicate if we don't have any next node and that means we pretty much stopped what we need to do is to check the values between my value and the next satisfied so if the if my value is different and my next that means there is no duplicate value there is no node with the duplicate value as myself so I can move forward otherwise I would need to short my next so this is going to be the iterative approach it's going to be linear and taya and console in the next space the logic is pretty simple so another way of solving this is to think about this question sort of like more I'm gonna put it on here another way of solving this is to solve this recursively which is going to be actually require more space complexity because we have to relay the task to our next so the rate of reason about that is if I'm currently looking at the node here let's say that I'm number one so I do find that myself is of the same value as my next so what am I going to do is to give myself up and instead of calling this function 3 do plates duplicate as if that my next is actually the starting point of the linked list so you will do so recursively so that you would continue checking if you if the my next has the same value with my next the next my Nexus are also gonna be voluntarily give him up give himself up so until that we do find the node has a different body with the next you will actually return its own value as the as if it's the fennel for subsequence of the linked list that has no duplications so if my I myself has and my next the values are different I can ask a my next to do the same thing to do the deduplication from himself him or herself and on after he or her done the same job I'm gonna actually connecting myself whisk him also Wisman was my next so that's the you know recursive relationship so I'm just going to note it down here no equal to I'm just going to use thought here if that this is a case that means I want to give myself up and I should return a function recursive function of mine my next if my value is different than my notes in my next value I want my next I want to point by next to do the same thing and so that I can say you know confident like connecting myself with risk this next because I know if we do the same job as I do the subsequent nodes will help contain the duplicates so you might be the case that I'm note one on my next slot note has a note money - that's all I know money - that's all I know money - that's all I know and that's all I care if there are subsequent notes that after my next that also has body - I don't really care you also has body - I don't really care you also has body - I don't really care you know the who to give up himself it's not my business oh and I need to know as I want my subsequent linkless the two notes to do the same thing to do the deduplication and that after that I can connect myself to that so that's the recursive for kind of a relationship the base pays is just for isolated node I would just retire myself single node I'm just gonna test single a termination old term in a node or a null pointer return itself so that's the recursive logic there the code is pretty similar actually to the iterative I should just change the variable name to a head so the yeah the logic has laid out there sorry I'm missing up the variable names so otherwise I will actually connect myself to this duplication of my next after that I will return myself yeah return myself is done there so that's the recursive solution you will be also a linear time but you will the cost that can go as deep as it has to go as deep as to the tell node and then backtracking all the way back to the beginning of the link invest potentially so that's a linear space nonlinear in time let's see if it works okay all right so that's this question simple question 83 remove duplicates from sorted list solved posed in the unit aversion to short the links iteratively I move forward or solve this recursively so that's to approach for this question all right
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
837
Hello everyone welcome to my channel, it is a mathematical question, but I felt that it should come in the middle of medium and hard, but if you understand it, then it is okay, it can be done till medium level only, ok, the name of the question is New Game 21. Ok, now we have to read the question asked by Google and let's see what all is mentioned in the question. It is very important to understand the questions first. Ok, so if you understand the questions, then look, it has been mentioned that Alice is playing a game. Okay, so what does she do in the game? Her total score at the beginning is her total score, that is, the points, her total point is zero. Okay, and what she did every time is that she draws a card and gives that card. There can be any number in the card, it can be any number in the card, there will be many cards starting from one to the maximum point. Okay mother, if we take it, then each card will have either one written on it, or tu hai, three more. So one will be 10 so this is the power to pick up any card at any time so as if mother takes any as she takes mother he picked this card okay he picked this card during this de gens and indigent number of Point: Point: Point: If he picks this card then his point will be added by two. Next time if he picks any card at random then he may be sorry. So let's take two after picking three. His answer will be added by three. Okay and then he She will play the game till her total points are less than the total points, she will play till the total points becomes greater and equal to you and she will stop the game, it is written here. She will stop, this thing is now clear, what is given in this question, it will give you the value of one N, but take out an example, okay, so he is asking such a question, okay, then see how will you approach it, if he understands. What is the best way to understand it, take an example, okay, because of mother, the maximum point given is 10, what does the max point mean, it will have 10 cards, okay and everyone's numbering should be the same, Rakhi will be 123m. Total will be till 10. How many cards are there? There are 10 cards. OK and the value of K is 17, meaning if her point, if her total point becomes 17 or more, then she will top the games. Okay, understand that. Now look at this to understand that I P Why should I go only till 17, he understands from here that look, let's take mother, he has 10 cards, the maximum point given is 10, so 1 2 and so on, there are 10 cards, so his total score, I will try to calculate it now. I am calculating the score. Okay mother, let's take it. For the first time, when you drew the card, he picked up the card with nine and nine. What score should I take now? Yes, 17 means this is the game ahead and game power. 17 What was my cake? Value was there, after that when he raised it again, that's why he raised 6. Now look at the total score, it is 15 inches li den 17, that is, A and the game is playing power. Okay, now in that, next time when he raised the card, it is okay, so he raised six. If taken then no six 15 becomes 21 ok either let's take mother 10 is taken from this okay so now whatever is 21 give it greater 17 means now the game has stopped here Okay now the game has stopped here meaning as soon as If it is found to be greater than 17 or if 17 is found to be greater than 17, then the game will stop. It is given in the question that either 21 means 21 N = 21, but if this is a very 21 N = 21, but if this is a very 21 N = 21, but if this is a very long value then it is difficult to start. I have taken six, then 10, I have the power to go till 26, but we have been asked only till 21, so what will I do, the point of 21, sorry, the probability of bringing 20, the probability of bringing 19, I will bring Poverty and Sohan only till 17 because if 17 There are many possibilities, the first possibility is that as much as he picked up, he would have got 26. So the game would have stopped here. What is the other possibility of this and one last possibility is that she would have brought 17, the game would have stopped after 17, is n't it okay, if there is less relief than 17, then she would have played more games, that is why it is clear, that is why I said that when I have to find the probability of N = when I have to find the probability of N = when I have to find the probability of N = 21. Well, 21 is one. Now I have proved it to you that it can go up to 21 or 26. But in the question I said, brother, if I have to find it from 20 one, then I am 21 plus 20 of 19 Pvt. I will go only till 18 of 70, ok till now it is clear, now pay attention to one thing, first let's pay attention to property of 21, okay rest will be taken care of, but what do I do, pay attention to protective 21, okay, let's pay attention to 21 separately. I am writing here to understand, look at produce 21, there are many ways to bring, what is the first way, it may be even, he might have brought 16, how will it look, I don't know, he may have picked such cards which will make 16. A must have gone but this is still the game power because the score of 16 is less than 17 now and the ball is the power to play and when the game will be played then I still want many of them but I still have access to many, I still have access to 16 I have to reach many people, no, I am taking out many of these, so how many children is this 16, tell me how many are five, one, this is a possibility, this is power, why are we multiplying, you must know that we multiply in probability because solar 5 Together, 21 has come, both are not separate solutions, both together will come from 21, neither one, so the chase has happened, each one is seeing this possibility, I am fine, and how can it be 21, they think it is okay, close it in brackets. Let's do 21 and how can A. They think okay so let's see here maybe he brought P of 15 and Samo can still play this game because it is less than 17. That's okay so the probability will be six. There will be a lot of probability. Okay, which card was picked last? The fifth card picked is the card with number five. Do you remember the number card which was the maximum point? Maximum point means ' which was the maximum point? Maximum point means ' which was the maximum point? Maximum point means ' One' written in one card, 'Tu' must be written in one card. The One' written in one card, 'Tu' must be written in one card. The One' written in one card, 'Tu' must be written in one card. The answer will be written: Okay, here is the answer will be written: Okay, here is the answer will be written: Okay, here is the maximum, here is the card with number five, here is the card with number six, how much power is the maximum, remove the power of 10, there is more power, I have many possibilities, I just write the one with maximum, I am six here. But okay, what about the maximum one, if we take the mother, she picked P of 10, then I wrote P of 10 here, how much child do I want, 21, then 21 minus 10 is clear till here, so I can write it like this and the capability of 11 * I write down the probability of 10, do 11 * I write down the probability of 10, do 11 * I write down the probability of 10, do n't I delete it. How is the love of 11? That certificate was shown to you. Now pay attention to one thing, what did I tell you that the questions are visible? 10 cards are visible. Are you looking at 10 cards? And every time it picks up a random card and it is said that brother, the probability which is H draw is independence and outcomes are equal probability, so brother, there are 10 cards, out of which you are picking up one card every time, then what will be the priority? It will not be 1/10. If the five card is picked, what will be its probability? One by max point means one by 10 means the value of maximum point given, then I am late to it, okay, similarly, Chhath card is picked, it is also given priority. Will it be one buy? What will happen brother, these 16 will come in one go. I have a card with maximum of 10. 16 can come from many possibilities. Okay, so the smallest one who will pick up those cards last will be the one who will be tanked from one. Its priority is inside, I have written it here, instead of 10, I have written M because it is a constant, it is clear till now, it is okay, so we have seen it, so we have nothing to do, if we have to remove the probability of 21, then what should we do? Look, pay attention, I started from 16 and I told you a little while ago why I am starting only from 16 because if you start with 17 then the game will stop at 17, now the next game will not be played. You will get it but after getting many scores, you are getting 17 scores. If you can't do 17 then it is obvious that you can't do 18. If it is more than 17 then the game will stop here. You have to bring many scores. So 18 19 20 21 can't do anything, you can just start from 17, like if 17 was maximum then you can bring 16, if the score of 16 is &lt; 17 then you can play more games, is &lt; 17 then you can play more games, is &lt; 17 then you can play more games, remember next time. When you brought it was 16, 5, 21. Okay, till now it has been cleared. 16 means, what happened? You can start from 1, because this is the dog, the game will end there, if you will not be able to flood further, that is what I am saying. That's what I am, I will start from B of A minus one, this is only K -1, so P of twenty one, I took out 21 plus, it means we were doing till K, this is what I told you above, you are not being very simple. Gya, I reduce one, no, I need from one to 21, no, I reduce, I took out one to 21, I am late and I am late, what did I do, I took out the property from one to 21, here is something There is something here, there is something here, something has been taken out, now after that, what is asked in the question, brother, what truth do I want till 21, what will I do, mother, if I did it here, then I will add the answers from K to 21. I will throw this out to hell, but how will I add the answer till 21 and send it because I have to send only that, sending the answer from many till 21 is clear till here. What did I say that I am from one to 21, what was my N? If was, then I am writing N, let's keep it ok, so first of all, let me tell you what the property of I means, that it is D. Probability of getting score = I. A meant that now it is zero based score = I. A meant that now it is zero based score = I. A meant that now it is zero based indexing, it means obvious. It is a simple thing, when you start it from zero, here it starts from zero, then what is the meaning of P of zero, understand the probability of getting score, it is equal to zero, now tell him one thing, the prisoner had started the game from zero itself. It is an obvious thing that the game has been started and if it already has a score of zero then it will not become priority one. So if its score is already zero then the priority of zero is getting the score zero is one because it is guaranteed that it has a score of zero one at the start. Its score is zero, okay, so P of zero is equal to one, so we have done it here, okay, now the matter has come, let's calculate from priority one till the end, okay, we have to calculate the probability of any number. If it was there, then remember it was written like this, it is okay if we take mother, then how did her cards come out, either one's power will rise, either you's power, or up to the max point, that's plus, everything is clear here. How much will this card be able to pick? Either one card will be picked, it has become one. Okay mother, let's take it. Now pay attention to what I am saying here, what will be the probability of I. Look at the value of probability of I. Rakhi will be plus point, max point, it will be clear till here, ok, simple negative, ok, I am repeating again the line you have written here, this one is ok, what does it mean that you must have picked up a card and the remaining score If there is one more tax, then it is like Party I - J. tax, then it is like Party I - J. tax, then it is like Party I - J. Okay, if I means 17, that means you have already brought 17 points, then after that you cannot pick up even one card, so there is no possibility of getting this maximum points. So this is going to be a mess, we will have to keep I K &lt; K, only then you will pick another card and have to keep I K &lt; K, only then you will pick another card and have to keep I K &lt; K, only then you will pick another card and multiply it. It is better than the one with one by max point. This detail is missing in many videos, meaning I don't know. This thing is not needed and it is not given even in the official solution of the need. If we look at it fine in detail, then our code ended here. What did we do, we filed the whole thing. It is okay with our answer. Now we need to know about this. What do I have to do, what did I say, I only mean what &lt;= till N, if N says, then whatever my result will be, what do I have to do, I will do the result, it is clear till now, the solution is quite simple, I have understood the insider. Loop which is max point time will run, complexity should be limited in this time, that is, this loop will run so many times, which is a very slow approach, but I will submit it and show it and it will give a seat in the time limit, but it will be able to pass more. Solution this is brat force method actually and in interview other interview bill want you first solve it by brat force ok so first let's submit it and see let's see four able tu pass which d best cases and note so let's code it exactly As I told you in my route approach, what I told you is that first of all I will take a vector in which I will store all the properties, okay, starting from one to 21, all the properties will be 0.0, all the properties will be 0.0, all the properties will be 0.0, okay and here I would write What is the meaning of hoon ki poi it is d probability of getting score is equal to tu i ok now remember I told you why PF will be zero one because starting is the power what is the value of how many types of cards are you picking then one By maximum property will be the remaining score. What is the value of your I-card? Is it value of your I-card? Is it value of your I-card? Is it okay and if you want to calculate its probability then P of I minus third is okay? One more card is okay, this is our less is finished. Now what do I have to do brother. I have to add priority up to k2n, just said the same in the question and fever is fine and one thing I told you here is that please check here brother I-card which is it should be greater than equal to check here brother I-card which is it should be greater than equal to check here brother I-card which is it should be greater than equal to zero and most importantly Check's I card should be taken because if the value of I min's card becomes equal to K then it becomes equal to K. Sorry because if it is equal then how did it become bigger, meaning your game has stopped here. You can't increase the game one more time, you must have chosen this card, it's ok, it's clear till now, it's clear, now what do I have to do, I just have to sum it all, I just did it yesterday, take it. Find out all the values ​​from low to the end. all the values ​​from low to the end. all the values ​​from low to the end. Ok and let's see by submitting it. Great, let's see by submitting it because it is not an optimal solution and see how many test cases it has passed. So let's see what small option has to be done here. Give them Bill Be Able, you submit the details, let's see what will be the optimal solution for the cases, remember I had taken this example, neither do they reduce nor do I draw and see that if I have to find the probability of 16, then the probability is ok. And how did we do Probability of 15 * 4 * Probability of 13 * 1 + Dot Pay attention Probability of 17 Let's see what will happen, ok Probability of 16 * 1 / M plus Probability of 15 * 14 Ok, is it clear till now? Okay, similarly what will happen in P of 19, your P of 18 cannot be because the game will stop here, I had to end the game in 17 itself, either in more than 17, after this you cannot play one more card, then no. If you are not able to reach then 19 will immediately become 18 17 Sorry, the same thing will happen to 19, here it cannot be 18, here it will be 16, then 15 will be the answer, ok, so there is no need to write it completely, I will explain it to you from all three, see Pay attention, look at this is 16, right, this is 16 and 17, you are looking at 17, already 16 is happening once more, okay, if I store this, then I cannot do that here in 17. Okay, okay, till now it is visible that when it comes out on 17th, I can do the result of 16th one. Okay, it's gone from 16th 15th, it's gone from here to above, okay and above. If you go and get 19, then it will be from here and there will not be 8 because there will be no there, it will be 9 * 1 / M, then my current sum will be maintained as a sum so that I can do the same and be happy in future only then. I will take a variable, the sum of probability, I will store this probability sum, I will keep doing this, I have calculated the future result, that is, look, 16 is smaller than 17, right, so what will I do, I will update us with the probability, why so that 17, with my probability, we can do that. If I can, what will I do? I will add myself in the probability sum. I have added myself. Okay, it is clear till now, so I have done it. Now look at one more thing, brother, I am adding it because now when I came at the age of 17, So take 17, isn't it 17? If mother brought me here, 17 lesson is not 17, then I will not do this because it is right, 18 is not necessarily 17. Look, here you can see the story 17, isn't it? It is not 17, it is not 17, so definitely not on, then 17 will definitely not be required, the one who is already running the probability sum, we will do this, but we will definitely have to mine something, you see here 7 - This happened here 7 - This happened here 7 - This happened here. Mines happened, right? I did this out of 16 because here in 17, that PCS guy doesn't have the last term. Okay, so I am saying that whatever probability is even, I will definitely do one thing because look. No, what was there last time in 16 is not happening here, it is happening in 17 and what was last time in 17 is not happening here, so what should I do, I will update myself, I am mining for the next time. Do n't worry, when I come here at the age of 18, I will do one buy there. First of all, I will do one buy there. Okay, don't worry about that, now after this first check this brother's eye - brother's eye - brother's eye - Max point equals you zero. It should be okay and one very important thing, I just told you a little while ago that I have max point, so I am doing it here, okay but I am not doing it in one by M because I said that I will do one by 17 in future. I will go close but here what does one mean that you will pick another card whose process is 1/M when you have not reached the field then it is clear to you that both these conditions are very important and you should not worry about this thing. Look, where else will I handle the one buy? I had said that I will figure it out in the beginning itself. Okay, what will be the probability of whatever I am running? What will my current sum be running? Make one buy max points in the probability sum that is running. You have given the max points, okay, here you are dividing by the buy max points, okay, after that I + 1, that is, for the next band that is going to come, after that I + 1, that is, for the next band that is going to come, after that I + 1, that is, for the next band that is going to come, I will update us with the probability, okay and when will I do it? I am Lee Deen Ki, like I was 16, so I was Lee Deen Ki, so he is updating himself, why is he updating so that he can do P17, he is okay, so what did he do to himself, he added this equal you P I just look here, we are doing p16/B, but look here, we are doing p16/B, but look here, we are doing p16/B, but remember, I am just adding p16 here, it will happen here next time, when the loop will run, then it is okay and when I was preparing for 17, then When I did this, I had said that this will also have to be removed, the one with mines is fine, so I removed that too here, Mines is equal to P of I - Max Mines is equal to P of I - Max Mines is equal to P of I - Max points are clear till here, okay, so if we see, now our Both of these things will happen in a single loop, because I have calculated the probability sum. It is okay from the beginning and tell me one thing that if the probability sum is zero, you will know that it will be one. It is okay and in the beginning, what will be the value of the priority sum. There will be only one because I have the same priority in the starting, right, p0 = 1, so in the starting, p0 = 1, so in the starting, p0 = 1, so in the starting, I will keep one from the first property, after that from one till the end, then I will run the loop there to take out everything from brother till the end. That will be my answer. Okay, so let's code and when we write the code, we will repeat it again and again. Explain this. Okay, so let's submit the optimal solution quickly. This is a very headache-inducing question. Okay, all this is the same. From This is a very headache-inducing question. Okay, all this is the same. From This is a very headache-inducing question. Okay, all this is the same. From will be vector of double p from 0 to sorry probability sum is equal you took one ok but look every time it will not be one na if we take ma that mine is zero tell me if k is zero then what will be my priority sum and that too It will be zero, okay, if it is not so, then it will be one. Here I write like this, if it is zero then it will be zero, otherwise it will be one, it is clear till here and give equal tu ni plus till this point it is clear, that's it now. Do the same again by returning the Accumulate Beginning of P+K to 0.0 starting time. This has become a two liner time complexity. We have written just one for loop. This is a huge improvement and the question paper is quite a headache. Thank you.
New 21 Game
most-common-word
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets `k` **or more points**. Return the probability that Alice has `n` or fewer points. Answers within `10-5` of the actual answer are considered accepted. **Example 1:** **Input:** n = 10, k = 1, maxPts = 10 **Output:** 1.00000 **Explanation:** Alice gets a single card, then stops. **Example 2:** **Input:** n = 6, k = 1, maxPts = 10 **Output:** 0.60000 **Explanation:** Alice gets a single card, then stops. In 6 out of 10 possibilities, she is at or below 6 points. **Example 3:** **Input:** n = 21, k = 17, maxPts = 10 **Output:** 0.73278 **Constraints:** * `0 <= k <= n <= 104` * `1 <= maxPts <= 104`
null
Hash Table,String,Counting
Easy
null
206
hello everyone my name is Horus and in this video we're going to be going through Lee code number 206 reverse link lists so for this problem we're given a head of a singly linked list and we simply want to reverse the list and return the reverse list so as always let's go through an example so for this example we're given this linked list and we want to reverse it so how can we go about reversing the linked list in an algorithmic way so we can take each of the links that are present in the link list and simply change the direction of them so since this link is pointing towards the right we simply want to change its direction so that the 2 is now pointing to the one we also want to change the head of the link list should be where the tail of the linked list was and the tail of the linked list was this node so this now becomes the head of the Reversed link list we can also remove this next pointer which points to null since this is the head of the linked list and we have to ensure that the new tail of the reverse link list points to null so we can terminate the linked list so the one node points to null so this is what the reverse link list will look like after we reverse the original linked list so there are two solutions to this problem we can take an iterative approach and a recursive approach so first we'll take a look at the iterative solution and for this solution we're going to be using two pointers a previous pointer and a current pointer first we can recognize that the end of the link list ends in null and since we're reversing the link list we can begin with null and that means we can point a previous pointer to null so we can say that we have null and then the previous pointer points to the null value and then we also have the current value and this points to the head of the linked list in the beginning so we need to make sure that the current pointer is not null so if the current pointer is not null we can continue with this algorithm so first we'll be tasked with updating this next pointer but if we update this next pointer and change it to point to something else then we lose reference to the next node and we cannot access it then we can create a temporary variable which is going to keep reference to this node and then we can go back to it anytime now that we have a reference to the next node we can update the next pointer for the current node so then we can just remove this next pointer and update it to point to the previous pointer then we have to update both the previous and the current pointers to point to the next values in the link list well the previous one is pretty simple we can simply just change it to be the current and then the current we can change to be the temporary value so now the previous pointer is going to point to the node with a value of 1 and the current pointer is going to point to the node with a value of 2. and then we simply repeat this algorithm until Cur is equal to null so let's continue with this algorithm we first store a temporary variable that stores reference to the next pointer from the node so the temporary variable is going to point to null then we want to update this next pointer and make it point to the previous node well we can just update the next pointer and change it so that it points to the previous node then we update the previous and the current pointers and the previous becomes the current and the current becomes the temporary so now previous is going to point to this node and then current is going to be null and we see that we've reached a point when current is equal to null so then we can just go ahead and return the reverse the link list and we can do that by returning previous and we can go ahead and return previous since this is now the new head of the linked list and that's how the iterative solution works for reversing a linked list the time complexity for this algorithm is going to be Big O of n since we need to go through each of the N nodes in the link lesson reverse each of them and the space complexity is going to be Big O of 1. since we're not using any additional data structures we're just using two pointers and reversing the linked lists iteratively with that being said we can go ahead and write the code for the solution okay we're on Lee code and we can start writing the iterative approach solution so first we can begin by initializing the previous and the current pointers as we said the previous is going to begin pointing to a null value and the currents which will say occur is pointing to the head of the linked list then we can write a basic while loop which traverses the linked list until current is not null so we can just say while Cur and it will continue iterating as long as we move the current pointer then we can keep a temporary variable which is going to point to the current next pointer so we have reference to it once we update the current.next once we update the current.next once we update the current.next we update the current.next and this is we update the current.next and this is we update the current.next and this is going to be pointing to the previous node so we can just set it equal to previous and then we shift both the previous and the current nodes so previous is going to be equal to current and then the current is going to be equal to the temp variable that we set which is just the reference of the ker.next reference of the ker.next reference of the ker.next then finally once the current is none we can just return the previous node and this is the entirety of the code so as you can see the code is accepted and we can check out the runtime and the space complexity so this is the iterative approach for this solution so for the recursive approach to this problem we first have to define the base cases of a linked list when we're trying to reverse it well we can take a look at two of the most simplest cases either when we have a node that is null or when we have a singular linked list and obviously this is going to be pointing to null now for each of these cases we know that we don't have to actually do anything since a null value is already reversed but for the other case we don't actually have to reverse it since we're not concerned with this part we're only concerned with the node and if we just take a look at the node we don't have to reverse anything since it's not pointing to any other nodes with values that means for those two cases we can just simply return first we begin with the call to the entire link list since we're calling with the head then we call recursively to everything after the head value so all the nodes and then again this continues and then until we reach one of the base cases so we reach the null value and then we can simply return from this point so we recursed backwards and then we see this base case which also just is already reversed then we look at this recursive step we can imagine that the current pointer is at two but notice that we also have reference to this node already so we can simply take this node's next pointer and update it to be the current head pointer so we take this next pointer and then we update it to point to the current head in the recursive call well what do we do about the next pointer from the current node we're at well we can simply take this next pointer and just remove it in other words we can make it Point To None or null so since we're looking at all the nodes now this is the current node that we're looking at then we can take the nodes next pointer but this is pointing to null so we can take that pointer and update it to point to the head and then we take the next pointer for the current node and then we point it to null and also while we're recursively calling this head is updated and the head actually becomes the third node and since this is because we recursively called until the base case and then we can just return the node and then this is the Reversed link list the time complexity for this approach is also Big O of n but the space complexity in this case is also Big O of n since we have to deal with the recursive stack and that can be Big O of n in the worst case which is all the nodes so with that being said we can go ahead and write the code for this approach as well so we can begin by writing the base cases and the base cases we said were when we have a null or if we have a singular node so we can just say if not head and this means that it's a null value or we could say that head dot next is not present which means that it's null and then this is the singular node in either case we just want to return the head then we can recursively call and we'll save this value in a variable called new head and will recursively call the function so self reverse list and then we'll call it what the next node in the link list so head.next head.next head.next and finally we can update the next pointer so head dot next and this is going to be equal to the current node or the head and then we can update the head next to be simply null finally we're just return new head and this should be the recursive solution so we can submit it and you can see the code is accepted and this is running in Big O of n time with Big O of n space so with that being said hopefully this video helped you and you learned something and I'll see you soon
Reverse Linked List
reverse-linked-list
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[5,4,3,2,1\] **Example 2:** **Input:** head = \[1,2\] **Output:** \[2,1\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is the range `[0, 5000]`. * `-5000 <= Node.val <= 5000` **Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
null
Linked List,Recursion
Easy
92,156,234,2196,2236
70
great hello everyone um this is logic coding this time we're going to look at another very classical um i think it's elementary dynamic program question called climb stairs it's very similar to fibonacci number we are given n and access to climbing a staircase it takes n steps to reach to the top each time we can either climb one or two steps and it asks us to get the number so it's count how many distinct ways you can climb into the top so if we want to go to n we can reach in from the previous two states one is n minus one by climbing one step or we can reach from n minus two by two-step by two-step by two-step so essentially this fn equals to f n minus one plus f and minus two so the most brutal way is just to use this recursive function but that would give us exponential complexity um just like fibonacci number we can use a tabular form uh we can allocate a dp array to record this and the time complexity will just be on and the space complexity if we do allocate an array will also be open so within that let's code it up so the base case will be if my since i do have a minus one or n minus two so my n has to be greater or equal than two so when a equal to zero i have one way and when n equals to one i have one way otherwise i can allocate a dp array which will take um n plus one and the initialization i can just initialize into zero and then i can do my dp zero equals to one degree one equals two one and when my i starts from two plus at the end i just need to return dpn so the dpi is a function of the previous two states i can just sum them up i minus one plus g p i minus two so each i can come from the previous two states one is one step before the other is two steps before if we just sum them up we are able to get the total waste we can climb to the top um let's try submit it so it passes but as we can see we can still improve on the space why because it's only a function of the previous two states so instead of using this dp array we can just allocate two numbers equals to one as well and then at the end i just need to return b so in between i need to so basically a will equals to b and b will equals to a plus b which equals to um a will equal to b and b will equal to this 10 plus b and at the end i can just return b let's try and submit it cool so um at the end the space can be optimized just to constant space since we only need two variables to store all the intermediate and the final results um that's it for this climbing stairs it's very similar to fibonacci number question and i think it's a great practice for introduction of dynamic programming regarding to the state is a function of the previous states cool that's it
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
47
hey everybody this is larry this is day 12 of the lead code daily challenge hit the like button it's a subscribe button join me on this card let me know what you think about today's problem permutations too so given the collections of numbers nums that might contain stupid return all possible unique permutation in any order okay this is just permutation and the obvious thing is that um you know there are library functions that does this in multiple language not gonna do that because if i do then that's just like a really silly video and you'll be like this is useless um but the idea here is also so the tricky thing um okay let's start with the basic idea is just the n factorial way where it's just like recursive and you know you generate all possible permutations the tricky thing here is that they're duplicate elements and there are a couple ways you can handle those elements then one thing to notice is that and you could kind of guess what it is without looking to be honest is that um it's eight factorial it's the worst case which is only 40 000 cases right so you could definitely for handling duplicates you could definitely like do some kind of hashing and kind of look through it uh that should be okay eight factories only about forty thousand and how do i know that um like we were looking at the constraints that i knew that this problem is going to be right like on order of n factorial because you can't do better than that right that's the number of output so that's going to be and factory no matter what and because i knew that and because n factorial obviously grows very quickly if n is any number that's big it's just not going to run anyway so like they have to make this small enough right so that's kind of the thing um the other thing to do is just take one number at a time without um so basically instead of looking at them as distinct numbers now you have buckets of numbers and you want to take one hour of each bucket at a time where you merge the um you merge the uh you know buckets of the same balls if you want to call it that where you know the two ones are together and one and so forth uh and that's the way we let's cut let's do it that way and that's the way i'm going to do it um this thing is up to from negative 10 to 10. um trying to think when i should use the hash table yeah let's just use the hash tables i don't have to think about it that much but and i could even use the collections.counter but collections.counter but collections.counter but in this case i want to be really precise so that i'm going to use just a normal hash table and implementation doesn't matter so you know definitely you know experiment with it figure out what it is that you think is good for you and you know don't copy people's style you know use what is comfortable for you that's what i would say uh but i will actually convert this to a collection.default deck so i don't have collection.default deck so i don't have collection.default deck so i don't have to check whether it's in there i'm going to make it ends which default answer is zero but and now we have uh a generate or permutation thing so let's get to it how do i want to get to that okay so let's just also end as you go to link thumbs so that's just i'm just putting um so i'm doing what i'm going to call bookkeeping uh it's a term that it's not a name for the algorithm it's just keeping track of stuff and making sure things and certain ways in terms of implementation if you keep track of certain things it'll let you implement things easier and that's what i'm doing now and the thing is that you can calculate these on the file all the time but if you make sure in some invariants are true you can do this uh to kind of pass in the function so that you have local variables that help you and what i mean by that is that using length is equal to n or n is equal to length i grab something like you know we curse and i could just have n left right and that's basically my thing uh and maybe current away um and then okay if n left is equal to zero that means we're done so do we have to keep them in sorted order in any order so we don't even have to do them in sort order though you know it's probably still a good idea but if end up left then answer dot append kern away um a copy of the kern away and then we return otherwise we go through the accounts thing and just take it one at a time and to be honest i do actually have to make sure that this works in the sense that i mean it just this will work but i think sometimes when you modify stuff while in iteration it may give you certain issues in some languages um so i have to double check that so n left minus one so that is just one smaller elements to kind of keep track of we do this current uh array plus an extra element which is the x and this is just regular backtracking i do actually have to keep track that if counts of x is greater than zero which so that we have one to take away so we take one variable we can we do a recursion putting this element in the back and then we add it back to the count so that's pretty much it i think and then we could return answer at the end we have to actually kick it off first of course so we use n to kick it off and also an empty array so let's give it a go i'm just going to keep the numbers small i think these are probably good enough uh yeah just to test them because eight factorial is gonna print you a lot of stuff so that's why i didn't choose a big number uh but it looks okay so fluff by eye boring uh you see that handling the dupe case as well so that's the only thing that i had to double check i am going to try oops an 8 thingy for a second just to uh and in this case to be honest i'm very confident about it in terms of running time but sometimes when you do things with a brute force you know you want to do the worst case just to make sure that it runs fast enough and in this case i took a look i'm like okay this is good and i look at this and it's long of course because it's printing a lot of stuff and it takes about 264 milliseconds which should be okay given that this is the worst case anyway so i cooked some mid it uh it's good and yeah so these are the things that i think about um in terms of complexity like i said the output the size of the output is going to be n factorial so you can't really do better than that it is output sensitive um yeah and that is both the time and space because well that's the amount of space that we need for also outputting the results right so you can really do better than literally giving the best answer that you can give uh so yeah that's all i have for this problem let me know what you think i think the only thing that is tricky is that i do this bucketing thing to handle duplicates and the reason why that works is that now when we go one at a time we don't have to worry about the order we just take because now it's um it's indistinguishable which uh ball we take from a bucket say right so now you don't have to worry about like four one ball two and they have the same number in different directions and that's how this invariant holds um and yeah um that's all i have let me know what you think this should be um a good problem for backtracking for practicing so definitely make sure you understand this and harder backtracking bombs will be uh you know in your domain soon anyway that's all i have i'll see you tomorrow and hit the like button and all those other buttons bye-bye
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
452
in this video we're going to take a look at a legal problem called minimal number of arrows to burst balloons so basically the question um given us a 2d array and this 2d array symbolizes the balloon size right so here you can see we have 1 six one six that's the balloon and the other um two eight is another balloon the hat that go that starts at two and ends at eight right and the other balloon is seven starts at seven and ends at 12 10 and this is 16. so the question is we want to find the minimum number of arrows to burst all the balloons right so in this case we can shoot one arrow here right um at 6 right so in this case x equal to 6 burst the balloon at 2 8 and 1 6. and another arrow as 11 to burst the other two balloons in this case 7 and 12 and 10 16. so in this case we're just returning total number of arrows to burst all the blues in this case is two right so um let's take a look at how we can solve this problem but first we have to see some examples here so you can see here we have another example where we have one two three four five six and seven eight in this case we need four arrows to shoot them all because they're not overlapping each other right so those arrays are not overlapping each other so we have to um return four in this case we need four arrows if we have something like this where the edges are touching right we have two and two three here the edges are touching that we can just return two because we can shoot one arrow here um for example we can shoot arrow one here and one here right between at four right a two and four and another example will be two one and two in this case we can just shoot um this balloon and all um the number of arrows we need is just one and for this one is going to be one because they're overlapping each other and let's take a look at how we can solve this problem and how do we know first of all how do we know if there is a overlapping balloon right so to determine if there's an overlapping balloon we just take a look at to take the um the last element the end point right in this case the endpoint is three um the endpoint is three right so in this case all we have to do is we take the endpoint which i could see if three is between two and five if it's between two and five then what we can do is we can just shoot this arrow right here right we know that if we were to shoot this arrow at three we can burst all those two balloons right so we basically have to find the overlapping and to find overlapping we have to sort the array because when we given this 2d array in this case the array is unsorted right so what we have to do is we have to sort the array based on the um the start element right like we first let's take think about if we were to sort the array based on the first element of the every um balloon right in this case the starting point then we get something like this okay well let's what if we have something like this where we have a different example right in this case if we were to sort this array we'll get something like this right we get 1 6 2 8 7 12 and 10 16. we shoot them all we all need all we need is two balloons and all we have to do is we just check to see if the current interval right in the current bloom the end point is actually between the next interval or the nest balloons range in this case six is between two and eight so the number of arrows we need at up to this point is one right so and then we move on to the third balloon in this case we know that six is not within this range so we need another arrow and then we check to see if this element is in this case a 12 is between this range in this case it is then we just still need to use the same arrow to burst all those the remaining two balloons right so the total is two but what if we have an example like this right if we were to apply the same algorithm that we just talked about right we basically store the array by using by based on the first element of each balloon where the star type the start number right then we get something like this where we have 1 6 2 5 and 3 4. then in this case we check the c of 6 is within this range in this case is not so the number of arrows that we need in this case is going to be three right so what we can do instead is we can actually sort the array based on the last element in this case we have four five and six so in this case we check to see if four is within the adjacent um uh intervals um range in this case four is bigger than two and sorry four is less yeah four is bigger than or equal to two and less than or equal to five and five is less than sorry bigger than or equal to one and less than or equal to sixteen sorry six right so in this case we just threw one arrow and we can be able to burst all three balloons so this is the proper way to do it we basically sort the array based on the last element of each and every single interval so now you know how we can solve this problem let's try to do this in code our first step is to declare the size of the array in this case we have points.length points.length points.length right and basically in the constraints it says that the array can be zero so what we're going to do is this if n is less than or 2 yeah less than two we can do is we can just return n right so if it's one we can just return one that's all right in this case if we only have one balloon then we just need one arrow if we have zero balloons we need zero arrows right so in this case what we're going to do then is we're going to sort the array right based on the last element right so based on the last element of each subarrays so we have points and we are just going to use alumni expression and we're just going to sort ascending order based on the last element of each interval once we sort the array what we're going to do is we're just going to have a variable called arrow that keeps track of number of arrow that we have and initially we're gonna have one uh because we're gonna start at index one we basically have a previous um previous let's see so we're going to have a previous end point right the endpoint is going to be the uh first element right the first elements last so the first array of its last element right so in this case it's equal to points at zero at one right so this will give us the previous endpoint which is this one right so that's the endpoint and what we're going to do is this we're going to start at index one so while i is less than n i plus what we're gonna do is this we're gonna see if the previous endpoint is actually um between the current intervals range right so we have i as zero if it's if the current previous endpoint is actually less than or equal to the current interval start time and the previous endpoint is less than or equal to the current intervals i at one so yeah basically what we're going to do then is we're just going to continue right so we're just going to continue the iteration because we know that we can burst this balloon with the same arrow that we have right now and then we're going to do is otherwise if we have a situation where it's not in the range then what we're going to do is we're going to increase right increment the arrow counts and then we're going to get the previous endpoint to be the current endpoint right so because we're starting a new uh arrow so we have to start a new endpoint then at the end all we are trying to do is we're trying to return number of error number of arrows that we need right in this case we just return arrow so to summarize basically we first we want to make sure if the current previous endpoint is actually within the range within the current balloon range right so balloon range if it is then we can just continue to use the same mirror otherwise we have to use a different arrow and have a different endpoints right so now let's try to run the code okay let's try to submit the code and here you can see we have our success so basically this is how we solve this problem by um using a n log in time complexity due to the sorting right sorting takes and log in time complexity and this is linear so login is bigger than linear so we have a log in time complexity so there you have it and thank you for watching
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
328
hi everyone get a solid question called old even like this uh so given single linked list one group all knows such order then the odd indexes will appear before all the even indexes now let's check the example one okay so example one here we see all nodes is one three five if we put these all nodes uh one side to be like this one connected to three connected to five right and if we put the even node because we know the even node two four the even nodes are will be like this and the final step is to connect the odd tail to the even head so you see it all here which will be five the event hand is true so can this find these two and get this and now we return the link this will be your result you see it correctly okay i think the problem description is quite straightforward and if you watch my previous english video i don't know okay i would prefer write the code on one side and display the graph join or underside now i'll explain the occult line by line accompanying the graph joint so uh let's put this coding path which i have right before recording this video on the left side and let's use this uh example for example one okay so here's example one we have a node one two three four right okay and let's use uh this yellow color for the order index one three five of the index and let's use the green column with even less two and four even index okay so the next step we want to check uh is to uh check the color cases right i should have finals so i think there's no need to check this qualification so just pass result and after the challenge quality just want to initialize all their hand it has even had a handle next so you can always have a head and one right so odd is actually at this relation let's use a different color okay so all is here and both even and even there are these two so even is here and given that let's use this eh and also here okay now finish that the next step is to go through this while look right and finally even then even though next we'll see this so next issue i check the odd it's one point all the next to even though next let's clean this all and connect this one to this one right and then want to move up to other next so i clean this off and write out here and after i want to check the even note so even though next is ordered next so i want to connect this one to uh this one right now finish that one to move even to even though next so clicking this all and right here okay now this is that i want to keep this while loop if the conditions to satisfy and focus in both even and even though next still exists so i want to continue this while loop right and the first thing to check okay order next equal to even dot x so clean this all and right here and move on to auto next just right now here okay then i want to solve for even right so even though next you know the next but all the next is not so just clean this off and write even though next maybe i'll connect it here because uh the end or the uh degrees in not and even set to even though next so clean this oh sorry uh just in this even knots not this slide okay and finally we check uh both even though next uh is now so we will break out this while loop and go to next step and next step to connect the odd tail to even head right so see the auto is actually defined because the old had arrived as a last all the index nodes and we want to connect this node to event we even have it still true right so let me just join here you see we're connected this file back to these two okay now uh this graph gets little message so i'll go through it from 1 and all the way to the end and let's see what it gets so it is level 1 and 1.x is 3 right and 3.x is 5. 1.x is 3 right and 3.x is 5. 1.x is 3 right and 3.x is 5. and final next is two right to the next is four and for the s now uh so it isn't split on this graph okay you see uh now get the correct result right okay now let's meet the codes it works okay you see the time capacity memory used in this solution is quite efficient right and the code is short in each of them if you find this video helpful or please like this video and subscribe to my channel thank you for watching and see you next time
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
77
and today we're going to solve another lead code problem that is combinations so in this one we are given two integers n and K and we have to return the possible combinations of K numbers chosen from the range 1 to n so what does that mean so we are given range from 1 to 4 so we have numbers like 1 2 3 4 and we have to make a pair of K elements that is two elements so what is the possibility what are the combinations we can have one two one comma two right we can choose one and three so we'll have one comma 3 we can also have one comma four then we'll start with two we cannot have 2 comma 1 because we already have one comma two that would not be a different combination so we can have 2 comma 3 right we can also have 2 comma 4 now let's move further from 3 we cannot have 3 comma 1 or 3 comma 2 because we already have one comma 3 and 2 comma 3 so we'll have 3 comma four and that's it these are all the combinations we can have from one to four of K as in two so that is our answer one comma two one comma three one comma four two three two four and three four so how are we gonna approach this problem here's a pretty basic problem we can use recursion to solve this problem so what we're gonna do we're gonna make a recursive method which takes that would be one because we have to find in we have to find we are given a range of 1 to n so I will in a recursive method will have start will have end as in and we will pass the K and we'll pass the empty list as well so in this one what is the what would be the base case when can we add anything to our result so initially we are passing our empty list so in the list we will keep on adding 1 comma two or one comma 3 so whenever we see a list dot size that is it contains one comma two if less dot size is equals to K we can add 1 comma 2 Al to our result right similarly whenever we get 1 comma 3 we can add it to our result so let's see the code and we will dry run to have a better understanding okay now like I said we are given and as in 4 and K is in 2. so first thing what we are going to do we're gonna create our result of list of lists because that is what we have to return then we are going to call a recursive method get subsets with start initially as one and as in k and is In N will pass k the result and an empty arraylist this one so now we know the base case would be whenever a list size is equal to equals to K we can add that list in our result so now let's drive around this code we have start initially as one end as in 4 in case two and our result is empty initially and so is our list right so now our list is listed size is equals to 2 why does not so we'll go to for Loop initially start is equals 1 and will always remain four that is 4 die plus so initially what we are going to do we're gonna add 1 to our list because I is 1. so 1 will be added to a list and we are going to recursively call this get subsets again with I plus 1 that means the start will change to 2 right now it is the list dot size list or sizes as of now 1 which is not equals to 2 so we'll go to this for Loop and start as to this time right Which is less than equals to 4 and we're going to add I to our list that is 2. so we have added 2 to our list and again we're gonna recursively call this get subsets with I plus 1 so I plus 1 will be 3 this time right now the list dot size it is true now so since it is 2 so we can add 1 comma 2 to our result right and then we will return since we are returning so we will move to this line and this will remove the last element from the list so we will remove 2 from our list right so now we will change we will go to this for loop again so I was 2 lasting so I will be 3. again we will add 3 to our list so our list would be 1 comma 3. right then we are going to call this recursive method again with I plus 1 we're gonna pass it to 4. right so but again our list dot size is equals to 2 so we can add it to the result array so after this we're gonna return again and we will remove the last element we'll remove three from the list and now since the I was 3 we will increment it to 4 is less than equal to 4 yes it is and we are going to add 4 to our list we will add four and again we are going to recursively call this method and 1 comma 4 that is the list so size again equals to 2 so we can add 1 comma 4 to our result right after returning we will remove this as well right so we have already reached 4 it will be incremented to 5 is not less than 4 so we will remove one as well from our list then we're gonna again run this for Loop recursively again and we will get 2 comma 3 and 3 comma 4 as well so yeah I hope you understand the solution thank you
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
1,704
let's go over question number 1704 determine if string halves are alike now the question says you are given a string s of even length so it's an even length split this string into two halves of equal length and then a be the first half and b be the second half two strings are alike if they have the same number of vowels so this is a key statement it's alike if it has same number of vowels and these are our vowels right we said s contains uppercase and lowercase letter so we have to count four cases where it's lowercase and case where it's upper return true if a and b are alike otherwise return false so if the number of vowels for right and left vowels are the same we are going to return true otherwise it's going to be false now let's look at our example one so all we have to do is we have to split this string in half so this is going to be left this is going to be right and for each character we have to check the number of vowels so for that we have one vowel which is an o and for right we have another o so left is equal to right so we return true for the second one we split over here and we have one val for the first half which is e and for the second one we have two which is two o so that's two right and does l equal to r no it doesn't so this is going to return false and we are going to do that for all the characters now i can think of two ways to do this well the first one is split the string into two so left and right and have a counter for left and right and check later is l equal to r and we just return this second one is well we do have to split left and right but we actually don't have to have a separate counter for left and right over here what we can do is we can just have one counter and set it if left has a vowel we can increase if right has a vowel we can decrease so if it was the case that they had the same number of vowels counter would evaluate to zero otherwise it's going to be some other number whether it's one or negative one but as long as counter is equal to zero that means that they have same number of vowels and then we can do something like return exclamation mark counter and if it was the case that counter evaluated to zero this exclamation mark zero would evaluate to true and that way we could get our answer 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 well actually all the solutions are going to have the same time and space complexity which is going to be of n for time and of 1 for space now as we discussed in our first part of this video what we can do is we can split our given string into two left and right halves and create two variables to store the count of the vowels so first i want to make a variable that stores all the vowels and that's going to be an array so a e i o u and we're gonna name it vowels okay that looks good and next i'm going to create a variable to store the left half of the string i'll name it left and this is going to be slice from index 0 to s dot length divided by 2 and we need the right side and let's name it right and we can just get rid of this one for the right one now let's just console log our left and right and you can see that we have our split string and remember that the question said we are always going to be given an even length of string okay so that looks good and now i want to iterate through my strings so 4 let i is equal to 0 and i is going to be less than well it's going to be less than s length divided by two because remember there is no reason to keep looping do the whole thing because we are splitting our string into half that means that we just have to iterate two times for the first one four times for the second one and so on and so forth and we're gonna increment i by one each time next i need to check well if my current character is a valve for the left i want to increase the left vowel count and if it's right i want to increase the vowel count for the right one so let's make two variables i'll call it left count and set this equal to zero and another one will be right count and this will also be zero now i need to check if my current shrink so it'll be left at index i dot we're going to convert this to lower case and we need to check if this lowercased letter is in our vowels array or that so in order to do that we're going to use vowels dot includes so what includes does is just should be vowels so what this does is we check well is this element or this character in our vowels array if it is this is gonna obviously evaluate the true and then we want to increase the left count right so we increment by one what if our right string or our current character at the right side of the string has a vowel well we need to increase the right count so we need pretty much the same statement so let's just copy this over and this time this is going to be right and this should be right count now let's just console log our left and right count so you can see that we have our number of vowels for our left side and the right side of the string for the first string we should have one each so one and one for the second one we're gonna have one and two so that's what we have and for the following ones we have one and two and one so that looks good right but we're not done yet we need to return a boolean value if they're equal to each other we're gonna return true if not we are going to return false so how do we handle that well what we can do is just return left count is equal to right count and as you can see we have our result so true false true which looks good now let's just go over our code one more time so we create an array to store our valves and we split our string into two halves which is going to be left and right and we make two variables to keep the count of the number of left vowels and the right vowels now we iterate through the array and we iterate until i is less than string dot length divided by two and the reason is because there is no reason to keep looping through when we have a split string and the next we check well does the current element that's lowercase in the values array if it is we're gonna increase the left count if the current right character is in the values array we're gonna increase the right count now you can actually just get rid of this lower case and just include capital letters for aeiou and that should work exactly the same way i just chose to leave it like this finally we check well is the count of left and right equal to each other if it is it's gonna return true if not it's going to return false now let's go over our second solution and our second solution is pretty much going to be the same as before but let's just try to implement the different so that we can you know just think more about the problem and then maybe just get better over time now for this one as we talked about in our intro video we're going to have just one counter that we are going to return later so we're not going to have a separate one for left and right so that does save us space just a little bit and remember how we sliced our string into two well this time we're not gonna do that we're just gonna instead of slicing we're just gonna look at the first one and the second one and compare the second one and the third one and then compare or check if it's a vowel so let's start coding i'm going to make a vowels string this time so it'll be a e i o u and this time i'm just going to put in the capital ones too just to switch things up a little and going to make a count variable now we need to iterate through our array so for let i is equal to zero and we're going to iterate as long as string dot length minus one minus i and increment by one each time now why didn't we just use string.length divided by two well to be string.length divided by two well to be string.length divided by two well to be honest you could have done that but i just want to use something different just for fun now if you don't know what this evaluates to so this is going to refer to the last character in the first iteration and then it's going to refer to the second to last character in the second iteration so as i increases this is going to decrease so now we need to check if files dot includes if the array or string includes my current character which is going to be represented by string at index i so that's the first character right if it includes that character what i want to do is i want to increase my count by one well what if it's the other case if my right side had the so this side right okay if my right side had a vowel i want to decrease my account so if vowels die includes string but this time the index is going to be different so index is going to be string dot length minus 1 minus i if that's the case we are going to decrement by one each time and again this index reverse starts at the last index and as i gets bigger it's going to get smaller by one each time so in the first iteration string at index i is going to evaluate to b and string at string length minus one minus i is going to be k and the second iteration this one is going string at index i is going to be o and second iteration this one is going to be the second o or the third element so you can just think of it as this one moves to the right this one moves to the left now what we need to do is we need to evaluate our account so return we're going to give an exclamation mark and before that let's just constantly count and you can see that we have 0 negative 1 and 0. so when it's 0 it 1 negative 1 and 0. so when it's 0 it means that it has same number of battles because if it had dials in the left one our count would increase if we had balance in the right one our count will decrease so meaning that if this increased by one and if this decreased by one we will have a count of zero which means that we have one vowels for each now we want to return our result so when it's zero that means that we want to return true right so if you don't know what exclamation does when we have a value in the exclamation it's going to give us a true or false value so 0 evaluates to false in javascript and 1 evaluates to true in javascript so if we were to give exclamation mark it's going to give us the opposite value so let's console log exclamation mark false that's going to give us true if you were to do exclamation mark zero that's also going to give us true so it's that logic and so we're going to return count here and we should get our result so we have true false posture which looks good and that's our solution if you guys find this helpful make sure you guys like and subscribe thanks
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
593
hey guys let's talk about problem from google which is known as valid square it's a medium level problem so we are given the coordinates of four points in 2d space p1 p2 p3 and p4 we need to return true if four points construct a square the coordinate of points p i is represented as x i and y i the input is not given in any order a valid square has four equal sides with positive length and four equal angles 90 degree angles this is a valid square this is a definition of a valid square which is given over here and we need to see that out of these four points we are only given four points and these four points should make up a valid square okay so we need to return true or false whether it is some valid square or not so how do we do this problem so we need to see the properties of the square so let's say we have a square like this let's say i have the point p0 p1 p2 and p3 so we have to check what are the properties of a valid square when we are trying to calculate it through the points we how many distances do we have so at any particular point we have a distance from over here to here from here to here and let's say we have a diagonal distance so we have a length a breadth and a diagonal from a particular point so this means that we will calculate the distance between p0 and p1 p0 and p3 and p0 and p2 to all of the three points but we can also calculate the distance from itself so this distance and this distance they are basically the same so let's call it as d1 okay and this distance we will call it as because this is a diagonal this will be d2 so one coordinate is giving us two distances two distinct distances to all other coordinates if we consider distance to itself as well then that would be a distance of zero so we have three distinct distances from one particular point right that will be d3 so this is one property that we can check that at any particular coordinate the total number of distances that would be formed would be either the distance to itself or the distance from the diagonal or the distance from the breath or the length so the total number of the distinct distances that we will be calculating from all these points would be three so we can check from p0 to p1 and p0 to p2 p0 to p3 and v0 to p0 and then we can do the same for p1 to p1 and then p1 to p2 and then p1 to p3 and p1 to v0 right so we can calculate but the answer would be the total amount of distinct distances would be 3 over here so we must be given 4 coordinates in this case which means that none of these coordinates should be duplicates because if we have duplicates then we only have three sides okay so if we have two zero zeros then we have only three points and that would form a triangle it won't form a square so there must be four coordinates and the total number of the distinct distances should be three if that condition is met it's a valid square so let's try to put this okay so let's first try to put all the points into a list we define a list points and we can just say p1 p2 p3 p4 right and now we will calculate the distances for a in points for b in points and then we can calculate our distances so this would be a 1 minus t 1 square of this plus a 0 minus b b0 square right and we can just say as result and we can say set of it so if this is a set then we will have all the distances we will only have the distinct distances by using the set right and then in the end we can just return if result is equal to three so there should be three distinct distances and the total number of the points should be four which means the length take out the set of the points but this is the points is basically a list so we cannot directly convert into the set so we have to convert it into the tuple first and this length if this is equal to 4 then we are done let's try to run this would be let's say i think we are missing this would be length of result because the length of is set it should be 3 i think that's what we are missing ok now it works let's try to submit this great it works so guys i hope you get the logic thank you very much for watching
Valid Square
valid-square
Given the coordinates of four points in 2D space `p1`, `p2`, `p3` and `p4`, return `true` _if the four points construct a square_. The coordinate of a point `pi` is represented as `[xi, yi]`. The input is **not** given in any order. A **valid square** has four equal sides with positive length and four equal angles (90-degree angles). **Example 1:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,1\] **Output:** true **Example 2:** **Input:** p1 = \[0,0\], p2 = \[1,1\], p3 = \[1,0\], p4 = \[0,12\] **Output:** false **Example 3:** **Input:** p1 = \[1,0\], p2 = \[-1,0\], p3 = \[0,1\], p4 = \[0,-1\] **Output:** true **Constraints:** * `p1.length == p2.length == p3.length == p4.length == 2` * `-104 <= xi, yi <= 104`
null
Math,Geometry
Medium
null
1,061
hello everyone welcome to algo simplified today we will be solving lead codes 1061 problem lexicographically smallest equivalent string now moving to the problem statement you are given two strings of the same length S1 and S2 and a string base Str we say S1 I and s2i are equivalent characters for example S1 equal to ABC S2 equal to C D E then we say equal to c b equal to n c equal to E equivalent characters also follow the usual rules reflexivity Symmetry transitivity and from this question we have to return the Legacy graphically smallest equivalent string of Base Str by using the equivalence information from S1 and S2 from the problem statement we are given two strings S1 and S2 for example in this example we are given A B C and C D E and we are given a base string Eed we have to find the lexicographically smallest equivalent string to the base string Eed based on the string S1 and S2 as we have we know that in the string so corresponding characters from both the strings are equal from the problem statement we can see so we can say that if the string a b c is there and C D E is there then a is equal to C D B is equal to d c is equivalent to E and we have to find the base string that is smallest equivalent so this is the problem statement that we are given in the question so let's move to some examples some example test cases to get a better understanding of the problem for like looking at the example one we see there is string S1 that is Parker S2 is Morris and base strs parser so as we are given the input Parker Morris and the base Str is parser so what we will do if we just group them like P and M are equivalent so just P and M are written here a and o are equivalent r is equivalent so okay no need to write it R and K are equivalent so UK R and K are equivalent e and I are equivalent and R and S is equivalent so this these two characters are equivalent so R and S are also equivalent from this we can say that these are the characters if we replace the uh if we replace each character of the base Str to the smallest equivalent then we can achieve this lexicographically smallest equivalent string okay so for every group if we see for this P and M the smallest character is m for this a and o the smallest one is a okay for R and K r k s we have the smallest one as K and for e and I we have the smallest one as e if we just replace P and M with m a o with a r or k or S with k e or I with e we can achieve the smallest lexical graphically possible string let's say p will be replaced with M A will be replaced with a r with replaced with k e s will be replaced with k e will be replaced with e and r will be replaced with k so we have achieved this smallest lexical graphically smallest equivalent string ok so for doing that we have just have to follow two steps find the smallest equivalent character of each string and replace each character of the base Str with its smallest equivalent character so the second one is just to replace this character within another character which is obviously simple and the first one is to find the smallest equivalent character of each string which we will be doing with the disjoint set data structure so let's move to the algorithm part so let me tell you about the disjoint set in this joint set it is basically a data structure through which we partition a set for example in this we have we can basically using this we can keep track of the connected components and in this problem we are dealing with the connected components since PM end is a connected component and O is a connected component R K and S is a connected component e and i this also forms a connected component what if in the next letter what if in the next ladder we find something like this like o and in this we find something like R if we find o and R it means this a o and rks these two different components now are the same components like these will be now these two components will become a single component and all these five characters will be equivalent now so to deal with this what we will do is in case if we have a component like we have a and we have o and these are connected and we have R we have K and we have S so basically we have K we have r we have S so these are connected and if we have to connect o and R then what we can do is in this component the smallest character is a and in this component the smallest one is K and in this is a so if we can connect this A and K then we can make all these five elements equivalent and connected through the disjoint set so if we just make these A and K connected then we can say okay now we this is connected and the smallest equivalent of O is a r is K and the smallest equivalent of K is a so in this way we can get the smallest equivalent character of each character so this will be done using disjoint set in this what we will do is we will initialize a create an array like parent array of all the elements and initialize it with the corresponding indexes like for the like 0 1 2 3 will be initialized for index 0 1 2 3. so in this way we will initialize it and we can say that the element 0 the element 1 the element 2 or the element 3 will have an have a parent that is it The Element itself and whenever we find we have to connect these two then we will just make the bigger one we will make the smaller one as the parent of the bigger one yeah you know like the bigger one will be acting as a connected component and the smaller one will become the parent but in this case as we have a lot of elements like R we have if we connect R and K since we know that r k is the parent of R but what if we connect A and R then K will no longer be the parent of are but we and if we make the pay r as a print of K then R will be k will be parent of itself but since it is connected so to deal with that problem we will be using path compression you will understand the path compression once I start explaining you okay so just to give you a better understanding of the problem let me dry run this for you okay so we have p m so what we will do is we will take P we will take M and we will make p as in the Index P we will make M as the parent of P so now we have p and the parent is m okay now we have a and o so we will take a and we will make o here now we know that the smaller one is the smaller character will be replaced in the base string so we will make o as a parent of yeah so we will make a as a parent of o now we have R and R so okay we have R but it is the parent of itself so it will now be the same then K and r so we have K and r so now we have k and we know that K is smaller so K will be the parent of r now we have e and I okay so we have e and I so we will just take e and I end e will be the parent of I now we have R and S so we have r and s now R and S for this we see that R is the smaller one so s will be the parent of r and R will be the parent of k so in this way we can say that s is the period of R and R is the parent of K so s is the parent of K but every time we cannot just assign directly like s will be the parent of K for this we will use path compression will be used for this thing in this what we will do is we use path compression so using path compression we will be able to assign this character to all the characters which it belongs as a smallest equivalent character like if K is the smallest one for all the connected components let me explain it with you an example like if we have this a this B and yeah a is a parent of B and C d e okay and now we find that B and D are connected like B and D are equivalent so we have to connect them but we won't just directly connect them as if we connect them then D B will be the parent of D and ok so we I've just made the if we just go without path compression what will happen let me show you what will happen is uh we will just make b as a parent of d and this will no longer exist here so what will happen D will be the parent of b will be the parent of a okay that's it's fine but c will be left alone but this C should be a part of this component this connected component and the parent of C should also be a so to deal with this problem what we are doing here is we are just making we are just connecting the parents at the end like the parents we will find the parents through path compression like okay D is okay the these parents whose these parents sees the D C is these parents okay B whose B is parent a is B's parents now once we reach the end like okay so a is parent is a itself and C is parent is C itself so okay we don't need to do anything we are at the we have reached the end so at A and C now we will connect these two so since a is smaller then C will become the child and a will become the parent okay so now if we try to search it through graph compression path compression we will find that these parent is A and B's parent is a and they both have the same parent so therefore they both are equivalent in this way we can check that those these two are equivalent also and we can replace the a character with the smallest equivalent character so that's how our algorithm works and after that we will replace it the base string with the smallest equivalent characters now coming to the code part in this we have two functions find parent and Union character find parent function is basically a path compression function through which we go to and elements parents parent like we move towards the parent until we reach a element which is its parent itself and this Union character is a method through which we assign the minimum value as the parent of the maximum value while connecting two characters for example if we are connecting a and B then we will make a B that is the minimum of two as the parent of the maximum of 2 that's what we are doing in this and now coming to the main function n is the size of the string we are making a array of size 26 which is parent array and initializing all the elements as the parent of itself now traversing through the array that is S1 and S2 VR taking the integer equivalent of those characters through zero based indexing and check if they both have the same parent or not if they don't have the same parent then we will connect them using the union care function as I have explained you this is just connecting the parent that we have found through path compression by making the smaller one as the child of the bigger one and now while traversing through the base Str string we will replace all the characters with the parent character and return the base string the time complexity will be as in this we are traversing it in constant time traversing this in n and calling the fine parent and Union care function which are also constant as their time complexity is 4 Alpha and traversing it the base Str in and the time complexity the overall time complexity will be big of n since we are creating a Vector which is of constant size and no other and a variable therefore the space complexity will be big of one that's all for the question
Lexicographically Smallest Equivalent String
number-of-valid-subarrays
You are given two strings of the same length `s1` and `s2` and a string `baseStr`. We say `s1[i]` and `s2[i]` are equivalent characters. * For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`. Equivalent characters follow the usual rules of any equivalence relation: * **Reflexivity:** `'a' == 'a'`. * **Symmetry:** `'a' == 'b'` implies `'b' == 'a'`. * **Transitivity:** `'a' == 'b'` and `'b' == 'c'` implies `'a' == 'c'`. For example, given the equivalency information from `s1 = "abc "` and `s2 = "cde "`, `"acd "` and `"aab "` are equivalent strings of `baseStr = "eed "`, and `"aab "` is the lexicographically smallest equivalent string of `baseStr`. Return _the lexicographically smallest equivalent string of_ `baseStr` _by using the equivalency information from_ `s1` _and_ `s2`. **Example 1:** **Input:** s1 = "parker ", s2 = "morris ", baseStr = "parser " **Output:** "makkek " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[m,p\], \[a,o\], \[k,r,s\], \[e,i\]. The characters in each group are equivalent and sorted in lexicographical order. So the answer is "makkek ". **Example 2:** **Input:** s1 = "hello ", s2 = "world ", baseStr = "hold " **Output:** "hdld " **Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[h,w\], \[d,e,o\], \[l,r\]. So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld ". **Example 3:** **Input:** s1 = "leetcode ", s2 = "programs ", baseStr = "sourcecode " **Output:** "aauaaaaada " **Explanation:** We group the equivalent characters in s1 and s2 as \[a,o,e,r,s,c\], \[l,p\], \[g,t\] and \[d,m\], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada ". **Constraints:** * `1 <= s1.length, s2.length, baseStr <= 1000` * `s1.length == s2.length` * `s1`, `s2`, and `baseStr` consist of lowercase English letters.
Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position.
Array,Stack,Monotonic Stack
Hard
2233
133
hey guys persistent programmer here and welcome back to my channel so in this channel we solve a lot of algorithms and go over legal questions so if you haven't subscribed already go ahead and hit the subscribe button smash that like button because that helps me create this content for you guys so without further ado let's go ahead and look at today's problem hey guys today we're looking at the question clone graph and we are given a graph like this and what we need to return is its deep copy so first of all i think the question doesn't really do a good job of explaining how the data structure is that is given to us so i will go ahead and explain that because that is a part that i didn't understand when i was trying to solve this question which is why it made it very hard and i had to reverse engineer after looking at the discussion forum so i'm doing this for you so you don't have to do that um so what we're given here essentially is a node right and we have this node one and we have this value so the node structure is um node.value um node.value um node.value and this is that the one and the note also has its neighbors so the representation of the neighbors are two and four here and these are again nodes right they're not just values so if i go to node.neighbors node.neighbors node.neighbors right i'm going to see a reference to this node 2 and to this node 4 and what this node holds two is its value right like so if i go to um one's neighbor at position zero here i will get i need to get the um and do dot value so i will get two and then if i look at um two's neighbors here i will see a list here in this node and in that list i will see the two's neighbors which is one and three right so i really like to understand how the node is given to us um you know in a data structure format like so that i can have some ideas to solve this problem so if you understand this structure i think breaking down the problem becomes a lot easier so all we need to do is clone one by one each of the nodes and their neighbors that's all we need to do right so here we can see choose neighbors are one and three and force neighbors here are so if i go to this once neighbor at the index one and so if i will get the value four and then we have within it its own structure right so force neighbors are again one and three and again these are also nodes so this reference here is referring to this one right and this reference here is num the three is reference saying the node three here so these are all references so the first thing we need to figure out is in order to copy a node first of all we need to create the reference create reference because you cannot um point to something that doesn't exist right so this is the first sort of like mental um leap you need to take to understand okay so first thing i need to do is create a reference and then the second thing i need to do is associate that reference okay um now i'm going to walk you through exactly how to do this so the first thing we need to do is have some kind of structure to organize what we are um converting from the old to new and obviously a dictionary comes in very handy because we can look at this one and see okay have we processed this are the clone created or not and if it is created then we are going to um just refer the neighbor otherwise what we need to do is step one this create the reference and then associate right so okay so i'm at one and this is the old value and what we need to do is we need to um create so i have not seen here new right so i'm going to create this one um and i need to create a space to store the neighbors right so we're going to follow the same data structure here so the node.value and node.neighbor so you the node.value and node.neighbor so you the node.value and node.neighbor so you can see that i did that here um right and after doing that we are also going to use a queue so we are going to put this in our queue so we can iterate over all the connected nodes like i need a way to go to the reference of one and then process it right so in the next step we're going to pop this out of the queue right we're going to pop this and here what we're going to do is process we're going to say okay um we are looking at currently once neighbors which are these nodes 2 and 4. now the question i need to ask myself is have i seen this 2 before in this mapping and no i haven't so there is no way i can refer something here that i have not seen so therefore we need to create this reference here two and we are going to initialize this to reference the same way we're going to create the value and then we're going to create the neighbor list and next what we're going to do is put this where we now have our reference to this is our reference right so we are we now need to put this associate this here so this is what we're doing in step two associate the reference right and then same thing with four and okay the next thing we also need to do is put this in the queue so we are going to put in two and we are going to put in four right because we again need to do the same thing with two and check if we have processed choose neighbors or not so once we are ensuring that all the references are created and the neighbors are associated that means we have created a clone of the graph okay so we will follow the same process as four here um when we are iterating over one's neighbors and we will refer this we will create this reference for right same way as we created two and we're going to refer this 4 here so that's done um so we have completely processed one now but our q is not empty right so we are going to iterate through this q and we will see okay next to process is two and what we're going to do is look at two's neighbors so what are two neighbors two's neighbor is one right and three so when we look at one here yes we have a reference so this is what we need we have a reference to this one and we know this because our dictionary is populated with this index one so what we're going to do is we're going to put this reference here right like we're going to put this refer this node to two's neighbors so we will put the one here um and then next we are going to look at three and three has not been processed yet so again we need to create that same structure for three so that three has the opportunity to have a reference and to have its neighbors populated so when we look at 3 here we have now created this reference 3 and we're going to put it here so this is two's reference one and three and they're both populated um so this note is done right and we have also put this three in the uh queue because it wasn't in it wasn't processed before its neighbors right so next we go to four here and we are going to look at what are four neighbors so fourth neighbors is one the node one and the node three and um when we look here we can see okay we do have an existing reference here of node one so we're going to put this pop this here so one and we don't need to add this to the queue because it's already processed and the dictionary is actually responsible to account for what we have processed what we have visited and fully taken care of and what we have not right so we have this reference here that is great and we have associated this so literally this these are the two main steps we're doing create the reference and associate so we're done with one and we're not going to pop this back into the queue because we've already processed this um and then it is time for three and we do have a reference to three because we created it earlier here so we're going to refer this three over here right um so this is complete now right and the last thing in the queue so we have processed all these numbers the last thing in the queue is this tweet and we can see okay we do have a reference for three and now we're exploring three's neighbors so what are three's neighbors are two and four and now we look at this map do we have a reference for two yes so we put it here do we have a reference for four yes we do so we put it here right and this is how we are transforming that old um index of each of the clone to the new mapping so this is what we need to return this same structure this index like this node here because this has all the references and all the connections we need um to create exactly a deep copy of our given graph okay i'm in the code now and the first thing i've done here is just return the node if the node is none um and then the next thing we need to do is initialize our old new dictionary so i will call this dictionary old new so it is very clear that we're mapping the old values indexed by the old values and then we are mapping them to the new node object so i will initialize this and let me set this to the first value so what we're going to do is here we're going to put the first node's value which is here in this case is one right um so i will get that so i will say first val equals node.vowel okay so we are going to index by this first vowel here so i'll copy this over and then say first vowel and what we need to assign this to is a new note because remember we're copying we're cloning this um original graph to the new graph so this is the old and then this is the new value so we will say who called this class here node so i'm going to instantiate an object here oh sorry drop none node and um i'm going to pass in the first value here first val and we will initialize its neighbors to a empty list so if i had to draw this it would be like one and then this one maps two um so this one is an integer here right because we want to index and keep track of what we have visited or not and this will map to this object so i just want to write this in a way where the data structure makes sense so it's easy to understand so it will map to this one and it will map to um that one's neighbors so it looks like this so this is how the object looks so if i had to get this new clones self.value it would give me a one and self.value it would give me a one and self.value it would give me a one and self.neighbors would give me an empty self.neighbors would give me an empty self.neighbors would give me an empty list so we're initializing these neighbors to empty and as we go through the queue we're going to start populating the neighbors okay so the next thing we need to do is initialize our q so call this q equals dq and then we'll push the node in there um so we have in our queue now the access to this first node here one okay so we're going to go through the queue so we'll say while q which means while q is not empty um what we want to do is we want to pop this out of the queue so to do that we can say this is the current node which is equal to q dot pop left okay so now we have access to this one and um what i'm going to do is also get access to this node that we initially created so to do that i'm just going to index access the index of this first value so what i'm doing here is saying all new add the index of card dot value so this will give me the access to this new node that we have created as a clone so we can call this um how do we want to say this we can call this current clone okay so currentclone is giving me access to this object and we want access to this because what we are going to do is populate these neighbors in this list okay so we want to iterate through all the neighbors of this current node so we're going to one's neighbor two and we're going to one's neighbor four so let's do this by saying for n where n is the neighbor in um car dot neighbors okay so the first value here is going to be um 2 right so we are looking at the node 2 here because remember when we're getting it out of the queue we're looking at um this node itself so we can go to one's neighbors which is in this neighbors list right so when we pop left we are going to access all the neighbors of this one by iterating over those neighbors okay so for n incur dot neighbors now we want to check first if this neighbor exists or not right because we cannot put a reference of a neighbor that doesn't exist so we will ch check if n dot value so we have our map here so currently the map only has one so if n.value not in one so if n.value not in one so if n.value not in old new then what we need to do is create that reference in the map first so what we need to do here is create this reference so we want to create this reference here 2 and we want to create this node with 2 and then we're going to go in and populate so first of all we need to create this reference right so we cannot refer something in the neighbor node if this node doesn't exist so that's the whole point of creating this second node okay so if it doesn't exist then what we're going to do is we are going to um add the index of the neighbor's value so in this case this is two sorry in this yeah in this case it is two so n dot value um is going to be we're going to set this equal to um and we're going to instantiate the object so we're going to call um the node class here so node and we are going to pass in that n dot value which is 2 and we are going to um initialize an empty list here so this is exactly what this step does and we are also going to append this to the queue so we can process this node next and fill up its neighbors so we're going to append um the note the whole note right so we're you're going to notice that we're indexing by the node value um and then this value has a this value holds that cloned object right okay but we're not done yet so now what we need to do is refer this node here this currently holds this value and now we're going to um populate this right so i can say in the current clone now we need to populate the neighbors so i will say current clone okay this needs to be indented here okay so currentclone.neighbors dot append okay and what do we need to append here we need to um append this to that we just created right so we are going to append that n neighbor sorry we need to append this old new value of this new neighbor so yeah we need to access basically this spot right so to access this spot we need to uh go to that index which is the choose index here that we just created and then access this okay and this is how we have now populated the two here and then in the next iteration because you remember one has two neighbors one and um two and four so in the next iteration it's going to populate the four right so this is how we are creating that neighbor relationship here so first it's going to create that node 4 um the same way we did with 2 and then it's going to go ahead and append that here into one's neighbors all right so this should do it um and what i'm going to do is return um okay so we do have access to the first node here right so we need to return this same structure back so i will say return the first value okay so this is what we need to return because this is this has all the relationships that we need to um need to send back so first value okay yeah i need to access this so i will say the first value in the old new um map right okay so we're going to return this okay so i hope you understand why we're doing this because we have access to this first note that we created which has all the relationships we need to return so this was confusing for me to understand first but what they want you to return is basically this structure where you know one has its neighbor two and four and then if you go into the two object you will see that two has its own neighbors so everything is um populated within this structure so that's why we're returning this all right let's give this a run okay awesome accepted
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
888
Will try 200 and the family has given hundreds in the description but Baghwa subscribe The Channel subscribe and subscribe the Channel subscribe Karna should subscribe 1000 will tell that it will need this much size and tell with tears how much it is The President Clan Minimum Return Even Attempted Guarantee If you understand what is happening with Dancer Express, then Edge has Abhilash Pandey ji's colors, they have got four sizes, so those who are coming, they will have to transfer something to each other, because after this, see this something. Subscribe Thank You That its relation is back to its face phone Some intermediate owner will have to come which if both are done then its size and in that I have given that what will you become Finally want to you Will go to the earthen pot That are all the way will go to one or two It means that I said come, I have given the answers here, now I have given another name, what kind of oily person has one or two and fast forward this is like we are applying more clean as if I am going to subscribe and share, then its. What will total relationship give to a human being, something else should also come, that is, hello and in this, what is the enjoyment through shares, share something to me through file messages that I had shared 721 shares in this, so I will add it to this and the limit of subscribe is It is certain that this post has been explained so much that how to free the letters, let's submit this question, which means that we have taken it well, I will subscribe in the rallies, I will join the belt in this pot, if you want, I will add you in a lot of water. Okay, I will add in Assam because I will give the meaning because see this, when I shift this message to, I will have to subscribe in front of it * I will have to do it again, I will have to meet again, * I will have to do it again, I will have to meet again, what will be the relation by presenting it in subscribe to and the relation to the campus will go again. At this time - you can follow for free, I am doing Surat porn difference, see now try to blow with candy in the list and try to make - no and try to make - no and try to make - no hello so if we see this 20 today the commission that we get for this eye lash Now what quantity am I cutting off? Picture verification quantity which is this different. Hello. If it is any of the two things then it means how to reduce. Let's see if it is explained to everyone. What does it mean if I am removing the candy because of this? Yes, you will have to subscribe for this, you will have to do this difference, listen to both the people present in the subscribe page properly and sorry for your peace of mind, if this IOS has candidates have one or two, if you have two and two, then take time to solve it. How much is that we, that is cat time, is it somewhere else or should we not use it in front of friends profile - why is the difference ok, so profile - why is the difference ok, so profile - why is the difference ok, so I said that if I subscribe lemon in it, then why will there be seven in it, there will be a cross in it too, I am I was seeing that it has definitely become that hero is equal mobile, which means we will have to share the candy from this, white chemist and we will have to share the size and we will not have to send the message, it is of force because both of our girls have to go to college, it is Pooja Ishq. That one thing they see and touch light is not like 12541 subscribe to a gradual hand answer five I come in this again sometime the roadways are different so I ignore these things you are doing a temporary calculation then I Now one point behind the neck and leave it here, at this time you would have found the difference between these two, today the fiber office is deprived of the same affection that I will add to it, okay, so let's look at it once, look at it two 200, take half an inch. What did I say, let's take out everything, now we will take out one more, that is, take out its length and then we will put it, then this will be another serial, now after that, we will take the candy of this Shankar, two, so this is the time of boxing contest, now it is After what I am doing was the point is Guddu the hero of investment and outside Star Plus then the points him is the loud size that Chetna searched means both of them are tweeting now what is the difference by subscribing to their element means and second - will always do I will do - will always do I will do - will always do I will do that if he is sick plus difference has to return the answer for proper protection then the answer will be in the form of sitting then the answer will fast Tatush I will do now what should I do eye lens element only to make happy Which is that till now Candy 's sex to beef, at that time I will give religion sugar, 's sex to beef, at that time I will give religion sugar, 's sex to beef, at that time I will give religion sugar, okay and where we reach here that we will meet sometime, I will give that after completing Sukma, two former MPs, here I have put plus minus here, P plus is to differentiate. Yes, we went to sleep and addressed, if we get robbed then I will get bloated here, my stomach will swell that means I.N. means we will start the website from here I.N. means we will start the website from here I.N. means we will start the website from here like this and like this is what we saw - Mountain is ours, don't this is what we saw - Mountain is ours, don't this is what we saw - Mountain is ours, don't science and our peer and - 110 science and our peer and - 110 science and our peer and - 110 We shampoo and see if it has happened, then it is a good meeting, its time complexity as we can see that and off and into a barbie woman world is you two because we are traveling completely to both the plates, 8 minutes so mode off and * I will turn off MB organ duty and special and * I will turn off MB organ duty and special and * I will turn off MB organ duty and special horoscope city mode because we have no expressway to understand all this.
Fair Candy Swap
mirror-reflection
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
Math,Geometry
Medium
null
845
Hello Illusion Cars Video Subscribe to Channel Properties Subscribe 4000 Videos That Hina Do and Science Questions Page Vote in Food Will Work Like a Middle Egg subscribe comment And subscribe The Amazing Subscribe Former MLA Anil Kumar subscribe and subscribe Maximum Volume Enrollment Question Lite subscribe Video Subscribe This Video Subscribe 4,320 I Will Have Account Periods Page Will Hold Up Account And The Number Of Way Raw Appointment 323 Subscribe Increasing And Decreasing In Sikar District Is The Means Of Length I One Should Be Sealed And Will Simply Result A View To Find The Increasing Sequence Will Have Pimple Points 244 Ki Look To Phir Der In Aankhon Me Zoom subscribe The Amazing spider-man 2 Hai Vinati Mandir Ji And Account Next Video Subscribe The Amazing spider-man Three Idiots Subscribe spider-man Three Idiots Subscribe spider-man Three Idiots Subscribe To Donate Without Air Decrement The j point next point mintu subscribe for More Video subscribe have a wedding night result for 10 minutes for report subscribe definitely oil increasing the expert ring wrong result because you have put in condition electronic media subscribe to that noida that noida that noida New Delhi Se Implicit Flag That true nowhere in the swing of the election 2014 That belt without earth height result spoon scored my tablet organization finance corporation's pimples complexities of problems with all subscribe result subscribe to subscribe our
Longest Mountain in Array
longest-mountain-in-array
You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some index `i` (**0-indexed**) with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given an integer array `arr`, return _the length of the longest subarray, which is a mountain_. Return `0` if there is no mountain subarray. **Example 1:** **Input:** arr = \[2,1,4,7,3,2,5\] **Output:** 5 **Explanation:** The largest mountain is \[1,4,7,3,2\] which has length 5. **Example 2:** **Input:** arr = \[2,2,2\] **Output:** 0 **Explanation:** There is no mountain. **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 104` **Follow up:** * Can you solve it using only one pass? * Can you solve it in `O(1)` space?
null
null
Medium
null
1,760
hey there everyone welcome back to lead coding so we are in the middle of the contest number 228 and this is the problem number three i'm making this video so that i can upload it as soon as the contest is over so during the contest i have come up with one of the solutions to this problem and i will explain you the intuition behind coming up with that solution also if you know a better solution please let me know in the comments so we are given a numbers array nums where the ith bag contains the number eyeballs you are also given an integer max operations you can perform the following number of operations at most max operations time so take bag of balls and divide it into two bags with a positive number of balls for example if we have five balls then we can divide it into four and one or we can divide into two and three your penalty is maximum number of balls in a bag you want to minimize your penalty after the operations okay so we have to return the answer now let me explain you with an example here so here we are given an array with a size one and maximum operations are two so nine balls can be divided into six and three using one operation and then six can be divided into three and three using the second operation so we used two operations and now this is the array that we have three so the maximum element in this array is three that's why we are written in three as the answer all right now let us look at another example so here we have the next example in this one i think the maximum operations allowed are four okay so let us say we want to make the maximum element of this array to be two so this is already two for four we need to split it so how are we going to split four two and two it will take one operation here then we will split eight into two and two this is how we split eight and the number of operations used here are three and this is already two so total we used four operations and we made all the elements as 2. so the final array will be 2 8 times this is the final array that we have so we were given 4 number of operations and that is why the size of the array that we generated here is equal to the original size plus the number of operations so if we have x operations then the size of the array that will be generated will be the original size of the area given to us plus x that we can see simply with the help of this example and the other examples now the question is how to figure out that what should be the allowed maximum size all right let us look at another example here so here let us say the allowed maximum size is let me consider it as 10 okay so 10 is the allowed maximum size now this is already smaller than 10 so don't worry about this one come to this now can we split 17 into in such a way that the maximum element is 10 so we can split it as 10 and 7 it is going to take one operation and how many operations are there we are allowed to have two operations so in one operation we made it into 7 10 and 1 and i think this satisfies our condition the maximum element is 10 so we are good to go with your operation but what we are but we are not going to stop we will reduce 10 and we will try to make the maximum element as 9. so this one 7 is already less than 9 so don't worry about this 17 you can split it as 9 and 8 okay so how many operations did it take it took one operation again and we are given that we can use two operations at most so this is also satisfied now we will try to reduce nine also we will try to see if we can make the maximum element as eight so this one is already less than eight this one we can split it as eight and nine and to nine we can again split it as eight and one so the final area is going to be seven eight and one and the maximum element in this array is eight which is which satisfies our condition and we used how many operations in this case we used two operations and we are allowed that we can use at most two operations so 8 is also satisfied now we will try to reduce this further because we want the answer to be minimum we will try to reduce it further now we will try to make the maximum element as seven so this is already seven don't worry about this one you can split it as seven and ten and to 10 you can again split it as 7 and 3. now the final array is 7 and 3. this is the final array and how many operations did we used two number of operations is why the size of the final array is 4 2 because of the operations and 2 because of this original array so now we were able to satisfy this condition as well so 7 is the minimum till now we will further try to reduce this and this time let us say the maximum element that i will allow in this array is 6 so to 7 i can split as 6 and 1 now to 17 i can split it as 6 and 11 now to 11 i will again have to split it as 6 and 5. so the final array that we have is 6 1 6 and 5 but in this to jump but to generate this array i used three number of operations and i am allowed to only use two number of operations that is why i cannot go further so six is something that i cannot achieve and anything less than six is also not achievable so here i will stop and i will return the answer as seven so in this example i started with nine or ten but to generalize the solution i will have to start with a large number so let us say i started with a very large number maybe 10 raised to the power four or five then i will try to see that using the given number of operations can i make the largest element of the given array as smaller than or equal to the given number so if i am able to do that i will try to reduce the number that i am using so i will try to reduce it i will be using 9999 and if i will be able to satisfy this one as well then 9998 and so on till the time we are able to satisfy so this is called linear searching the solution so we are doing a linear search here we are starting with a large number and then we are trying to reduce it one by one this is called linear searching so instead of linear searching we can use a binary search here so that is the optimization here we can use a binary search instead of linear search so how can we do that let me just show you so i'm starting with s is equal to 1 and n is equal to int max while start is smaller than equal to end also those who don't know what binary search is i have created a very good lecture in binary search the link i will provide in the description you can go to that lecture there will be theory then there will be some solved questions as well so you can first do binary search and then come back to solve this problem so here it will be m is going to be our mid it will be start plus and minus star divided by 2. now i will try to check the condition so m is the allowed maximum number right so i am passing m nums and the operations let me just rename this as o so what is the check condition is the maximum allowed number is m so can we make all the numbers in nums smaller than or equal to m using o number of operations so that is the check condition i will write the check condition here bool check the first is the integer m then the second is the vector of int nums then it is o the allowed operations so i will be going to each of the elements one by one where n is num star size so if the element is already smaller than m then we can simply skip it but if it is not smaller than m so in this example if i am taking m as let us say 2 so i will be coming to 4 and i will have to split it because this is something greater than 2 and the maximum allowed element is two so how can we split four so i will have to split four s two and two okay and when i come to it i will have to split eight as two and two so here i am using one operation here i am using two operations basically i will have to divide this number by 2 so 4 divided by 2 is 2 minus 1 these many operations i will have to use similarly with 8 divided by 2 is 4 minus 1 3 operations i will have to use i hope it is clear i will take another example to explain this let us say the allowed maximum number i am taking here is 3 so m is equal to 3 now i will have to see which all numbers are greater than three so four is greater than three so i will have to split four in such a way that the maximum number is three so i can split it as three and one eight i can split address three and two so in this case i'm using 4 divided by 3 that is 1 operation and here i'm using 8 divided by 3 that is 2 number of operations all right so i will just write it in terms of mathematics how many operations are we using we are using nums of i divided by m number of operations these many operations we are using here o minus equal to these many operations in case we have a remainder okay and if we don't have a remainder then if nums of i modulo m is equal to 0 in this case i will just increment an operation so basically when we were having m s 2 then 8 divided by 2 is 4 so 4 minus 1 operations we were using right so that is why we are incrementing the allowed operations here i hope it is understandable so finally if o is greater than or equal to 0 then we can return true from here otherwise we can return false so we can simply return o is greater than equal to 0 if it is true then mid is one of the possibility so answer is equal to mid so if this check condition is giving us true it means we can allow the maximum element to be m so we will further try to reduce this m so that we can do it like this e is equal to mid minus 1 if m doesn't satisfy the condition then we are taking m too low so for that i will have to increment m that i can do this with the help of s is equal to mid plus 1 this is how we do binary search right then finally i can return the answer while and let me create the answer over here let me try to run this to see if there are any errors so i think it is giving us correct answer let me try to submit this now and it got accepted so talking about the space complexity are we using any extra space here so we are not creating any extra vector we are just creating few variables so we are not using extra space what is the time complexity so the time complexity is going to be because of this while loop because of this binary search and the check condition for each iteration of this binary search so the check condition is going to be big o of n because we are going to each of these elements one by one so let me explain you the time complexity here int max we are doing a binary search on into max this is the maximum element so the logarithm of this log with base 2 of into max is going to be the complexity for the while loops and in each iteration of the while loop i am using another big o of n so multiplied by big o of n so this is the overall complexity that is basically big o of n log into max this is the complexity all right so i hope you understand this solution if you like the video make sure to hit that like button and make sure to subscribe to the channel if you want more such content in future i am also making a really good series for beginners for the interview preparations if you haven't seen that the link is in the description as well thank you
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
84
Hello Hi Everyone Welcome to my channel it's all the problem large rectangle in histogram given in the winters representing district where do I am with which would find the area of ​​rectangle example subscribe like no one will start from which country from subscribe after subscribe and Share and subscirbe 21 20130 spider-man press six starting from spider-man press six starting from spider-man press six starting from the first ver and considering all the words which will become the maximum area will get 6 knowledge from distant from years and right side this will give us maximum fine subsidy 506 will start from subscribe maximum of all Possible in this approve will start from display board the length of the states which starts from side will start from IIM co of the land of blood and every time below you starting from minimum of point of which animal update minimum method the previous main like Minimum light on this is it from minimum height * The topic of the environment it from minimum height * The topic of the environment it from minimum height * The topic of the environment like Amazon in height Vijay beach fennel chief will update and local area Nigeria this will see this is height in 2G - five plus one this is height in 2G - five plus one this is height in 2G - five plus one class ninth class 10th take and first classy all your worries According element subscribe like maximum and computing for every year updating start from eyes pakistan from online and will update the maximum age and electronics show the time complexity Veeravikram Square and Distinct subscribe The Amazing and do the thing will have to use divide kar approach will start from Starting from 8am depending - 121 depending - 121 depending - 121 ki vinod minimum of this vipin minimum viral height of the minimum bar bank will be sharing comment like this minimum is a given for not effective sharing one for all the year award show the number of bars is light and - award show the number of bars is light and - award show the number of bars is light and - start Plus Ones Were Considered 110 Method Number Of Beneficial If White 3006 To The Meaning Of This Is Not Forget What Will U Will Smith And David Share And subscribe The Amazing Starting From That Some Idiots Virvansh Divide Like This Point Histogram One Side Program Maximum From This Setting Open quiet six and election from the dal refit ordination from this point subscribe devices great lakes in the list of this great astrology mill beau 20 condition for the ship videos histogram invite oo want oo from within minutes and a shoulder result porn video android implement a very Good read by Sohail Jakod What will be started from the full are luxury all in the cases when stars meet and will return to BDO Sudhir will be no other wise left otherwise will find the index of the minimum so here in this example which will be A First Year Running Is Sudhir Will Win This Can He Be Maximum Id From Being All The Bodies Including Also Minimum In Next Saunf Balbir Hydro Power Rectangle And With This And Minus Plus One Swadesh And This Front Part Of The Height Regulator Reforms For The End Of The Life Will Be Media Management and Defense Staff The Right for These Means Express Will Reconsider Equal This and Will Get Concrete and 3D Max and Absorb Tight Not Vidhi Time Complexity of This Nation Can See in Average This Time Complexity of Dissolution Will Be O Off Login Voice of Baroda Every Time Difference Perfectly Jeevan The Like Share Balance Like Share and Subscribe Divide subscribe and subscribe the Channel and subscribe this After Increasing Your Daughter and Subscribe Know How to Solve This Problem and Very Easy Apni Previous Explained in Interviews Well But Can We Do It In Motion For The Let's Understand Your Information How We Can Do It In Fans To Solve Video Like Trying To Find And Every Time Might And Take All Possible Rectangle Updater Maximum Area Will Not For Every Time They Will Keep Track Of B Id M Id wood for calculation - 110 Of B Id M Id wood for calculation - 110 Of B Id M Id wood for calculation - 110 003 - - - 121 is 003 - - - 121 is 003 - - - 121 is this the index chanakya ne service tax know what will oo where is the k effective nautical miles 250 km will be first hai next 9 news room for i20 will start from the length of the like this From the element and avoid not - 19 - 110 avoid not - 19 - 110 avoid not - 19 - 110 16 First Grade Teacher Elements - Vijay D 16 First Grade Teacher Elements - Vijay D 16 First Grade Teacher Elements - Vijay D Nurses And nowhere in the process in which we will not have riched it is not mine in this whole of power strength and its identity and what is the height and peacock power Stocks for This is Start Places with Extracts Start Peeth Element Effective Screen Incomplete Side Effects in the Case of Getting New Minimum Element in Array Element Calculate Area from All Possible Ways Central Districts Will Start from This Will Stop This Element This is Not - - Verb - One end Element This is Not - - Verb - One end Element This is Not - - Verb - One end elements which element of water element is after any content which app is water intake will halve the bill of processing fees will come hair consideration for display subah height is vansh with it will take this element first and will calculate one Message also start pick element height and you will be chief - dip index of clans be chief - dip index of clans be chief - dip index of clans element filter element of this element - not and - not and - not and minus one prosperity our video development element is - meetings will find her strong element is - meetings will find her strong element is - meetings will find her strong benefit from this area to the maximum global to The End Of The Year To India Channel Subscribe And Share Subscribe And You Will Be Amazed And Tagged Idi From 98100 And Research Height Not Like This Yes Dhan I Plus And They Also Create Available Mexico Real Life Will Be Tracked Dual Maximum Alien Life From 09 will right boil district headquarters at that is not equal to minus one Snowden to Russia - 110 The height of India height of track Russia - 110 The height of India height of track Russia - 110 The height of India height of track dot element is grated in the request to the height of power of development in that case will find out which will be The height of start element Swift element is set to minimum the will also will start to love and updated on voice messages dawai maths dot mix of max india itself and area which is calculated from which Google will give and after that will guide you new index i * will guide you new index i * will guide you new index i * Duration Effects Will Dare Subscribe Now To Receive And Also In The Elements To Elementary Middle He Decided To Write On A Message Apni Height Don't Like And Which Is The Largest Tatloo Jaayenge In The Moral Limit Subscribe Our Channel Subscribe To Hai So Let's Compile Record That NCC Cadets Walking Dead Try Maximum By The Way Effigy Of Rectangle Election Maximum Sharing The Year Will Put Her Will Get 9 6 And Subscribe That Retail Pack Shirt Election Can See Bear Running Swine Flu Cases And Distinct Came In Verse Can Be Possible For Its Earliest Se Subscribe this All in increasing order Android's This is the child will not be torn down Its soul will take only after some time and space complexities of soul Like Share and Subscribe My Channel and Option A Rectangle in the Matrix Very Thanks for Watching
Largest Rectangle in Histogram
largest-rectangle-in-histogram
Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_. **Example 1:** **Input:** heights = \[2,1,5,6,2,3\] **Output:** 10 **Explanation:** The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units. **Example 2:** **Input:** heights = \[2,4\] **Output:** 4 **Constraints:** * `1 <= heights.length <= 105` * `0 <= heights[i] <= 104`
null
Array,Stack,Monotonic Stack
Hard
85,1918
70
hi guys hope you are doing great a today's question is climbing stairs it's an easy question but it's a dynamic programming question and a very good one to just understand a lot of questions were just submitted to this alright so you are climbing a staircase it takes n steps to reach to the top each time you can either climb one or two steps in how many distinct ways can you climb to the top so this is really important to know that it's not asking us in how many steps you can climb to the top it is asking us in how many distinct ways we can climb to the top note given n will be a positive integer so base case ruled out so the first example is input is given 2 so you can either take one step at a time or you can take one single step which will cover two steps and that's why there are two different ways you can reach to the top which is two steps right similarly if the input is 3 that is you have to take three steps in total you can either take one three steps in totality or you can take one step and then basically two steps in one go or you can take two steps first and then one in one so these are the three ways you can reach the top okay so here there is no slide where I can show you the different ways of solving this question because there is no data structure in this question and it's actually a very known classic example of dynamic programming so we'll just see how the solution works right so first thing to note about this is that we are given that we want to find so we can either take one or two steps right so if let's say you to reach to the third step right the total number of ways you can reach the third step would be the number of ways you can reach the second step plus the different number of ways you can reach the first step because from here you can reach to the third step so only from first and second you can reach to third right or let's say for another example if you are at the fifth step then what are the different number of ways in which you can reach at the third step and the number of ways in which you can preach at the fourth step right so because you can take either one step from fourth to fifth or you can take two steps from third to fifth that is the only option that we have according to this question right so we just have to basically for every element or every stair or every step we have to take a summation of the number of ways in which we can go to the N minus 1 one in step and n minus two it step right so keeping that in mind so if we take an array right there is nothing like the zero at step right its first second third and so on so that's why we will take one extra value and basically the length of the DP array that we will use will be one more because there is no information applicable to this logic which we can use for DP of 0 right so we'll just create a array okay which size will be n plus 1 okay sorry what am i doing okay and DP of 0 equals to 1 I mean it's actually no value we just assign it 1 and one more reason is that when we have to calculate the value for 2 and we want to subtract to my s 1 &amp; 2 minus 2 so 0 will be taken into s 1 &amp; 2 minus 2 so 0 will be taken into s 1 &amp; 2 minus 2 so 0 will be taken into consideration and that is why we wanted to be 1 because there can be two ways to reach to the second step right also DP of 1 will be 1 because we know for the first step there is only one way to reach that is by taking one step so this is also quite explicit ok now we start right so we start from I equals two is less than equal to the N right we want to go till n because our DP is n plus 1 right and I plus and DP of n is also what we want to return right because T P of n will tell us the number of steps required to reach n ok so now it gets like really simple DP of I is equal to DP of I minus 1 plus DP of I minus 2 right and then we just say okay return DP of that's all let's see if this runs mm-hmm so in the meanwhile the time complexity for this will be typically dynamic programs they tend to have both n square time complexities but in this case since we have just travels like n elements you know for loop it is o of n and the space complexity would also be O of n because we're using a DP of size n right so yeah so it's both o of n time and space complexity I really wish this connects all right so let's just try to refresh this and see it works thank you okay that's something like this fine okay so I hope this helps you with the concept of dynamic programming and if it helps you please like share and subscribe keep holding and take care guys you
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
926
hello everyone welcome to our channel kodu sunny and in this video i will be talking about a simple problem flip strength to monotone increasing its index is nine to six and it is a medium type problem the liquid okay so this problem basically has like a dynamic programming approach you need to store the frequency of prefix like frequency of number of ones like from the suffix side light from the back side of this adding okay you can store from the front like from the beginning of this array but you can store from the back side also like for now in this video i have explained the o of n time and o of one space solution okay so let's move further to understand this problem first a binary string is a monotone increasing if it consists of some number of zeros possibly none followed by some number of ones possibly none okay so we would be given a binary string it means that every character is either a zero or a one okay and uh it is a monotone increasing if and only if we have some sequence of zeros followed by some sequence of ones okay i will explain it out with the help of examples if you are not understanding this right now no need to worry about now you we have been given a binary string s and we can flip as i changing it from zero to one or from one to zero okay so we can change any character from zero to one or from one to zero as we want and we have to return the minimum number of flips to make s a monotone increasing like a monotone increasing binary string we have to make by doing minimum number of flips okay so what we are going to do over here we are going to check it out all possible cases and take the minimum answer if you're not going to understand this right now again i'm saying have patience and just to go on through this video okay so we begin this example i will talk about all these examples first let's look over the constraints first you can see string length is like 10 power 5 so it means that you cannot have uh like o of n square approach or something like that so you must think for o of n log n solution or o of n if it is possible so in this video i will be talking about of end time solution and oauth 1 space solution in which how i can get the minimum number of flips needed to convert the given binary string into a monotone increasing like a sequence of zeros followed by a sequence of ones how we are going to do that let's understand this problem with the help of examples okay so let's move further okay so let us take an example like let me pick up from here like triple zero double one followed by again triple zero okay now our c uh binary string is called a monotone string if and only if like suppose we have some binary string like s1 s2 s3 s4 and s5 okay now let me call it as a binary string where the characters are having like in a monotonic increasing type a monotone increasing binary string is such that suppose we have some characters from s1 to s3 followed by some characters s4 to s5 note that i am doing like that because these all characters are of same type like s1 s2 and s3 are of same type and s1 must be exactly equal to 0 also as i've already said s1 must be equal to okay so let me write down clearly s2 and s2 must be equal to s3 and these all characters are same and it is zero followed by some another character which is not equal to this zero that is it is a binary string so i am talking about s4 exactly equal to s5 note that these characters are also equal and it is exactly equal to the character one okay so it means that it is a monotone increasing binary string if and only suppose we have some amount of zeros followed by some amount of ones so this is a monotone increasing binary string and also as given in the problem statement possibly none also like we can have all the ones or we can also have the all the zeros you need to be very much careful about these two corner cases okay so suppose we have been given you know this string as i've already said then what is the minimum number of clips required to convert this string to a monotone increasing binary string a flip is going to be defined as change this 0 to this one so the new string would become this type right or if you're flipping at zero right now or suppose you're flipping into one so the string would becomes like this type okay so this is the our new string so what we are going to do is we are going to check it out all possible cases for the corner cases like all ones like we have this one what we are going to do is we are going to flip all the zeros you can see to make all the characters as one we need to flip all the zeros to 1 okay so in this case our answer is number of zeros okay so let me explain it in other words if we want every character as one we need to flip every zero character that is present in this original string to character one that is we require a flip to convert a zero to one in this case our answer is like zeros okay this can be our minimum answer but this is not a minimum okay and what about the case when every character becomes zero like this type in this case you need to flip all the ones that is already present in our original string to zero so in this case uh your answer would be like once the count of ones okay so what i am going to do is i am going to initialize my answer as this can be minimum of number of ones that is present in our string or number of zeros that is present in our string okay now you can see that i can write this zeros term as string length okay i can write this term with n minus where n is the string length minus number of ones okay this is the simplified term okay so to handle the corner cases what i am going to do is like i am going to initialize my answer with this term okay now the very important thing is like how to find out the answer like minimum answer for all the cases okay so let's take this string like as of previous one okay now as i've already said the definition of monotone increasing binary string is like we have some sequence of zeros followed by some sequence of ones okay so we will check it out all possible cases like uh suppose here like this is the tub you can also understand this as the tub like we have a sub string starting from the index equal to zero and up to index equal to i we are just assuming that these all characters are 0 okay like if you're not understanding this let me introduce with another term like suppose so i'm talking about this i equal to 0 so it means that i am just assuming that what about if all the characters from index equal to 0 up to index equal to i both inclusive becomes 0 okay followed by all the characters which becomes 1 it means that i am just saying that suppose i am just assuming that from index equal to 0 up to this index all the characters become 0 and all the other characters right after that becomes 1 so in this case what is your answer what is your current answer to change your current string to this format of string in this case you need to find out the answers efficiently okay and like this is not one of the case we need to check it out all the cases like as i've already said it is for i equal to zero suppose i equal to 1 like i am assuming that all the characters from index equal to 0 up to index equal to i would become 0 and all the rest of the characters should become 1 in that case what is your current answer ok there might be some more cases like i becomes this one and the rest of becomes 1 like we have some 0 and here it becomes 1 what is your current answer in this case if you assume the orientation of the string like this one so in this case you need to change this one to zero as you can see in this case also you need to change this zero to one you need to do three flip operations in the right side part and one flip operation to the left side part okay now the thing is like we need to traverse i from every position from index equal to zero up to the last index okay now for a particular index how we are going to find out the current answer in like in of one time okay so for that you need to have some like a free calculation and the pre calculation is like you need to know the number of ones that is present in the entire string okay let's call it as o-n-e-s string okay let's call it as o-n-e-s string okay let's call it as o-n-e-s this is a variable okay now for answering a particular state like suppose we need to answer for this state okay then what we are going to do we are also maintaining uh let's say now variable which is going to be initialized with zero and at the particular state order you can set a particular index i when we try to find out the minimum like current answer for the ith state we need to know the now variable where now variable is going to store the number of ones that is present in the substring starting from index equal to zero up to the current index okay now if i am at this state like we have two partitions over here you can see this one and this one if i'm at this state now variable will be stored the number of ones that is present in the substring is starting from zero up to the current index i which is number of once it's only one so now variable will store the current value as one okay note that now variable will be initialized with zero when we start iterating from the beginning of the string and also we have some once variable also okay now we need to find out the current answer okay so current answer is like we need to find out the flips that is being required and we want this string as our final string in the required format where you can see this is the string which is a binary string and in a monotonic increasing fashion now what we are going to do is we are going to flip all those ones like for the substring 0 to i we need to flip all the ones to 0 and the number of ones is being stored by this now variable so my current answer would become now plus note that now stores the number of characters which are 1 in the prefix from 0 to i and we need to flip all those ones so that it becomes zero like this type okay and also we need to flip all those zeros to the right of this i like from i plus one to the last index we need to flip all those zeros to once so that it would become like this type okay so how to find that efficiently okay so you can see that 9 minus i minus 1 is the remaining like length of the string okay and if we subtract it out number of ones that is the present in the right side part then what will happen is like you can see once is the total number of months minus the current once that is present in the prefix if you sub cracked it out then we are left with the number of ones that is present in the right side part so it will be like once minus now so this is your current answer and you need to find this answer for every i from starting from 0 to the end of the string and find out the minimum take minimum with this current variable every time after finding your current state of the answer okay so let's head over to the code to find out the implementation okay so let's look over the code like i submitted the i don't know like many times okay so 32 i messed with 28 ms also i have the code okay so what i have done is like i have taken ns strings length okay so let me just zoom it out yeah it is fine i think yeah it's visible now okay so and it strings length and first i will count down all the number of ones present in the string and first find out the minimum of this ones and n minus ones because like every character can be like all the characters are one or all the characters can be zero in that case i need to flip all the like all the zeros to ones and all the ones to zeros respectively now it's going to show the number of ones present in the prefix from zero to i now when we encounter the one character one i will increment my this variable okay now first like we need to find out the answer for the current state it will like now plus the remaining length minus once minus now like first term is like now is like number of once that is present in the prefix we need to flip all that to make it zero and for the remaining part we need to flip all the zeros to once and it will it is going to be calculated by the length of the remaining part minus number of ones that is present in the right part so it could give the number of zeros find out the minimum answer just print it will give you all test cases first so if you have any doubts do let me know in the comment section of the video and i will ask the viewers to like this video share this video and do subscribe to youtube channel for latest updates thank you for watching this video
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
168
so our today's problem is L code 168 Excel sheet column title it is a easy level problem and it consists of topics such as math and string it is asked in only single company Amazon in last few six month here we are given with the integer column number and we have to return a corresponding column title as it appear in our Excel sheet we all know that when we open Excel sheet we start with the letter A H and we have 26 alphabets in our Excel sheet which means Z up to zed so we have written a position equal to 1 and our Z position equal to 6 and similarly for B position two C position it is three when uh we want to exceed our Excel seed we will be representing r a character as 27 because after 26 we after Z we will be again starting with our same character first character which is a but we have already assigned a value for our a equal to 1 so we will be using a = to 27 to 1 so we will be using a = to 27 to 1 so we will be using a = to 27 similarly we will be doing it for all the permutation of a then we will be doing with all the permutation of B then we will be doing with C up to z so in our example one we are given with an input integer which is column number and we will be converting it to corresponding column in our Excel form so we here we are given with an column number which is one and we know that the position for our column number one in our Excel form is one uh a so we will be wring our output a here in our example two we are given with an integer which is 28 we have we know we have only 26 character uh in our alphabets so we will be checking all the permutations for our uh alphabet a and we'll be wring an output which is AB here you can check that we have only 26 character in our alphabet alphabets so we have checked all the permutation for our AA which is AA equal to 27 then we will be checking for AB which is 28 because we here we are given with an integer which is 28 so we'll be wring our output which is a equal to uh 28 equal to a similarly we will be doing it for uh 701 if our 71 number match with any permutation uh in our alphabet so we will be wring its output uh which is zy so let's write our code so you'll be getting it more clear first we will be initializing a string variable named result initially this variable will be empty because in this variable we'll be storing all the values of our converted column number now we'll be writing a while loop for our column number greater than zero this Loop will be continuing until our column number is greater than zero inside it we will be decrementing our column number because our Excel start from number one but our indices start from zero Vector character letter equal to a here we have taken character a because we start our alphabets from character a plus column number / 26 because there a plus column number / 26 because there a plus column number / 26 because there are total 26 character in alphabets and to know its position we will be dividing our character with 26 now we will be adding result of our character letter a and a result of string in our variable result column number divide by 26 that means we are dividing our column number by 26 and shifting its value to right position by one digit at the end we will be wring our result let's check our code we have some corrections let us run our code yes our code is accepted for all the cases let us submit code
Excel Sheet Column Title
excel-sheet-column-title
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnNumber = 1 **Output:** "A " **Example 2:** **Input:** columnNumber = 28 **Output:** "AB " **Example 3:** **Input:** columnNumber = 701 **Output:** "ZY " **Constraints:** * `1 <= columnNumber <= 231 - 1`
null
Math,String
Easy
171,2304
1,266
Hello everyone welcome to my channel quote sir with mike so today we are going to do video number 17 of the playlist of maths 1266 yes easy marked has minimum time visiting all points but it is a very good question it means not to be ignored ok meya net Has asked this question. Let's see what the question says. It says that you have been given a point. D plane's ok with integer coordinates ok. Return the minimum time in to visit all the points in the order given by the points. You have to visit all the points but the most important point here is that you have to visit in the same order in which the points have been given to you. It is okay and you can move only in these three ways. Let us assume that you are here. Okay, so you can move either horizontally, sorry vertically, either horizontally, or diagonally, right, horizontally, vertically, either diagonally, horizontally, vertically, or diagonally. Okay, in any direction, but you can move horizontally, vertically, and diagonally. OK you have to visit the points in the same order. Look at this. Stress is given on this point. You have to visit all the points in the same order. In your mind you are allowed to pass through the point that appears. Letters in the order but those do not count as visits is ok. Let us understand from this example. Look at the example 1 3 4-1 is example. Look at the example 1 3 4-1 is example. Look at the example 1 3 4-1 is given. You have to visit in the same order. The points are ok so let us assume that we started from Nav is ok, see what it will do after this, it will go to 2, then go to Th, okay after this it will not go further, yes, it is a simple thing because look, if you find this point here, then it will move horizontally one move up, then look after Nav 3. After doing F move, we have reached in the same order. Now after 3 F, we have to go to Manav ji. If we have to go here then it will be best to move diagonally because you can move fast through diagonal. It is okay to come here but come to Natu. Coming again to the creature, see how many steps were taken in total here, so one, two, three, five, so the answer is Sen. Okay, so look, we definitely got a hint. We definitely got a hint that it would be best to move diagonally first, like this, I see. Here, we were going diagonally, it's okay until we come in this line, because after this, if we go to Dunali, if we go further away, it will be useless, so go diagonally until this line. Either meet this line or meet this line. Okay, so we will always try to go diagonally first. After that, the remaining distance or this distance is fine, then we will cover it. And one more very important thing, look at this. Question: This question is easy to know thing, look at this. Question: This question is easy to know thing, look at this. Question: This question is easy to know why it happened. The easy part about this question is that you have to visit the points in the same order as it is given, first you have to visit this one, then you have to visit this one, whatever points come in between. Like, remember, we had to move 3 steps one by one, this point came in between, this point came, we don't have to count it, okay, it came here 3 4, it visits here, means it exists in this space 3 4 You have to come here if you have to visit some points in between but see the order is the same 11 3 4 -1 0 Okay so this is the easy is the same 11 3 4 -1 0 Okay so this is the easy is the same 11 3 4 -1 0 Okay so this is the easy part of it isn't it you have to visit the points in the same order as an input so Know the easy part of this, what will be the points given to us, it is obvious that where to go before points a, we have to go in i + 1, in where to go before points a, we have to go in i + 1, in where to go before points a, we have to go in i + 1, in between, you may step on any of the points, but after a, only go to a. So what will we do? We will find the shortest distance from aa to aa p. Whatever the shortest distance is, let us assume that a is a. Then what will we do from the points of aa pv to the points of aa plus two. Let us assume that s2 is and so on point aa. Going from points aa to aa p4 and so on till po aa go to point of n-1 po aa go to point of n-1 po aa go to point of n-1 and add all s1 p s2 and so on. Okay because from points aa we have to go only to points i pw. Same If the order is correct, then find out the shortest distance between these two and so on, we will follow the same thing, I will show you a diagram, because of the values, this is x1 and this is x2, the coordinates of both have been given, so a hint to you. It was found that it would be best to move diagonally. Right, so first of all I draw a line that the line of this point is this and the line of this point is this. Okay, so if you pay attention, the line between x1 and x2. What is the horizontal distance? What is x2 - What is the horizontal distance? What is x2 - Match, okay, let's say, match here, so now look, pay attention, witch, if you match, then see, you have covered this distance, one is already covered, okay, now you just have to cover this. So from here you will move this much part, I take it as capital Now look at the sides of the square, this d is one, is n't it clear here, now look at one thing, this is the whole wa and since this square is mine, then this will also be d, the sides of the square are equal. And this is the whole d, so what is this remaining? D, sorry, d, my d, one is done, okay, take the absolute value because it can happen in any direction, maybe this point is somewhere below. Then by doing d my d one it is okay then the absolute value of d - d is okay then the absolute value of d - d is okay then the absolute value of d - d one you have covered this distance okay so if we look at what you have done then d you have covered one distance by moving diagonally it is okay d one distance you have covered plus Extra, look at how much you walked here, you reached the shortest distance from dy1 y1 to point number Here What will happen if it moves dially or meets it here? Okay, so see what happened by moving dially. It has covered this much distance. Okay, and if it is moved dially, then it is square, is n't it? If you move the square, now look, it was here, this will also become D, this will also become W, this will also become D, so one thing you pay attention to is that whenever you do a dialy move, which line do you meet first? Yes, this time you have met on this line, here you have met on this line, so the one who is smallest, first meet on that line. There was a small one, it is here, so see, one was covered, right? One part was covered and look here, if it is smaller, then look, the distance has been covered. Here is this much part. Yes, of the two, the smaller one will be covered first, so look, it is covered. Now this much part is left. Okay, what is this part? Look so d a midi wa ok so how much distance did you walk d dy1 You have to walk this much right what will be the straight absolute value of dx-data-grid dx-data-grid dx-data-grid lesson d one was here d or just this and d one look so big And in the previous case, remember, in the previous case, d one was small and d was big, so look, d one was added, so this is actually the diagonal distance because when you move diagonally, the distance which is the most. If it is smaller, it gets covered by d, one is covered, look at the remaining, this is the one, okay, so what will be our generalized equation, whichever is smaller, we will add the minimum of d, which is smaller than one d, this is my way of doing diagonal travel. Due to this, the plus which is the extra distance will be covered. What will be the absolute value of the extra distance? Simply make a diagram. We have made the diagram and our answer has come out, so by using this same formula, we will come. Then we will find the shortest distance from apv to ap2, we will find the shortest distance from p2 to ap3 and so on and till my point, let's say s1, s2, or s3, and so. If we keep adding on then our answer will be out. Finally, it is okay. I had put this answer of mine in Stack Over Flow also in 2021. It is okay, I had also put the same diagram, you can see that too, I will put it in the link, but it is fine in the description. So the code has become quite simple, let's finish it quickly, now let's code it exactly as explained, first of all let's find the size int aa e 0 ale aa p ok so what are we going to do aa 2 Those who find the shortest distance of Aa Pv B, so look, we will go till Aa Pv, so we went from mid to less, okay, so first we come out, xv points of i ka zero int ext sorry vav e points of i ka one, similarly which is a psv point. Let's also find out ext watu aa pw i + 1 ok ext watu aa pw i + 1 ok ext watu aa pw i + 1 ok after that remember what was the answer steps plus equal to minimum of d a i whatever is the minimum in d ok plus absolute value of d - dx2 - y1 int d a e absolute value Off x2 my Next video thank you
Minimum Time Visiting All Points
minimum-time-visiting-all-points
On a 2D plane, there are `n` points with integer coordinates `points[i] = [xi, yi]`. Return _the **minimum time** in seconds to visit all the points in the order given by_ `points`. You can move according to these rules: * In `1` second, you can either: * move vertically by one unit, * move horizontally by one unit, or * move diagonally `sqrt(2)` units (in other words, move one unit vertically then one unit horizontally in `1` second). * You have to visit the points in the same order as they appear in the array. * You are allowed to pass through points that appear later in the order, but these do not count as visits. **Example 1:** **Input:** points = \[\[1,1\],\[3,4\],\[-1,0\]\] **Output:** 7 **Explanation:** One optimal path is **\[1,1\]** -> \[2,2\] -> \[3,3\] -> **\[3,4\]** \-> \[2,3\] -> \[1,2\] -> \[0,1\] -> **\[-1,0\]** Time from \[1,1\] to \[3,4\] = 3 seconds Time from \[3,4\] to \[-1,0\] = 4 seconds Total time = 7 seconds **Example 2:** **Input:** points = \[\[3,2\],\[-2,2\]\] **Output:** 5 **Constraints:** * `points.length == n` * `1 <= n <= 100` * `points[i].length == 2` * `-1000 <= points[i][0], points[i][1] <= 1000`
null
null
Easy
null
438
hey guys how you doing this is Jay sir who is not good algorithms I'm recording these videos to prepare my Facebook interview next month in this video I'm going to take a look at four three eight find all anagrams in a strange we're giving a string and non empty string P find all the start indices of P is anagram success okay the order does not matter like this we find ABC the anagrams ABC so CBA of course is one of them and then BAC is also one of them so the index will be 0 6 so well naively we could just to traverse through auditing in index right compare all the possible sub strings well what's the time complexity there will be else let's say this is s and M ok and then it will be oh I'll just use SP so there will be s index and for each s they were how we compare the if these this is the anagrams of this while they're up I think we could just do sorting right sort to this side anagram for P we could sort it at the beginning and that would generate s times the sort it will cost us for sort it cost us what for sort it cost us n P log P right and then there will be another P to compare right this actually causes and OS P log P this is a time complexity Cody could we improve it we have received the information that the words will be will only consists of lower English letters so the possibilities are a finite that reminds us we could do some try to hash sub strings and then compare with what with linear time this could improve us to OS right what much greater how could we do how could do it how could do the hashing well they would because the letters are finite right so we could count it could create a straight array with count of each how to say count of each alphabet right so there will be like something for ABC will be a 1 dot right yeah but the net would be there will be might be duplicated right so maximum this would be to one something like this Maxim and then we could compare if they are the same well this is not very cool if there's only one we could join them as a hash the link to string all right something like one zero I know one zero 26 something like this right now maximum would be twenty thousand so it's not that appropriate to this so we need to find a way another way how do we hot how about counting I can really know like for P like this right when we are travelling through the substring we could do them to do some subtraction like for B we find B and we reduce it yeah right and if we find fun if we found that B doesn't have the character then it is false right if we have it we subtract to it one and continue doing it so this won't be linear time right this is Opie so yeah we cannot do with constant we could use the linear time you could do something like this so let's try to do it so for every round of track we need to reset the count right should we use array if you use array it will be sparse hmm it's okay let's use array so cast count equals new array 26 let's first count for p4 let I come cost X equals P this is cocksure code at I minus 8 character mmm let's cash it code for a code and zero this is the index okay we feel with them feel with zero and then you could say count index plus equals one okay this is the count right and now we are look through the ass and for each starting X we will for let K plus I okay smoother than S Plus P cup net and the case were then esthappan's ka plus okay we should ignore with this s-mint if it isn't is one should do this s-mint if it isn't is one should do this s-mint if it isn't is one should do this if weeks to which is at the previous one so Peter plinth that's one plus one is one yeah okay so for K I actually I plus s that's okay this is a good now for each starting X we should say fixed matched count I said no the I'll let Kate out of this for loop and last I would check if K reaches the riches to reach the last if matched if met then this is a possible risk index right so that K equals I will found where it break and the matched count for P like this I'll create a clone of it course slice serial okay now when you break there are only two cases or only one cases that is that count okay means let's say index equals s character at K - code for index equals s character at K - code for index equals s character at K - code for a this is the exact if count index is 0 we break if it is not is 0 we update it write update you with 1 - abstract with write update you with 1 - abstract with write update you with 1 - abstract with 1 and then continue to next one and last we will check if K equals I plus P dot min we say this is a this is match - min we say this is a this is match - min we say this is a this is match - right so result push I and then at last returned result if you work yay it's a minute cool we're accepted but only but actually not that fast well I thought we were I thought this is mate might be fast anyway let's analyze the time complexity for here this will be s this would be P but the worst case is AAA SP right so time actually is SP space we use an array here 26 and use array here Wow 26 so it's constant we're not that fast so and cost a lot of memory could we improve let's try to improve huh if this is an anagram how could we compare if two strings are a negraph slice and then okay move it get the coat if zero break if not got the minus one and then we check if the last is met if so we're pushing the X so finally Oh screw it could we make it faster it seems that wait a second I realized that if we found anagram here actually if we found an anagram here actually we could determine if this is an anagram by checking this substring and this substrate right if they are the same but we help if it is we could avoid this one in your time if it is not then wait a minute if this is not same as him click this could be same as him and this still could be possible ok I stop out take a look at a solution sliding window with hashmap let's see what does it mean - maps are not the same 1p ABC P count - maps are not the same 1p ABC P count - maps are not the same 1p ABC P count ABC s count yeah the hashmaps same yeah not same yeah this is actually what we did right it's an S &amp; P what does an SNP shouldn't shoot SP right and SNP what is it x y a sliding window with the Ray hashmaps is quite complex structure with known performance issue in Java using two elemental ring so actually where do isn't it yeah we use array initialize it right we compute sliding-window Reyes count at we compute sliding-window Reyes count at we compute sliding-window Reyes count at each step by adding a one letter on the right and removing one ah yeah uh-huh yeah uh-huh yeah uh-huh this is what we could improve actually just as I said I found that we could determine whether this is the same as this one but it's God but it's a it could be better it means sliding window it means I'm not going to check whether these are two anagrams but I could calculate to the characteristic of this service ring by a previous by one step checking the previous one yeah Wow very cool very clever cool let's try to do that sliding window why didn't I find it got a sliding window the idea is the same can for be okay and then we would okay cast account for s still we array 26 view with zero okay what loop from I to en okay now we get the we don't need to count here and we don't need to do here we first getting next is it's like this right so we what we do we push it right so count for s index plus equals one so we get this get the index now here is one thing when the string when the characteristics array like count for s match this name of P which means I know if I is bigger or equal to K document minus 1 which means this is possible we need to check right so count for P check if counts meets and then we need to if I speaker than done it we will remove the previous one right remove previous remove the head so cast index would be s character here is I minus one nice to minus K so PN code for a count for s index minus one yeah check if it's myths it's very simple zero Oh J let's rewrite write it write put it another function to means cost equal equals ar-18 our two what return false return true so if equal count for s then count for e if they met we will cost result a cush the index n right result push I minus P dot now hmm I think it used to work that while we return my minus one okay when we get one - ah yeah minus one okay when we get one - ah yeah minus one okay when we get one - ah yeah here is I is the last one my bad so we get a zero but we didn't get a six waiting we first we update it and then this should be a start this should be start oh this is pennant I think because is bigger it's not this thing if it's like line three not if it is three you three subunits so issue zero I think this is right where is the problem I lock the 4s first a c b a and then e means BAE a B II as a B II and a B then a B a and then B AC so there's another one right so this should issue which piece they match much here match this one result why there is only 0 console walk it cool they had r1 and r2 ah come for us oh yeah please match and then there's no man check hmm this is not much we get a b c d it gets not this one oh god yeah I should update first and get my bad I should get the right before to the comparison sorry guys yeah now we're faster than 99% got yeah now we're faster than 99% got yeah now we're faster than 99% got the result so yeah sliding window I didn't come up with it I find the solution and this is basically the implementation a time now we only traverse the s4 ones right and be VP for once so Saturday s plus B sliding window cool space next extra to array costumed Wow sliding window yeah so in the future for any problems we for doing something about the string you front to calculate some characteristic like hash or something about the sub strings we might need a slight window by adding one element and remove an image we could do easily without recalculating them actually we actually realized that I already come up there was came up with a step that maybe we could detect if two adjacent substring are anagram by checking the head and the tail but I didn't thought about the sliding window hmm anyway okay I'll see you next time bye
Find All Anagrams in a String
find-all-anagrams-in-a-string
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "cbaebabacd ", p = "abc " **Output:** \[0,6\] **Explanation:** The substring with start index = 0 is "cba ", which is an anagram of "abc ". The substring with start index = 6 is "bac ", which is an anagram of "abc ". **Example 2:** **Input:** s = "abab ", p = "ab " **Output:** \[0,1,2\] **Explanation:** The substring with start index = 0 is "ab ", which is an anagram of "ab ". The substring with start index = 1 is "ba ", which is an anagram of "ab ". The substring with start index = 2 is "ab ", which is an anagram of "ab ". **Constraints:** * `1 <= s.length, p.length <= 3 * 104` * `s` and `p` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Medium
242,567
524
Hello Welcome Back Friends Today We Are Going To Solve Liquid Problem 1119 Longest Word In Dictionary Roop Deleting Aa Shyam Yaar Ajeeb Developer Aur Fever On Monday This Preparing For Coding Interview And Job Interviews Channel Please subscribe The Channel Asap Play List For Your Interview Preparation Subscribe So Let's Go Through Time Description Given String Dictionary Backem Widely Characters of Giving More Than One Possible Results Returns Along With High Court Order Is Not Possible To Return Something Graphical Border Basically Alphabetical Order That This Will Come Before Start With Basically Right For Example Let Items from Just a Few Years Should Be Appointed as You Can See Like Share Apple Comes in Lexicographical Order Among Food Before World Daughter Battery Evolved Is Lexicographical Smaller Dubai Which So She Has to Return the Smallest World Lexicographical Smallest Bird Can't Be Formed by Some Deletion Option Character can do that what is justice for example and share and they will discuss how they can solve this problem soft stride let's understand what is the problem is the what is of cache the problem should have to give one string actually and This viewers this cream dictionary of world wide and how to delete time characters from distic and you have to que word english dictionary can be formed for example if you find out what is it apple so if you did s b c d a b c and Decided in you can come to the app word can be for ball deleting sea of characters including hundred similarly you have to check for each word in the given dictionary and will have to front cricket world can be formed for editing eliminated characters in this cream and who have to return lexicographical smallest bird that can be for duplicate egg in the dictionary word basically choice of India example disawar dictionary example monkey and airplane the for more words in the dictionary e at se and string is this is the giver spring force 100 Gram You'll Like Solving This Problem Is Bright What You Have To Is Basically One Thing Is Clear Frigate Hui Have To Go Through This World And One By One And They Will Try To Find Out It's The Longest Word In The Witch Witch Witch Can Very From Latin Characters So Let's Check Out The First World And You Want To Share What Will Be Doing To Solve The Problems Create One Eye Pointer And High Point Will Appoint Clear So Come Right In The Beginning Until Point To The Battle First Character And Will Create another character j&amp;j ill-will point on this Will Create another character j&amp;j ill-will point on this Will Create another character j&amp;j ill-will point on this site and jerry sall0 in the beginning so what do you mean to 151 character and Thursday there is the match will like oo will remove the point earned pointer and a pointer show quintal will keep moving and a The pointer will move will find the corresponding match of the character so now have you ever seen a girls and a needle find the match as soon as otherwise the brightness pointer and I will keep moving red so I will go on air 920 is not equal to a great So I'll Keep Moving Name Right So Aayog Ko Share Pina V Greenpeace Not Equal To Also I'll Go Near Sea Is Not Equal To Flight Courier Unknown We Shape Is Not Equal To And I'll Again Clear Name Is This Point Is Equal To Also Give And allergy pointer servi points and to character at character to and dinner again no names 5.2 I am not disclosed again no names 5.2 I am not disclosed again no names 5.2 I am not disclosed matching whose show will me pointer 238 vikas g plus you free basically at this point and in a great and will check the matter and gives equal To this world dot length right this world link one to three languages ​​also equal two-three shoulder to languages ​​also equal two-three shoulder to languages ​​also equal two-three shoulder to Delhi disawar longest word way cigarette railway and longest word which like will and will keep looking for next world is that is a long drawn can right and Satisfying Our Criteria So Now Have Seen The Game Started Right Now Who Will Just Dial List Remove This Point Attend Ahead In Ubuntu Dhaneshwar Slides And Literature And Show You How To Work On And Sunao Soft Hui Have Found A Great Soul Will Just Before Long S Word Is And Will Not Keep Looking For Apple Pet So Lets Remove This Latest Remove This World Ki Saugandh Suryansh World So Lets Remove This App Kar Do 2018 How To Remove Jis Economic Rut This Note Is Rated Sex Juice Create Another Word For A Plate is one word for apple tower next world is pe new delhi that is lineage world software can be formed by deletion right now again hui tattoo pointers our pointer to posting hui check is a gap word that were looking in tweet lexicographical smaller but it's true lexicographical smaller States You Can See British And Intellect And S&amp;P 500 And Chappell Is And S&amp;P 500 And Chappell Is And S&amp;P 500 And Chappell Is Lexicographically Smaller States Will Consider This App Will Hear Another Will Go And Will Check Now For Apple Song Again Will Have To Point 80 Air Tight Points Come December After Winter End You Will Be Amazed To Interpret That Shubhendu Very And Ponting 208 This Point Suzy More 120 And Is Also Equal To Zero In The Beginning 108 Will Now Go And Check Is Character Noida Sector-12 Show Will Mode Jet Is Character Noida Sector-12 Show Will Mode Jet Is Character Noida Sector-12 Show Will Mode Jet Clear Suna Ujjwal 218 0 I Will Also Moved With Next Character 920 Not Equal To Peso I Will Moved To The Next Character Share It Is Page Show Will Me To The Next Character Which Gives Pain Disappears And Position To And I Will Go To Srinagar Flight Is 180 Is Not Equal To P Surya vilvamul avarai point appear again you is equal to p election fake point clear suji point 3.18 election fake point clear suji point 3.18 election fake point clear suji point 3.18 location third character is that master detail show different in this matching with this also now you will move our 0.2 to zone is for position fried and 0.2 to zone is for position fried and 0.2 to zone is for position fried and again if you Want to go to ki dry is equal to ki saugand and will increase 14258 this point is plus with Amazing 125 and din a aa o studied a to editor and when they compare the length of the world is pale is equal to favorite length of the World Is Equal to Five and Jewelry 2005 Switch Minute Apple Can Be Formed by Removing Samudra Characters from Distinct Right Shoulder Is Updater and Longest Word From Where to Apple Fight with This App Will Also Can Be Formed a Nail Polish Lexicography Palet Smaller and This Region Link flight ticket do you want to front rock longest word middling longest word sorry for that is the united way of give went to implement this problem and in case of world like airplane for example flight solar system tech show airplane word vinyl matthew this a ride show version Will Go Fear Not Lead So I Will Match Again Here Due Point You Will Hear It Will Match Clear And Hadith This Point You Will Not Dare Not Matching Characters For His Remaining Work Should I Cannot Be Amazed 100-150 Loot After Declaration Of 100-150 Loot After Declaration Of 100-150 Loot After Declaration Of Characters Can't what is the various types of the world and Apple will only consider that is the world can be formed by computer data is the way will be implemented in implementation click hair soft that such things like this is our function rights should have been given Settings and list of spring specific dictionary sources create one longest word screen android operating rudra dictionary relative word and where chatting with world link and long s word that they have for odisha small waves of you where looking fog point to you want to loot longest word Basically give it is the means and give word link and longest word that they have for both have seen length first day to you are looking at this lexicography bud notes border basically developed look at the problem share the thing that you have to consider Smallest is graphical and others on this world but they are looking for that twist present the longest word that British model will consider your feet is not Considered Opposition It's Not Mexico Graphically Smaller A 202 Are You Correct Super Example Is Top Delete Se Late Udhar World Late Se User Btc Late Se Solution Word Is Loot Se Jasbir PC For Example In PCs Late Par Tune Of It's Not Lexicographically Smaller Than A Great Developed Taste Switch Off But Will Not Consider This World Is Basically Dead So Dude Do These Here So Guys And Courts Will Just Continue Appointment They Are Not Considering Them And In You Have Created 2.60 3.20 In The Beginning And Want To Give Back 2.60 3.20 In The Beginning And Want To Give Back 2.60 3.20 In The Beginning And Want To Give Back To Words You Can Win for deletion side software co window wildlife and oil is less damage dot length belt development ke adi sa pointer is a daughter in this as a string ride and this is the world and this award for example this is the world in 100 to courier tracking shoes price 10s Don't Drink and Gems List and Watering Means This is the World Richest Village and what length and you will check if the don't drink - came is greater than equal to what drink - came is greater than equal to what drink - came is greater than equal to what a link - did so why you are doing this a link - did so why you are doing this a link - did so why you are doing this actually is development for example of why Are considering award late se airplane right gifu or use like it time award winners from today one of the country in the world with the condition to am late se hui hai he word list for a day and in a that sp ko tight APN fog sum Words Lately Say A Swami Ji Rights Award Is The Writer Death So Excise And Custom And Changes Say Now Peace One The World And When You Can Say Likea On A Plate Shirdi Say A Boy Don Exam Torch Light Software App Will Make Hair Clip From This Is A Year And Previous Year But After That Nothing Is Matching Share Rate Update Showin Hui Cross You The A Pointer Like This Flats And Certain Extent Day Late Is Not Possibly Date Hui Can Match The Remaining Character Certificate This Link That Is More Than What Is Leftover Here Right Sudhijno Possibility That Even If You Are Popular Characters Match There Is No Point Will Check And Second Tune In The match will be reserved against World will match Basically choice that is the reason why they are doing this condition United States for tailing - 8 cigarettes daily States for tailing - 8 cigarettes daily States for tailing - 8 cigarettes daily Watering - Decided to leave this point to Watering - Decided to leave this point to Watering - Decided to leave this point to consider and take good care Characters Shopping so that Fish Methi is a neurotic character Off and stubborn position and matching battle 0.86 Should you realize this is a good match when they battle 0.86 Should you realize this is a good match when they battle 0.86 Should you realize this is a good match when they point to the next character in the morning doing sports and high point at which always be loot the string to allow only give one day match draw as it is the Value of the World League Match Cancel Longest Word in the Longest Epic Poems in the World with Congress Word for Example for This World But When Will Have to Go Through All the Dictionary Word That and Will Return the Longest Word Basic Edu Fonts Clear Shot That Is the weather in implementing a solution so that you can see me clear it is interesting through all dictionary words so you dictionary word art length in this will be in order of any right to edu in hindi for love and share if you consider that purpose will go through Beach character basically m from latest ring site for texting gas against the world with will go through each character muslim cant se saunf dushman late se for example hai sir name characters and enemy hai jab in character new vacancy date year seat will be m into a Bright inch deposit will have to go through all the characters are there in this way look right as that is common so that is the way we have implemented this problem is so let's doing this you know like SIM example that we discussed this year is so common here as you Can see here.the people with the you Can see here.the people with the you Can see here.the people with the longest word which can come very from practice inside test vs the soldiers who can see all the marketing characters result in our answer so let's submit our code is a must mission WhatsApp Twitter 22% must mission WhatsApp Twitter 22% must mission WhatsApp Twitter 22% Faster with this pretty good Show this is the way you can solve the problem Longest word in dictionary fruit deleting or character shirt and recite kinnar google basically little singham returns of this question someshwar you understand this question and practice at you know and tried to understand like this wide spread do you know How The Point At Which Can Take To Point Also Here And The Are Sorry For The Two Points Will Mo0 Character Mature 9:00 Point Arvind Mun And Will Mature 9:00 Point Arvind Mun And Will Mature 9:00 Point Arvind Mun And Will Have To Find The Link Alica Of The World And How To Check The Amazing 125 World Of linkup discover daily means that we can form date world federation of some characters from the given string gas is so will update our longest word basically in that case solve aam surya meeting you check out channel videos as per created a lot of list alaika lord of all its Solutions in Java j2ee Cases Pending for Java j2ee Interviews Telephonic Interview Four Initial Screening This is Not Talk Material Data Activated Dare You Not to Each Other Frequently Asked Questions Through the Best Experience Advisors for From the Past Interview Supplements and You Go Through Day and Tried To Understand Them And Yaar Samudra Like Us Mall Like And Subscribe Difficult Dynamic Programming List And The Amazing Taste Features Like Youtube Alarms List Play List Sunao Example Sardar Lotto Example Sardar Aansoon Regarding The Binary Search Tree In Binary Alcohol Iodine Like You Can Do Likely To Side with right side news vertical traversal please check dam ₹2000 this traversal please check dam ₹2000 this traversal please check dam ₹2000 this question tetra skin b tech companies in rate uniform india according interviews with them in person interview someshwar you practice game also please subscribe to this channel pickup emotive subscribe this Video scan grease to more people YOU FIND THIS VIDEO HELPFUL AND IF YOU HAVE KIDS INCREASED YOUR KNOWLEDGE PLEASE CONSIDER SUBSCRIBE RING TO MY CHANNEL AND THANKS FOR WATCHING THE VIDEO [MUSIC]
Longest Word in Dictionary through Deleting
longest-word-in-dictionary-through-deleting
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. **Example 1:** **Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\] **Output:** "apple " **Example 2:** **Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\] **Output:** "a " **Constraints:** * `1 <= s.length <= 1000` * `1 <= dictionary.length <= 1000` * `1 <= dictionary[i].length <= 1000` * `s` and `dictionary[i]` consist of lowercase English letters.
null
Array,Two Pointers,String,Sorting
Medium
720
491
join us as we tackle coding challenges on code Crusaders in this video we'll be diving deep into the problem by addressing five crucial elements the problem definition our approach to the code an example to illustrate the code the intuition behind the code and the complexity analysis the problem is non-decreasing the problem is non-decreasing the problem is non-decreasing subsequences the problem statement is to find all the different possible non-decreasing different possible non-decreasing different possible non-decreasing subsequences of a given array with at least two elements a non-decreasing subsequence is a non-decreasing subsequence is a non-decreasing subsequence is a sequence of elements in an array in which the elements are in increasing order for example given an array 4 6 7 sum of the possible non-decreasing of the possible non-decreasing of the possible non-decreasing subsequencies with at least two elements include four six seven four seven and six seven the goal is to generate all the different possible non-decreasing different possible non-decreasing different possible non-decreasing subsequences of the given away and return them in any order here is an overview of the approach used in this solution Define a vector result to store all the different subsequences that are generated Define a vector temp to store the current subsequence being generated Define a set hash values to store unique hash values of the subsequences Define a backtracking function that takes the current index and a hash value as input within the function check if the current subsequence has at least two elements if it does add it to the result vector use a loop to iterate through the elements of the array starting from the current index for each element check if it is greater than or equal to the last element in the current subsequence if it is add it to the current subsequence and call the backtracking function recursively with the updated subsequence and the next index after the recursive call remove the last element from the current subsequence finally return the result Vector containing all the different non-decreasing subsequences non-decreasing subsequences non-decreasing subsequences it uses the backtracking algorithm where it starts with an empty subsequence and in each iteration the algorithm can either pick or ignore the current element in the sequence and recursively call the same function for the remaining elements to avoid the duplicate sequences it uses hash underscore set to store the unique subsequences here is a step-by-step explanation of here is a step-by-step explanation of here is a step-by-step explanation of the solution using the example Step 1 initialize the result Vector result in the current subsequence Vector attempt to be empty Step 2 Define the backtracking function that takes the current index and the hash value of the current subsequence as input step 3 within the function check if the current subsequence has at least two elements if it does add it to the result vector step 4 use a loop to iterate through the elements of the array starting from the current index step 5 for each element check if it is greater than or equal to the last element in the current subsequence if it is add it to the current subsequence and call the bat tracking function recursively with the updated subsequence and the next index step 6 after the recursive call remove the last element from the current subsequence step 7 when all elements have been considered and the function has returned the result Vector will contain all the different non-decreasing subsequences of different non-decreasing subsequences of different non-decreasing subsequences of the given array step 8 return the result vector for example input nums equals 4 6 7. initialize the result and temp as empty start the backtracking function set the current index to 0 and the hash value as 0. check if temp has at least two element as it is empty it doesn't so move on to next step use a loop to iterate through the elements of the array starting from the current index zeroth index which is 4. as the temp is empty and 4 is the first element it is added to the temp the backtracking function is called recursively with the updated Temps at smiley4 and current index 1. check if temp has at least two elements which it does now so it gets added to the result vector the next element 6 is greater than the last element in temp four so it is added to the temp and the function is recursively called again with updated Temps at smiley4 6 and index 2. this process continues with elements 7 and 7 being added to the temp and the function being recursively called when the function Returns the temp is reset to 4 and the next element 7 is checked since it is greater than or equal to the last element in temp four it is added to the temp and the function is called again this process continues until all elements have been considered the result Vector will contain 4 6 comma 4 6 7 comma 4 7 comma 6 7 comma 7. the intuition behind this solution is to use the bat tracking algorithm to generate all possible subsequences of the given array and then check each one to see if it is non-decreasing it is non-decreasing it is non-decreasing backtracking is an algorithmic Paradigm that builds a solution incrementally one piece at a time and if it fails to find a solution it backtracks to the previous step and tries again this approach is well suited for solving problems that involve searching for all possible solutions in this case the bat tracking algorithm starts with an empty subsequence and in each iteration it has two options either include the current element in the current subsequence or not the algorithm then recursively calls itself with the updated subsequence and the next index to consider the check for non-decreasing is done by the check for non-decreasing is done by the check for non-decreasing is done by comparing the current element with the last element in the current subsequence if the current element is greater than or equal to the last element we include it in the current subsequence and move on to the next element if the current element is less than the last element we discard it and move on to the next element to avoid the duplicate sequences it uses hash underscore set to store the unique subsequences as we know hash set store's only unique elements so it can be used here to avoid the duplicate sequences in summary the backtracking algorithm is used to generate all possible subsequences of the given array and the check for non-decreasing is used to check for non-decreasing is used to check for non-decreasing is used to filter out the invalid ones in terms of time and space complexity the solution has a Time complexity of big O2 to the power of n into n and space complexity of Big O and the time complexity of big O2 to the power of n into n is due to the fact that for each element in the array we have two options either included in the current subsequence or not therefore the total number of possible subsequences is 2 to the power of n the N Factor comes from the fact that for each subsequence we are iterating through the array and checking if the current element is greater than or equal to the last element in the current subsequence the space complexity of Big O N is due to the fact that we are using a vector temp to store the current subsequence and a vector result to store all the different subsequences that are generated the size of these vectors is directly proportional to the size of the input array which is n thanks for following along I appreciate your attention and I hope you found this explanation helpful if you found this video helpful make sure to hit the like button leave a comment and subscribe for more content like this
Non-decreasing Subsequences
increasing-subsequences
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]\] **Example 2:** **Input:** nums = \[4,4,3,2,1\] **Output:** \[\[4,4\]\] **Constraints:** * `1 <= nums.length <= 15` * `-100 <= nums[i] <= 100`
null
Array,Hash Table,Backtracking,Bit Manipulation
Medium
646
35
greetings youtube today we're doing problem 35 search insert position now this problem was given by amazon in a coding interview and it is based on binary search so let's read the problem and figure out a solution given a sorted array of distinct integers and a target value return the index of the target as fouled if it is not return the index where it would be if it were inserted in order and we must write an algorithm with login runtime complexity now the first thing that you need to notice is this login this should scream even though not 100 of the time but you should be very familiar with binary search so this is a problem that um this is an algorithm that is going to be found in a variety of problems and it is very famous and it shows you that you have a clear understanding of what is a login runtime complexity once again if you don't know where to start always ask for any related topics and here you can see array and a binary search and the interviewer might actually say that you should be aiming at figuring out an algorithm based on binary search now very quick before we actually start analyzing the problem binary search is based and it is called binary because we're always dividing the set by two now i'm gonna write here this thing out so i'm going to write one three five six and i'm going to have a target that is going to be equal to the number five so let's say that i want to find five in this array and that's pretty much what i need to do i'm going to find the middle of the array and i'm going to take it so that's going to be 3. keep in mind that this only works in a sorted array and that is why before we are actually performing binary search we need to have a sorted collection now if 3 is less than 5 this means that everything on the right side of 3 is something that i should be taking a look at meaning that this here are going to be valid candidates and if the number five here the target is going to be less than three for example we are going to be searching for i don't know how to delete that but let's say that i'm going to be searching for the number two is less than 3 so everything here is going to be valid candidate let's say here this is going to be everything that we're going to be searching for when we're looking for two and that is why we're calling it binary search each and every single time we're actually going to check if the middle of the elements the new elements that we're going to have so here we're going to have five and six are these elements going to be equal less or smaller than the target we're going to be searching for if they're smaller then we're going to look to the left if there is bigger then we're going to look to the right and that is how we're actually going to be performing the binary search so let's actually code it up now in order for you to perform this binary algorithmic right to each and every time to divide by two and making the set smaller what we need to do is we need to create a low pointer or just a low value that's going to be equal to the start so low is going to be equal to the zero index and high is going to be equal to the final index if i say low plus high divided by 2 this is going to give me the middle index of this set meaning that this for example is going to give me 3 here now one thing that is very important for the last very important thing to note is that if i have low plus high divided by two both of them this might result in a int in an int overflow which is something that a good friend of mine had mentioned now i'm not going to dive into the idea here because it's way beyond the scope of this problem since in this problem we're not going to have something so sophisticated but let's say that low is an int max value meaning two one four seven and whatever the max in number is and if i add even one to it means that i'm going to have an exception here so that is something to note but we're going to look at it in a different video now let's go with the high and i'm going to say nums length minus 1. keep in mind once again i want the low to be equal to the first index and high to be equal to the last so i'm able to find the middle ones an exit loop should be low is less or equal and high meaning that if i have found if i haven't found anything yet and low is here and hi is going to be equal to it then just break the loop because i have already been searching through the whole collection and i haven't found anything so there is no need for me to keep going because otherwise i'm just going to have an infinite loop now i'm going to create the middle value that i have been talking about and this is going to be equal to low plus high divided by 2. all right the first thing that i do want to note is for example if i have the numbers one two three five six and i'm looking for the target three the middle element here is going to be exactly this is going to be exactly three so i'm going to have the middle element equal to the target that i'm searching and of course if that is the case all i need to do is to return the endings over here since i'm going to also have indexes and this is going to be a bit big but you get the idea meaning that i say if nums of the middle value that i have already found and this is not a middle value this is a mid middle index if nums of middle index is actually equal to our target all i'm going to do is return the middle index that i have already found and the interesting part here is how am i actually going to make the set bigger or smaller i'm actually not making it bigger anytime i'm just making it smaller all the time but in order for me to make it small i need to change to choose what kind of a subset i want included so this i already explained but i'm just going to go through it one more time one two three four and five and let's say that i'm looking for the target is five i'm looking for the number five i'm going to take the middle and i'm gonna say is three less than five so if five is actually bigger than three then i'm going to look at the right because i know that these are sorted so everything on the right is going to be bigger and if 5 is smaller than 3 i'm going to take a look at left so that's pretty much it all i need to do now is just increase or decrease high and low points that's pretty much it on the other iterations i'm going to get a new middle index here because i have already increased or decreased low and high meaning that if i have if nums of middle index is actually bigger than the target all i need to do is to say i is going to be equal to middle index minus one and else low is going to be equal to middle index plus one so that's pretty much it i'm actually going to remove the brackets so we can see it a bit clearer and now you're going to get the whole idea once again i'm gonna draw it on the screen here and i'm gonna be looking for the number five i'm gonna put it against three and now i'm gonna say middle index is less than three right so i'm not going to have this point i'm going to go to the else and here i'm going to just increase the low pointer low is going to come from here to here plus one meaning that i'm going to have the new low at this index and of course after that i'm gonna be looking at this set over here four and five and i'm going to have a new low and of course the old high and that's pretty much it that's all i need to do the final part is if i haven't found anything it means that there is no target and i have already got to a point where the target should be because i already incremented the low of and here at this stage all i need to do is just to return low and that's pretty much it so let's actually say console do the use example test cases and run the code to see if this is going to be successful okay still waiting and there we go accept it then i'm just going to push it to the server and hope for the best and there it is so it's running quite fast even though i have already said don't look at these numbers since they're not all the time correct in fact most of the time they're not correct if you want to benchmark something use to benchmark something use to benchmark something use and that way you can see the exact runtime complexity and the exact speed and that was binary search thank you for watching and if you have any questions leave them down below bye
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
1,460
okay let code number 14 60 make two arrays equal by reversing sub arrays we have to erase we can reverse any sub array of one of them and the question is can we obtain the second one okay well if they're not of equal lengths we cannot obtain any one of them of course and then there is the second idea so we can perform that operation as many times as we want and at the same time it's very important to notice the fact that reversing a sub array of length two is swapping the elements and as we all know we can actually sort or rather obtain anything we want any every one but only swapping the two adjacent elements so the question is whether they are of equal length and can contain the same number of the same elements so for checking that out we will do something very simple it will sort both of them are that end and we just need to check whether they are the same or not completely the same and the first check would be nice that their sizes are not equal the answer is definitely false okay so if they are equal the question is do they have different elements since they are sorted if they do not match for even at least one positions then we'll never be able to obtain one from the other so in for a it doesn't equal the target I return and after this if none of them crashed and it's definitely true so now let's see what where did the screw-up wisent Avangate where did the screw-up wisent Avangate where did the screw-up wisent Avangate force like this doesn't make any sense whatsoever sort swords move if they're not equal return false oh my god it's multitasking it's little bit tough here okay things happen okay good enough and this is it thanks for watching
Make Two Arrays Equal by Reversing Subarrays
number-of-substrings-containing-all-three-characters
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\] **Output:** true **Explanation:** You can follow the next steps to convert arr to target: 1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\] 2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\] 3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\] There are multiple ways to convert arr to target, this is not the only way to do so. **Example 2:** **Input:** target = \[7\], arr = \[7\] **Output:** true **Explanation:** arr is equal to target without any reverses. **Example 3:** **Input:** target = \[3,7,9\], arr = \[3,7,11\] **Output:** false **Explanation:** arr does not have value 9 and it can never be converted to target. **Constraints:** * `target.length == arr.length` * `1 <= target.length <= 1000` * `1 <= target[i] <= 1000` * `1 <= arr[i] <= 1000`
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Hash Table,String,Sliding Window
Medium
2187
454
hello everyone i'm bihan chakravarti and today i'll be discussing problem number 454 from late code that is for some two so this is february 2022's day three problem and it's a medium level problem as you can see so let's get started so in this problem we have been given four arrays num one two three four and we have to return all like return the number of tuples i j k l such that the sum of i uh like ith number from nums one j th number from nums to like that the sum of four numbers equals to zero okay so this is the question like numbs one of i numbers two of j numbers three of k plus number 4 of l so we have to use each index from each area like we cannot take two elements from a single idea we have to take one element from each array and get the sum as zero so the approach is very simple now let me go to my editor here okay so suppose i have x plus y equals to 0 so what are my possible values of x now this can be infinite but the way uh like what can be possible value of x it can be only minus of y because only then i can write minus y plus y equals to zero so if i have y that means my x will be minus y so for any given value of y x should be its negative okay so suppose i have two arrays nums one and two initially okay so this is 1 and this is 2 so suppose i take two numbers from here let me call the numbers i and j okay i and j once summed it becomes uh like let me denote it as x so if i have x and suppose i have three and four here the third and fourth adding now we can check for every index of k and l using uh two nested loops we can check that which element sum is negative of x like it should be k plus l should be minus of x now only then i can say that x plus like i plus j plus k plus l equals to 0 only then i can say that right so what we will do here is that initially calculate all the possible sums from the array one and two okay we will use two nested loops and we will like check for with zero then zero with one zero with two then one with two like that so we will have all sums of all the indices then we will store that in a map and store its frequency as well and i'll get back to the frequency after a bit so once we have that stored then we can again do a nested loop in three and four and check like for every sum k plus l we can check whether there exists a sum in 1 plus 2 like 1 and 2 as well like there exists a sum k plus l which is equals to negative of i plus j we have to check that in the hash map and if we have that we can simply write that our answer variable answer plus equals to map of like hashmap of that key map of negative x now why we are writing this now let me uh like you one can argue that we can use sets here as well right to store only the elements and why you need the frequency that is because uh suppose uh there's a test case just give me a minute yeah so observe these cases here let me zoom in yeah so these are the four arrays and let's consider 0 of num1 0 of num2 with 1 of num3 and 0 of num4 so let me write that comma zero from num1 and num2 and here one comma zero okay now we have minus ones here so let me show another possibility now i choose minus one here again and minus one this one but this time i choose the second one from nums one so it will be one comma zero and i'll keep the ones as same so one comma zero so as you can see there are two possibilities here but if i store this in a set then it will store only unique elements so there will be only one so the count would be one but i need the count as two so i need to keep the frequency of the same thing so that is why we are using a hash map so let's take a look in the code we have empty hash map initially okay so first of all we traverse the first two arrays that is nums one and two and inside that i just increase the counter so it is equivalent in c plus is equivalent to hash of norms one plus nums plus equals to 1 in c plus it's like this okay so i'm just incrementing the counter of this key nouns 1 plus num2 now after this is done i initialize a answer variable it's a counter variable that will store our answer now we traverse the ideas three and four numbers three and nums four inside that we check first of all we sum nums three of i and nums four of j and then we make it like change its sign so if it spots it positive it becomes negative and if it's negative it becomes positive then we check whether the inverse value exists in the hash map or not if it exists then we just get its key and sum that value because we sum that frequency to the answer so suppose here num 1 plus num2 equals to 5 for some instance now while i'm here if num 3 plus nums 4 becomes minus 5 okay suppose i get minus 5 through here so my key would be minus 5 into minus 1 that would be equals to 5 so now we will now since numbers 1 plus num2 was 5 it was already in the hashmap right so since it's already in the hashmap and now we can check whether this 5 after it's inversed we can check if this 5 exists in the hashmap now if it exists in the hashmap then we will increment the counter we will increment the hashmap of 5 we will increment it by the frequency of 5 right so this is the problem if you have any doubts on this problem please comment below i'll be glad to answer all of them i'll try my best to clear your doubts and if you have liked my video and my previous videos please like and subscribe to get further notifications on upcoming videos and i am creating a whole playlist on the february long challenge of lead code so i'll be uploading videos every day so make sure you subscribe to get notifications and yeah as usual see you in the next video
4Sum II
4sum-ii
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that: * `0 <= i, j, k, l < n` * `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0` **Example 1:** **Input:** nums1 = \[1,2\], nums2 = \[-2,-1\], nums3 = \[-1,2\], nums4 = \[0,2\] **Output:** 2 **Explanation:** The two tuples are: 1. (0, 0, 0, 1) -> nums1\[0\] + nums2\[0\] + nums3\[0\] + nums4\[1\] = 1 + (-2) + (-1) + 2 = 0 2. (1, 1, 0, 0) -> nums1\[1\] + nums2\[1\] + nums3\[0\] + nums4\[0\] = 2 + (-1) + (-1) + 0 = 0 **Example 2:** **Input:** nums1 = \[0\], nums2 = \[0\], nums3 = \[0\], nums4 = \[0\] **Output:** 1 **Constraints:** * `n == nums1.length` * `n == nums2.length` * `n == nums3.length` * `n == nums4.length` * `1 <= n <= 200` * `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228`
null
Array,Hash Table
Medium
18
455
So hello what is up guys so happy new year to all of you first of all ok and today we will try again new questions new year new what ever you can call it so let's start without any delay ok So the first one is today's first January question, it is easy, it has come ok for us, assign cookie ok, so let's see what is telling us, the question is so amazing, you are an awesome parent, ok brother, you are an amazing father, ok and your Children want some cookie, okay and want to give your children some cookie, you want to give your children some cookie, but you should give each child at most one cookie, so you can give only one cookie to each child, okay, I will give you only one cookie, brother. Can't eat too much sweet son, it's okay, no one should go, child has a greed factor, GI is okay, every child is greedy with GI factor, okay, f is the maximum size of a cookie that the child will be content with, so GI. What is the maximum size of the cookie which will make the child happy yes ok I am happy ok and each cookie j has a size i s j ok so every cookie also has a size s j ok so if sj is bigger Okay, because of the greed of the child, if the child is bigger than what I want, then what will that child become content? Okay, we can assign the cookie Is the cookie bigger or equal? ​​If the cookie Is the cookie bigger or equal? ​​If the cookie Is the cookie bigger or equal? ​​If the child eats as much as he wants, then that child will become content. Okay, he should become happy. Your goal is to maximize the number of content children and output the maximum number. So what do we have to do brother, we have more. How many more children can we make happy, we have to tell, okay, and we have to give the number of the same number of children who will become happy, okay, this question is very easy, it seems easy, now see what they say here. Example one, okay, so what is the given size, how much grid do we need, the first child needs one, the second child needs two, and the third child needs three. Okay, and the second one is given the size. Now we have two cookies whose Size one and one is okay now there are two cookies of size one and one okay and one child wants one, I want one is saying I want two, one is saying I want brother three, okay so either Look, this is the child, it is okay and if we can give only one cookie, then we will give it to him, this will be our waste because he will not agree, okay, so we will be able to give only one not agree, he will not agree, okay, so we will be able to give only one cookie, only one child will be happy, okay So the output is one is ok you have three children two cookies the greed factor of three children is 1 tooth and even two you have two cookies since the rate is both one you can only make the child whose greed factor is one content you need to Output one is ok, I have understood brother, there is no problem here, now let's see this second example, ok grid is one, two more cookies are on our 1 2 3, ok so there is one, ok grid is one and one is on ours. Pass two is okay and how much is the grade One is okay two and three is okay so this brother give it this two children's book has calmed down two we have output the matter is not over okay but now here Look, there is nothing like this here, look, all the cases we have are fine, till now what do you see in both the examples that it is sorted but it is not necessary that it will be sorted, let's assume that our grid is 4th, it is fine, 5, 6, 1, 2, it is fine and We have cookies, the size of the cookies is us 6 2 1 8 4 F Okay, let's assume this is okay, then how many children will we be able to make happy? Okay, so see what is coming in my mind here, no meaning, how can it be? Well, brother, if we sort both of them, it's okay, if we sort this too, it's okay, and if we sort this too, it's okay. Now after sorting this, what will happen? 2, 3, 4, 5 and 6, okay, after sorting this, the tooth will come. So it's not 4 5 sx 8 Okay, he will come, so let's see, we can give the lowest p to the lowest, okay, then it will not be like that we have given brother fifth cookie to brother one, now when he is asking for fifth, okay So we have to give a bigger one. Are you able to understand? Okay, if you understand, here six of our cookies will be divided, here all will be divided. Look, we have given one, it is okay for one, two is okay, we have given two, it is okay. Yes, to three we have given what letters, let us assume that we have given four, okay, to four, we have given F, to five, we have given six, and to six, we have given A, everyone will be happy, yes, all the children are okay. There is no problem, okay, so here we have something in mind about sorting, okay, if we sort, we can do something, okay, so we have to put a check, okay, one of our checks. It will remain that S A of A is greater than Eq A. Okay, now you mean the basic idea has come, now after this we will understand the code better. Okay, so first of all, what did we talk about, friend, both of them. Sort both of them. Okay, so look. Cert is G of G. Okay, from the beginning of G to G. End, we have done the set. Our first one is sorry or wrong, so with this, our G has become shirt. Okay, now we will do the sert. From beginning to end, we have also set this up, now look, okay, now see what we can do, now we run the loo, okay, we take it, and it's okay, we will run it. P and a we will run s p ok aa lesson g dot begin ok end kya b sorry sa and j len add size ok brother this one thing we have made a loop ok now see if a off i a off sorry j Going with F J E Greater than equal to G of I Okay, so what happened to us friend, the of G of I Okay, so what happened to us friend, the child's grid got filled, okay, it got filled, so what will we do, we will do it G P I P Ps ok green i plus is done and see in the last it will be plus i think things are going well in the last it is ok f kept watching let's submit and see if it will work or not a ok guy so this one is done. There is no problem, okay, so I hope you have understood this thing, it is not so difficult, okay, because look what we are doing, the lowest, look at all the lowest grids here, whenever our grid is being fulfilled. So, that is, one child's grade has been completed, so we kept on increasing it. Okay, so the number of children's grade is getting completed, right, we are increasing it and where are we running our pockets? It is okay on the lowest pay. If it is sorted then it will remain at the lowest position. Okay, now it will remain at the lowest position. What does J's lowest mean? Can J complete the lowest grade? If it can, then it is okay. If it cannot, then J is increased, then it will complete it. Understand. If you continue like this, then whatever grid will be completed, we will come and return it at the end, okay, so it is being made like this from here, okay, I hope guys must have understood what is the code for this? I will give in the description section, if you like the video then please like the video and I will see you in the next one, share it with your friends, subscribe the channel and see you tomorrow, okay, this time January batch will take everyone. Ok so keep doing it friend lead code and I will meet you in the next video bye
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
148
hey guys welcome back to another video and today we're going to be solving the leak code question sort list all right so as the title says we're going to be given a linked list and all we need to do is we're going to sort it so real quickly given the head of the linked list return the list after sorting it in ascending order all right so follow up so can you sort the link list in big o and log n time and constant space okay so the question itself is pretty straightforward we just want to sort a linked list now there's several different ways to that you can use a bubble sort insertion sort there's several different sorting algorithms but one thing that we want to keep in mind is that we want to preferably do it in big o and log n time so i on the top of my head there's two algorithms that come to my mind which can complete it in such a time complexity one of them is quick sort and the other one is merge sort so the thing about quick sort is that even though it's average time complexity is big o of n log n uh it's uh its worst time complexity is big o n squared but on the other hand merge sort is consistently big o and log n so that's why we're going to be using merge store and another reason we're going to be using merge sort is because it's a lot easier to do and it's commonly used in linked list questions so if you don't know what that is don't worry i'll be going through it step by step okay so uh just one example real quickly so we're given four two one three we sort it and we get one two three four pretty simple and this is another example negative one five three four zero and it gets sorted so i'll be working with example two here and i'll be going through it step by step and show you what it looks like all right so this over here is the linked list that we're starting off with negative one five three four zero and when we want to perform a merge sort there's actually two different steps that go into performing it now let's just write down the two steps the first step is going to be a splitting step i'll explain what these actually mean and the second step is going to be a merging or sorting step usually it's called a merge step all right so this is how it's going to work so basically we're going to be given a linked list and what we want to do given a linked list is that we're going to break it down the way we break it down is we're going to keep cutting it down in its halves so we're going to keep breaking it or splitting it down each time by one half so first let's say this has a length of n then we would end by two then end by four and by eight and by 16 and so on and so forth and we keep shortening it now when do we actually stop shorting it so we're going to stop shortening our linked list over here until we get each of its elements uh by itself right so over here we have negative one by itself right until we get to such a point we're going to keep splitting it i'll show you what the purpose of doing this is but in simple words what we're doing is let's say we have a massive problem all we're doing is we're cutting it down into smaller parts in other words we're dividing all of these smaller parts and it's just a divide and conquer strategy we're going to divide it into smaller easy to handle parts then we're going to solve each of these mini parts by itself and as we're solving each of these parts we're going to converge them and make it into the final product that we're trying to get at okay so let's just do this first step which is splitting it okay so in the beginning we're going to split it and we're going to divide it by 2. so this over here is all one of the halves is going to be uh even and one of them is going to be odd so in this case let's say we have negative 1 and 5 so that is going to be one of the splits and the other split is going to be three four and zero okay so now the question is did we reach any of our elements by its individual value values the answer is no not yet so we didn't yet so now in that case what's going to happen is we're going to split it again so over here let's just focus at this over here so let's put negative 1 to 5 and when you split this you get what two values you get negative 1 by itself and you also get 5 by itself so in that case we're going to end our split we're not going to be making any more splits so that's going to be it for this half of the linked list so now let's go on to the other half with 3 4 and 0. so over here we're going to split it and now when you split it you get 3 by itself so 3 is also by itself but 4 and 0 are not going to be by itself so when you split that you get 4 pointing to 0. so it's still a linked list so now we're going to split this again so only four pointing to zero and that over here gives us four by itself and then zero by itself all right so as you can see we've now finally reached a point where all these elements are by themselves so negative one five three four zero and the way that we're actually gonna do this inside of our code is we're gonna be using a we're going to be using a function which is going to be called recursively okay and as you can see there's kind of like layers to it and each time we go lower and lower we're getting closer to the individual values by itself so this over here is the split part okay we split everything into its smallest sections possible and now what we're going to do using the split part over here we're going to kind of build up a new linked list which and this new linked list over here is going to be our final answer so this over here is going to be sorted so this is our sorting or merging step i just drew a line to kind of show how the steps are different so we have negative one five three four zero so how this is going to work is we're going to start off with the last values that were kind of split apart so what is the last thing that was split apart over here so the last thing that was split apart was 4 and 0. so now what we're going to do over here is we're actually going to sort the very last thing that was split apart so that is 4 and 0 and we want to sort it so in order to sort that how is it going to be so in simple words it's just going to be 0 pointing to 4. that is sorted for a version of four pointing the zero but for the sake of this let's just go through it a little bit more methodically so how you would do it is you would have a dummy head and this head is just kind of there as a placeholder and we're gonna get rid of it later so in the beginning it's gonna point to none and then what we're going to be doing is that what is this going to point to so the options we have here are either 4 or 0. so in this case we're going to end up choosing the smallest of them because we want it in ascending order so we're gonna end up choosing the value zero and obviously the only other value left is four so that's how we get our sorted linked list uh and i'll be going through it once we have more numbers since then it'll make more sense okay so now we're kind of done with this layer over here right so now we're gonna go up another layer so over here we have three and then we have zero four so the aim over here is we have to add three over here in such a way that it's sorted so how do we do this so same thing we're going to have a dummy head and what is this and we want to sort this in ascending order so if you just look at it's obviously going to be 0 3 4. so let's see how we can do this so you can kind of think of these as two different linked lists so this is one list and this is list one so the pointers of each of these are going to start off at the very first value and what we're going to do is we're going to choose the smallest between those two pointers so in this case we have three at one point here and zero one pointer so what do we choose zero so whatever we choose we're gonna cross out that pointer and move that pointer in that certain linked list to the right so now our pointer is at four and now we're gonna choose between three and four obviously three is smaller so then we have three and then finally uh we're done with this so obviously the last one we have is four so now we have zero three four so let me just erase this and make it so it looks better okay and now by adding three to our linked list zero comma four in a sorted manner it's gonna be zero three four so basically what's really happening is each time we're going above a level we're sorting that by itself each and every time now finally we have negative one and five you would perform the same steps with the dummy head but already this is sorted over here so uh we'll just have it as it is so negative one point into five so now let's just go to our final step so i'm just going to draw a square brackets to kind of identify that these are two different lists this is linked list one this is length plus two they're both completely different uh for so far and we're going to merge them now and by merging them we're going to get our final result obviously okay so how exactly are we going to merge it same steps we have our dummy head and what is our dummy head going to point to and in order to go over that we're going to do the same steps since we have two different lists the first pointer is going to be at the first element of the first list and we're going to have one more pointer at the first element of the second list so we those over there are our two up pointers zero and negative one and which one are we going to choose so we're going to compare negative one with zero obviously negative one is less than zero so the pointer that none is going to point to or in other words the first head value is going to be negative one so since we chose negative one what we're gonna do is we're gonna move this pointer to the right by one so in this case now it's at five so and we keep doing the same steps compare five with zero obviously zero is less than five so in that case negative one is going to be pointing to zero and the reason this method actually makes sense is because at our lower levels we already sorted each of these linked lists so as we're building it up it just makes it a lot easier to actually merge these two together all right so now we have zero so in that case the pointer moves to the right by one now we're doing five and three is still less than the five and then we move it to the right again now we have four and we're completely done with this link post over here so we have no other option but to add this over here and that's exactly what we have and if you just look at this linked list that we have over here that is exactly the same as our answer which is negative one zero three four five and if you just look at it's sorted in ascending order okay so hopefully you understood how this work uh works and there's two different ways to do this uh you could do it recursively or you could do it iteratively and uh we'll be absolving it recursively because that's usually a little bit easier at least in terms of code before we actually go into the code part i just want to go over the part of how exactly do we make the split so in order to do this we're going to be having three different pointers or actually variables so one of them is going to be a slow pointer we're going to have a fast pointer and we're going to have a pointer which is going to keep track of the previous slow position that we were on so i'll just call that p okay so just for the sake of representation just think of these as different levels so anything in this level would refer to slow anything in this level would be referring to fast and then this for the previous pointer all right so now that we have this let's see how we can actually use these pointers to actually divide the list so what's going to happen is that over here our slow pointer and the fast pointer are all both going to start at a value at the head node so in this case they both start at negative one now the reason the fast pointer is considered to be fast is because it's going to move two steps for every one step that the slow pointer moves so if you move this little pointer to the right by one the fast pointer is going to move to the right by two so now in this case in the very beginning this uh the p pointer is not going to have any value so now let's go on to the next iteration so in this case we move the slow pointer to the right by one perfect and now after that what's going to happen is that we're going to move the fast pointer to the right by two so we move it to five and then three so this is over here right now and what is going to be the previous pointer so the previous pointer is going to be the previous location of the slow pointer so currently it's going to be right over here so our previous pointer is going to be at negative one all right so now let's go on to the next iteration so the slow pointer is now going to move to the right by one so we're gonna be over here the fast pointer is gonna move to the right by two so one two so now it's over here and now again the previous pointer what's gonna happen is gonna go to the previous location which in this case is five so currently the previous point over here is five so actually what happens over here is we end up stopping so when exactly do we stop so to understand that we have two different conditions so one condition is when the next values in this case technically this will be pointing to none so the next value over here is none for the fast pointer so in that case that means that we're going to stop so we can't really do anything but there might be some instances where the fast pointer is the is on the none pointer in that case as well we are going to stop so if the next node to the fast pointer is none or the current node of the fast pointer is none in that case we're going to stop iterating through it so in this case we're going to currently stop so let's just see where everything finally is so our p pointer is over here our slow pointer is over here and the fast pointer is over here now what really matters over here is actually the p pointer the previous value that we're looking for so what's gonna happen what we're gonna do is we have one five three four zero nine so what we're gonna do over here is we're gonna take negative one oh sorry i meant to say negative one then we have five and we're gonna take whatever the p value is and its next element is going to become none so 5 is not going to point to 3 anymore instead it's going to be pointing to none and what that basically means is that we have our own linked list over here similarly over here what's going to happen is the three since nothing's funny to it's gonna be the head note so three points to four points to zero points to none okay which is uh exactly basically splitting it in half uh if you want to go through it one more time real quickly i'll do it super fast over here so three four zero so we have a slow pointer fast pointer flow pointer moves to the right by one fast pointer moves right by two and obviously the next value to this is none so then we stop iterating through it and the previous value would be at three so in that case we would have three pointing to none that would be one thing and the other thing that we would have is four pointing to zero point two none so hopefully that makes sense and let's just see that in code right now all right so let's start with our code and the first thing that we're going to do is we're going to have our splitting function and i'll just do that over here and for the merge function we'll make a separate function okay so over here the first thing that we're going to do is we're going to check if we do not actually have a head value or head dot next does not exist or not head dot next and why exactly are we doing this and in this case we're just going to end up returning head so the answer to that is pretty simple so let's say we have some sort of linked list which has nothing inside of it or if it just has one value so if any of those two conditions are true what that means is that the linked list itself and its sorted version are exactly going to be the same because when you have only one value it's going to be exactly the same as the sorted version so this over here is what we're going to use and it's also going to help us while we're recursing through our function okay so after this we want to define our three variables so we have the p variable which holds the previous value of the slow head slow pointer so i'll just call that p uh then after that we're going to have our slow pointer and we're also going to have our fast pointer so p is going to start off at none uh you could also make it start at head i think that should also work but um then slow is going to start off at the head itself and fast is also going to start off at the head sorry okay so we defined all of our variables and now we're going to go inside the while loop so what are the conditions for our while loop so we keep going until the fast pointer actually has a value or if fast dot next is not none so while fast and fast dot next what that's telling us is that fast uh currently has a value and fast dot next is not none right sorry i can't spell okay now after we have this we want to redefine our functions so what is going to happen to p so p over here is now going to be the value of the slow variable or pointer because p always holds the previous value of the slow pointer so we have that now after this we're going to change the slow pointer and obviously the slow pointer all it does it moves to the right by one so slow equals to slow dot text pretty easy now we have to change the value of the fast pointer which in this case we're moving the fast pointer by two so fast dot next perfect so by the ending of this we're going to have the finalized versions of the p value this low value and the fast volume and what we're going to do over here p dot next is going to end up equal into none and what that's basically telling us is that we kind of split up our linked list into two different parts perfect so we have this over here all right so after we have this over here what we want to do is we actually want to be calling our merge function so how exactly we're going to call our merge function so i'll be making the function later before we do that we're going to call it over here so we're going to return that value and i'll just call this function over here merge and what are we exactly going to be giving inside of our merged values so in simple words to our merged value we're going to be giving it the two parts or the divisions that we made inside of this sort list function over here so what exactly are the two divisions so let's just go back to the sketchbook over here and as you can see let's say in the first instance we have two divisions negative one comma five and three comma three four zero right so negative one to five where does it start at so this over here starts at the head so we have that and where does three start at so this three over here starts at the slow pointer so as you can see the slow pointer ends up over here so the three is also starting at the slow pointer so let's just use that knowledge that we have and those are what we're going to be giving our function so over here we're going to call this function so self dot sort list and we're going to be calling it on the head so that is going to be one half and the second half that we have is going to be starting from the slow value so self dot sort list and then we're going to be giving it slope okay so now you might be confused about why are we actually calling the sort list function over here so in other words all sort list is doing uh just to be clear it's actually splitting down our values now the reason we're recursively calling this is when exactly is this going to stop so this is going to keep going until this condition over here actually happens so if not head or not head.next what that means is that or not head.next what that means is that or not head.next what that means is that if we only have one value or if we have no value at all only then we're just going to directly return the head that we have and that is going to stop this function over here so what that's basically doing for us is we're going all the way down to the bottom so we're going to be going all so we're going to recursively be calling this function all the way until we reach the very bottom which in this case is negative 1 5 3 4 0 so the numbers by themselves so we're going to keep going until then and each time that we're doing that we're going to be calling the self.merge we're going to be calling the self.merge we're going to be calling the self.merge function which very easily for us is going to be taking these two halves and it's going to merge it into one for us so yeah so all we really have left to do right now is to actually make our merge function so let's call it merge and it's going to take self and obviously we want to give it two different linked lists right so in order to do that i'll just call one of them l1 and i'll call the second one l2 pretty simple so inside of this function we're going to be having our dummy node that we were talking about and the dummy node just helps us to actually form our final linked list and just a quick reminder we're taking two linked lists and making it into one so what is this dummy node going to be so we want to make it an object of the list node and how exactly are we making this well it's predefined for us over here so we can just use that okay and the value for this is just going to be none sorry and over here we're also going to have one more node and i'll call this a current node and the purpose of this node over here is going to be to kind of find out what node we're currently on all right so now that we have all of this we're going to go inside actually creating our linked list so we're going to go inside of a while loop and this while loop is going to check if we have a value for l1 and if we have a value for l2 the reason that we're doing this is because we're going to keep going until we reach the ending for either one of the lists so let's say we reach the ending of list one and we're going to stop over there and after that we're going to go to the value in list 2 and add it to our linked list so over here we had our pointer so what happened over here let's say this is l1 and this is l2 what happened is that this over here got depleted before l1 so we used up everything over here so in that case we're going to stop in going through our while loop and in that case we're going to have one extra element remaining which in this case is the value 5 over here and that's what we're going to end up adding to the remaining of our linked list okay so let's just do that real quickly so while l1 and l2 so we have that over there over here we're going to compare the values of l1 and l2 so we're going to do l1 dot val so in the beginning it refers to the head node so if one dot val is greater than l two dot val what does that mean so in that case we're always going to choose the smallest value and in this case that's gonna be l2 since l1 is greater than l2 that means l2 is a smaller value and since we're choosing the l1 value what we're going to do is our current dot next node so we have our current node which in this case starts off at the very beginning so current.next is now going to have the so current.next is now going to have the so current.next is now going to have the same value as l2 and that's obviously because l2 is less than l1 and the other thing that it's going to change is since we're choosing the value from l2 we're going to change the pointer that is in l2 so in the beginning let's say we were pointing at the head node we're going to move to the right by one so and to do that we're just going to do l2 dot next now finally over here we're going to have an else condition which refers to the case where l2 is greater than l1 and in order to do that what's going to happen is current dot next is going to equal to l1 over here because l1 is smaller and the same thing is going to happen we're going to move l1's pointer to the right by one so l1 is now going to be equal to l1 dot next all right perfect so now that we're done with this if else statement over here one more thing that's going to happen is that we actually have to move our current node that we have so we can just let it be in the same place so to move it to the right by one current is now going to be equal to current dot next so this over here is going to be or should be the ending for our while loop so that over there by the ending of it we should get a linked list but what happens is that we actually don't get all of the values so what we want to do now is we're at our current value and what we're going to check is if l1 exists so if the by the ending of this l1 does not have a value of none then in that case what we're going to do is current dot next is going to equal to l1 and over here we're going to check if l2 exists so over here we're checking for l1 existing and if it does exist well we're going to do current.next equals l1 going to do current.next equals l1 going to do current.next equals l1 and if l2 exists we're going to do current.next equals l2 current.next equals l2 current.next equals l2 and actually we could do elsif because only one of these is going to exist and the reason for that is because our while loop over here says while l1 and l2 so what does that mean that means that l1 and l2 for it to stop both l1 and l2 must have been negative or one of them could have been negative so if they were both actually at a value of none then what that means is that we've depleted both of the linked lists but if only one of them had a value of none what that means is one of the other linked lists has not been fully added to the final result so in order to compensate for that we're doing this over here and we're adding that remaining linked list so we took care of that and finally we're going to be returning our value so what do we return over here so are we going to return our dummy uh node and the answer is no so the dummy node was just a placeholder and the actual ahead of our linked list starts at the next value so over here we're going to do dummy.next and that is we're going to do dummy.next and that is we're going to do dummy.next and that is going to be the head of the linked list that we're referring to and this really should be it so let's submit to our solution and as you can see our submission was accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
Sort List
sort-list
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 5 * 104]`. * `-105 <= Node.val <= 105` **Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
null
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
Medium
21,75,147,1992
1,431
hey so welcome back and this is another daily code problem so today it was called kids with the greatest number of candies and it's just an easy level problem you can actually do it in a one-liner so all can actually do it in a one-liner so all can actually do it in a one-liner so all that you're given here is a candies array with a given number of candies for every single I think uh child here and then you have three extra candies that you can give these children and all that you want to do is say that okay we want to return true if we can give this particular can like this particular kid it's reaction candies to give it greater than or equal to the maximum number of candies in this array so all that means is if you give this child two can or three extra candies it'll have five candies and because the biggest number in this array is five you want to return true because well 5 is greater than or equal to five which is the maximum or the greatest number of candies in this array at this step here if you give this child three extra candies it'll have six and because five is the greatest number of candies currently and six is greater than that amount you also want to return true same with five because five plus three is eight and eight is bigger than five the only one that you want to return false on is one here because if you do one plus three that is less than five so you wanna return false okay and so to do this you can just do in one or two lines here um I'll just do it split apart here so the first thing you want to do is figure out what is the current maximum in the candies array and you can just do that by like maximum candies is equal to the maximum of this array and that will return five and then we just want to return an array of Boolean values and we want to return true if the current number of candies like current number is greater than or equal to the maximum candies after we add the extra candies to it and so that will Define this kind of our function for defining is it true or false and we just want to do this for every candy in our candies array great and that's it awesome so this runs in oven time um if you make a one-liner it'll be like um if you make a one-liner it'll be like um if you make a one-liner it'll be like oh of N squared because you'll make this you'll be performing this Max operation for every iteration so it's good to split these into two separate lines um so this runs an O event time because to determine the maximum that takes o of n because you have to iterate through every number and then for this you have to iterate through every number to see okay if we add this extra candies to this current number is it greater than or equal to so o of n time and O of one space so yeah I hope that helped and good luck with the rest your algorithms thanks for watching
Kids With the Greatest Number of Candies
all-ancestors-of-a-node-in-a-directed-acyclic-graph
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ `ith` _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_. Note that **multiple** kids can have the **greatest** number of candies. **Example 1:** **Input:** candies = \[2,3,5,1,3\], extraCandies = 3 **Output:** \[true,true,true,false,true\] **Explanation:** If you give all extraCandies to: - Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids. - Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids. - Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids. - Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids. - Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids. **Example 2:** **Input:** candies = \[4,2,1,1,2\], extraCandies = 1 **Output:** \[true,false,false,false,false\] **Explanation:** There is only 1 extra candy. Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy. **Example 3:** **Input:** candies = \[12,1,12\], extraCandies = 10 **Output:** \[true,false,true\] **Constraints:** * `n == candies.length` * `2 <= n <= 100` * `1 <= candies[i] <= 100` * `1 <= extraCandies <= 50`
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
1912
32
hi everyone welcome to this recorder this is raveena and uh today I am going to solve liquid problem number 32. I actually selected this problem based on the poll that I did last week uh and the based on the words uh the you guys want me to solve string problems so I'm gonna do that now I'm I will keep referring back to that post if you wanna just you know if you haven't seen it you can go in and just vote on what which problems do you want me to solve or you can do that the same in the comments below and tell me uh what kind of problems you would like uh to see on my channel and I will solve them for you okay so let's start by reading the question uh the question says that given a string containing just characters of opening parenthesis and closing parenthesis return the length of the longest valid well formed parentheses substring okay so let's look at example one here in example one if you look at this uh we want to find out the length of the longest valid parenthesis substring what does that mean is uh we all have done math uh in our school time so we have to find out what is the valid parenthesis substring uh so in this input s you see there's no there's an opening bracket okay now there's another opening bracket and then a closing bracket uh so if you look at this string you can uh you know make out that this is a valid substring and the length of that valid substring is 2 and that is why the output here is 2. uh let's try and see how we can solve this problem uh let me go back to my notepad Okay so the example here what I'm taking is I want to actually let me move this further okay uh I'm gonna take the example two which is close name closing okay yeah so uh the first thing the that I want to do is I want to have a left and right variable so that I can count how many opening brackets and closing brackets I have so let me do that I have a left initialized to zero I have a right parenthesis variable initialized to zero the next thing I want to have is the maximum length variable so I have my max length variable also initialized to zero uh I'm gonna start traversing through the whole string from left to right count the number of you know left and right parentheses and at the point where you my left number of left parenthesis is equal to my number of right parenthesis that's when I see that oh it's a valid string right it's a valid parenthesis so for example if you look at the if you look at let's look at the same one yeah if you look at this example uh if I at some points this is uh this means that right is one left is one right is one so uh if you look at this substring it says that opening brackets number of opening brackets which is 2 is equal to number of closing brackets which is two that means that is for a valid substring and that condition we are going to use in our for Loop when we see number of left uh parenthesis equal to number of right parenthesis we calculate the maximum length uh and then we update the maximum length if we have not find a maximum length yet uh we have we will we also need a breaking condition here the breaking condition here would be so suppose if I have this example right uh I have a closing bracket so it starts with a closing Market I have one opening bracket okay then I have another closing bracket so when my closing so is there a chance that uh this particular thing is a is ever going to be a valid substring because my number of closing packets are greater than my number of opening packets which means that I'm never going to find that opening bracket somewhere right it should come before the closing bracket so that means that if my right is greater than my left number of brackets I mean my left opening parenthesis which means that this is not a valid condition that's the time when we will reset our right and left to zero let's see how we can apply I mean let's see how to work through it uh it will be helpful to learn it better with your example first my counter is here uh I receive a closing bracket which is the right which is right for us so I will update that to one I then go to uh then I check if my left is equal to right is my left equal to right no it is not okay my next condition to check is add my number of write brackets greater than my number of left brackets yes my right brackets are greater than number of left brackets that's when I will reset my left and right to zero since my left was already 0 I'm gonna keep it that way and my right will again be reset to zero okay moving on to the next element I go to the next element which is another opening bracket when I received that I have opening bracket so I am gonna update my left one is my left equal to right no is my right greater than left no okay let's move on so I move on to the next element in the string I receive one closing bracket I update my right with plus 1 so 0 plus 1 is 1. now I check if my left is equal to right yes my left is equal to right I have left 1 and right equal to 1. I will calculate the maximum length now my maximum length will would be maximum of the maximum length or my uh you can say left press right or you can just say right into two or left into two so I would say maximum of 0 and my left plus right the maximum of 0 and 2 is 2 so I'm gonna update my max length here okay moving on I encounter again an opening bracket I will update my left to 2 with plus one is my left equal to right uh no is my right greater than left no okay move on I go to the next string so the next element I receive a closing bracket then I'll update my right to 2. is my left equal to right yes it is then I calculate the maximum length my maximum length will be Max of the existing maximum length or and my left plus right so maximum of 2 and my left plus right is 4 maximum of 2 and 4 is 4. okay sorry about this okay maximum of 2 and 4 is 4 so I update my maximum length to 4. moving on I again encounter a closing bracket since I encounter that I am going to increment my right to 3. is my left equal to right no is my right a greater than left yes that's when I will update my left and right to 0. this is first iteration now it can also happen that a sub substring is valid when you go from left to right but so it is not valid when you go left to right but there can be scenarios when it will be valid when you go from right to left um so some of the some one case that I can think of is you know this so suppose I start with my uh I start from my left I see okay I encountered an opening bracket I increment my left again opening bracket okay agreement my left and then I receive a closing bracket then I increment my right at this point we don't have we don't actually come across those two conditions is my right equal to left or do I have more write records than my left brackets in this scenario we might miss our valid substring so that is why we are doing two passes one from left to right and the other pass from right to left let's see how we can do it from right to left for right to left we are going to do the same thing uh oh sorry my max length would be 4 I'm gonna retain that the only things I'm going to change is my left would be initialized to 0 my right would be initialized to zero and let me delete this pointers as well okay I'll start from my right most element in the string I receive a closing bracket when I receive a closing bracket I increment my right to 1. I check if my left is equal to right no when I go from right to left does it make sense to check if my number of right brackets are greater than my left practice uh no uh it would make sense to check if my number of left brackets are greater than my right bracket when I receive an opening bracket I will have my initially I will have my left and right initialized to zero when I receive an opening bracket I am going to update my left to 1. now if you look at the scenario when your you're at the end of your string and you receive an opening bracket that means that you have your string has already ended and there is never going to be a closing bracket there and that's why that scenario is invalid that particular substance is going to be invalid no matter how left you go so in this scenario when you go from right to left you have to make sure that your left count never um is more than your right count and that is really important to understand you know why you are chain why you're checking for a particular condition when you are going from left to right and why you are checking the other condition when you're going from right to left so I hope this is clear uh let's uh move on with our example here let's see I already had my right as one uh let me move on to my next element where I have my and I get another closing packet so I update my right to two I check is my left equal to right no is my left greater than right no move on I receive an opening bracket I update my left to one check is left created if uh is left equal to right no is left greater than right no move on get another closing packet update this right to plus 1 which is three uh is my left equal to right no is my left greater than right no move on get another opening bracket we get two is my left equal to right no left greater than right no move on receive an uh receive one more closing bracket update my right to 4. is my left equal to right no is my left greater than right no now we have done our iterations from we have traversed the string from left to right as well as from right to left and check for our conditions that means that the maximum length that we have is this maximum length is 4 and so we are going to return this 4. now let's see how we can solve this how we can code this problem okay so the first thing that we need is my left is equal to zero my right equal to 0 and my max length which is also initialized to zero now we want to go from left to right so for every X in s I am going to check if my X is an opening packet if it's an opening bracket I would do left is equal to plus equal to 1. else it's a closing bracket so oh typo so I would do write plus equal to 1. when I increment my left hand right what do I check if my left is equal to right so if my left is equal to my right if that's the case then I calculate maximum length so my max length would be Max of max length or my left plus right else if uh my right is greater than left that's when I will reset my left and right to zero so my left and right will be initialized back to zero this is the first Loop when you go from left to right before starting the second Loop we have to make sure that our left and right are initialized to zero so that's why I'm doing this now I go for every X in my string and I'm going to reverse it right here so colon minus one makes It reversed uh so I'm reversing my string I am checking if my X is a opening bracket if it's the opening bracket then the same thing left today plus equal to 1 and my right would be plus equal to 1. here I check if my left is equal to my right if it's true then I am going to update my max length so my max length would be Max of max length and or my left plus right okay my left is greater than right if my left is greater than right that means I have more opening brackets than my closing brackets that's the time when you reset it so let's first write equal to zero in the end when everything is done when you have Travis it from both sides you return max length let's try and see if we can run this code yeah it's uh it's running so let me submit it okay so it's submitted uh let's talk about the space and time complexity of this problem so uh if you look at this you are traversing through the entire string just once so that makes and so here it's one time and then the other time is here so it's basically you know n plus n which is 2N and we actually discard constant uh when we took time complexity so the time complexity of this uh problem would be o of n when you talk about the space complexity is going to be constant because we are using just right left and max length which is let me just storing a single integer at a time it's not scaling so that makes my space complexity as o of 1. so I hope this uh explanation was helpful and if you like my videos give it a thumbs up or comment below uh it really helps my channel and if you like to see more videos like this please subscribe to my channel uh there's a similar uh there's the same explanation in Hindi coming up later this week so stay tuned for it as well thank you bye
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_. **Example 1:** **Input:** s = "(() " **Output:** 2 **Explanation:** The longest valid parentheses substring is "() ". **Example 2:** **Input:** s = ")()()) " **Output:** 4 **Explanation:** The longest valid parentheses substring is "()() ". **Example 3:** **Input:** s = " " **Output:** 0 **Constraints:** * `0 <= s.length <= 3 * 104` * `s[i]` is `'('`, or `')'`.
null
String,Dynamic Programming,Stack
Hard
20
341
Today's problem is to multiply the nested list. In this problem, you have been given a nested list. Every element of this list is a sequence or is another list in itself. You have to multiply this nested list and after that you have to implement some API. The first API is your naked outer, in this you will be passed the naked list, whatever is your naked list, you can store it or you can perform whatever operation you want on it, after that you will get two APIs. Next and HasNext will be given. First of all, HasNext API call will be made. In this it will be asked whether there is any element left in this list. If there is any element left, then return True. Otherwise, False is returned. If Next is returned as True. So the next API call will be and what you have to return in the next API is whatever will be your next integer in the next list, let us see it with the help of an example, we have a list here, in our list we have tooth element and our first element is y. There is a list in itself. What is the second element? What is your index? The third element is in itself a list. So when you flip this list, what will happen to you? You will start traversing from this. Whoever comes first is your one. Then whoever comes after this, has not come, then again, then, you will get a complete list of fingers like this, then suppose you call on this next, return me next, then in the beginning, you have to return this After that, the next call is made, because now these four elements are left in your list, you have consumed this element, even after that you have four elements left, so what do you have to return? Then if the next call is made, then which is our first element? This is it, you have to return this, then next time it happens, then this has to be returned, next tomorrow this will happen next, after returning this, now we have consumed all the elements, so if now what will our birth be equal to, then we will have If there is no element left then we have to return false here and here our program will be terminated. If you answer all the API results correctly then your program will pass. If even one API result is called wrong then your program will be called. It will fail like if this one call 146 what will become of our flat n list 146 this will become in this if we call next then our one will come then if we call next again then four should be returned then if we return next again then six should be called after this Our array is finished so here if we call has next then we have to return false. Before this if we call anywhere here then anywhere else then we have to return false. Now along with this we have given some helper functions like if We have to find out whether this current element of the list is an integer or is it a list in itself, like here this is our list and what is this integer, then if we want to find out whether the list is If this element is an integer or is it a list in itself, then for that we are given two APIs. We can call this API and from this we can find out that the current element we are looking at is Is it an integer array or a list? If it is an integer array, it will return true. If it is a list, it will return false. Now we know that in that position, suppose there is an integer array, then how can we get that integer array. What is the virtual value on that integer, which integer is it? We have been given API for that. If we call get integer, we will get the actual integer. Apart from this, we will get a get list. This API is also given, if we have a list on our current index, then that list will be returned to us, like first of all, what we will check is whether the integer is there or not, if it is true, our integer is then we get the integer. We can gate that entry with the help of key and if its result is false i.e. there was a lit there result is false i.e. there was a lit there result is false i.e. there was a lit there then we can gate that list with the help of get list, so basically we have to implement this iterator in which we are Integer Get List will use these APIs and we will have given three APIs. First of all what will be the API of Inila Ization then second next then has next we have to return the result of these three APIs. First of all give us the complete list of Nest List. If we want, we can store it here or we can fold it and store it as a flat list. Here we can do some operations with this list, after that our two API calls Next and HasNext are these two API calls. Whenever there will be next API call, what we have to do is where our index will be now, we have to return whatever integer is there and what to do in judge next, if we have not set all the elements then we have to return t. Now, how do we implement this? If we pass the list here, multiply it and store it in an array or a vector, after that what will be left in Next and A Next? Simple. We will need a variable so that we can track the current index. Suppose I have taken the current variable which is initially set to zero, then whenever my next one comes, what I can do is simple, return the current of that array, this one and then this one. Make the current plus. I have to return the current of the array as this element and then make the current plus. So how can I do this? Make the current of the array plus on y. Either use post comment operator on y or simple. I can do this by storing a drop equal to two arrays of current plus and return the drop, basically what I have to do is return the element of whatever my current is doing and then return my Let me increment this variable current, take it one step forward and what do I have to do in the next, wherever my index is, all I have to do is see that it is in my valid range, when will it be in the valid range, when my index is whatever. The size of my array or vector will be less than that, if it is equal or more then it means that we have exhausted all the elements and we will return the force, then simply what we will do is we will compare this current with our size, if the current is our If it is smaller than the size, then we will return t, otherwise we will return the result, so if we can store this list in an array or vector by flattening it, then simply we can call Next and Judge Next in this API. Don't do this, our code will be very simple. Now how to store this next list? To store it, suppose I take a vector, I will store it in a vector, what type should my inger be of type because I need to store it flat. If I want to do this, what will all the elements be of inj type, I will take a vector, now I need to get the next list, this list, what is in this list, here is my list, so first of all, what will I put, I will put a loop on it, then my denominator. Scan an element, whatever is my nested list, scan each element of it. First of all, I will pass this element. What is this element, is it a list, but I will not know directly, how will I know, I am the integer of this API. From the help you will know that I have given some interface whether it is an integer or not, then I will check whether x is my integer or not, I will call that API on this x and find out whether it is an integer or not. No, if it is an integer, suppose its result is true. If it is an integer, then simply what do I have to do, store it in the vector, what will I do, push it back in the vector, store it in the last part of the vector and how to store it. If it is an integer, then from where was I getting it? Get integer and get integer, I will call this API and store it in it. If I get the result false or it is not an integer, then what does it mean that it is a list and I will get the list. How to get the get list, I will get it from this, I will call this API and now I have got this list, if I want to calculate it too, then I will call this function recursively. Whatever we will write this function of ratio, I will call this function recursively. I will give you basically how we will flatten this list, we will flatten it using ration, we will first look at the current element, if it is our integer then we will store it in a direct vector, if it is not our integer then what can we do? We will first flatten this list recursively, store it and then proceed further. Once we see its overall code, you will understand better from it. We had to implement three APIs of this nest class I Traitor. Next Hydrator is our basically constructor function, then our Next API Our Edge Next API In our constructor, we have a list and we are saying that we will flatten this list and store it, how will we store it, which type of vector in one of our vectors, store it in a vector of type Inger. So we have written this function for that, what will we do in this function, we will recursively flatten our nested list, let us assume that our list is Y, let us assume that Y is our list, then we will loop over this list. How many elements are there in our list? If there is a Th element, then first of all we will pass this. This will come in our IT. The complete list will come. Now how will we know whether there is an integer or a list here? For that, we were given an interface. Was the interface an integer? If this element is inger or is your list then we will call this ae inger. If its result is true i.e. there is inger on its result is true i.e. there is inger on What will we give inger er and it will return whatever is inger if its result is false, what does it mean, there is our list and we have to flatten it, then we will call this function again recursively id getlist. What will we get from this? Here we will get our list and we will send it to Phaltan to flatten this list and then when it returns here, we will come back in the loop and pass the next element to our two. If we do, overall our flow will run like this, first of all we will come to this loop, when we will pass inside it, then this element of ours will come in the starting, from here we will check whether it is integer or not, if not then we will come to else. We will go to it and getlist, basically what will we get from this, we will get this, we will pass it to our receive function, then in our receive function, we will have a loop on this, what does it mean to have a loop on this, one element is this i.e. That first we will loop over this element, is this i.e. That first we will loop over this element, is this i.e. That first we will loop over this element, then what will happen, we will check whether it is an integer, yes, this is a single element, so here it is an integer, so we will store it in our answer, so what has come in our vector now, one has come. Then we will move ahead, come to its second element, check it, if it is also an integer, then we will store it too. Now this loop of ours will end, then we will come to its end and will go back here from where our recurse call was made. What was there in that? Now this element of ours has passed, so now the next element will go to this. Green foreloop was going on. Will go to this and will check this. What is this is our index, so we will store it directly. We will store it on this. We will come back to this loop, now our element will come, now what is this is a list, so we will come to Y, we will recursively pass this list to our function and then we will loop over it again. What will happen to us while taking it? Three will come to this is an integer, we will store it, then the next will come to this is also an integer, we will store this and then our loop will end, then we will come back here from recurse and go to the next. Now our If there is no element left then that means our original relation will also be terminated and what list will we have stored? 1 2 3 The list of our next list has been stored in flat N form. Now what do we have to do after that? We will have next and has these two equals. To track where our index is now, we have taken the current variable which will track where our index is now. Starting, our index will be on the row, so we have stored the row in it. We have col is next what we will do is what is the size of our list 1 2 3 4 5 is five we will compare row with five is less that means we still have elements left in our list right now we have elements left in our flat n list so we From here we will return two. If we return two then our next call will be that tell me then which is the element on this current index, then what will we do? Answer of current, we will return whatever element is on this index and along with it our Index current plus means now our index will come to this one. Our index was earlier at zero. Now what will happen to us? It will become one again. Next will come to us because of this we will return T. Why is lane F? We will return T. If there is next, we will return no and now what will be our current? Next will we return lane is 5, then next will come we will return two and take our next one forward. Now what is our current? Will come to three. If th is still smaller than f, then what is the output of the next? If it comes to true, what will we do next? We will return three and take our current to four. If four is still smaller than five, then there is The output of next will be true. We will return this three in the next API and will take it to our next current. Now what has happened to us is five. I will compare less than five. What happened if this condition fails then what will my next return? It will return false and as soon as it returns false, our next e- soon as it returns false, our next e- soon as it returns false, our next e- call will not happen, our program will be terminated, after that only what our program will check is whether the value given to us was correct or not. If it was correct then Our output is correct, otherwise if our output is not correct, then your entire program will work in this way. What will we do in this? Initially, we will store our next list in this form, after that we will return the result of both Next and HasNext. What will our overall tongue collection take? If you look here, we were traversing the list, we were traversing each element once, like what was our list, vv 2 3, this was our list, what were we doing in it first. We were doing this element, then we were doing each element inside it one by one and then we were moving ahead, then our total number of integers will be 1 2 3 five integers, that is the number of times our traversal will run recursively. But each element is being traversed only once, so what will be our tangent of this function? Whatever will be the total elements in our next list, then comes our next A. This is our off one and J is the next one. If our A calls are of one, then both of them are the same. If our A calls are there, then the total time will be the same. This one is also of A. This one is also of ours. If our A calls are of ours, then both of them will run only once, so each one of ours will take only one time. What is of A type, then overall, what will be our time and what will be our space? We have taken a vector to store this list. How many elements will be stored inside this vector, as many integers will be inside our original nested list. If we consider it as n, then our total space will be of this size, then what will be our time and space complexity? Thank you guys.
Flatten Nested List Iterator
flatten-nested-list-iterator
You are given a nested list of integers `nestedList`. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it. Implement the `NestedIterator` class: * `NestedIterator(List nestedList)` Initializes the iterator with the nested list `nestedList`. * `int next()` Returns the next integer in the nested list. * `boolean hasNext()` Returns `true` if there are still some integers in the nested list and `false` otherwise. Your code will be tested with the following pseudocode: initialize iterator with nestedList res = \[\] while iterator.hasNext() append iterator.next() to the end of res return res If `res` matches the expected flattened list, then your code will be judged as correct. **Example 1:** **Input:** nestedList = \[\[1,1\],2,\[1,1\]\] **Output:** \[1,1,2,1,1\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,1,2,1,1\]. **Example 2:** **Input:** nestedList = \[1,\[4,\[6\]\]\] **Output:** \[1,4,6\] **Explanation:** By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: \[1,4,6\]. **Constraints:** * `1 <= nestedList.length <= 500` * The values of the integers in the nested list is in the range `[-106, 106]`.
null
Stack,Tree,Depth-First Search,Design,Queue,Iterator
Medium
251,281,385,565
1,012
Hello Everyone I am Jaysh Today in today's video I will be sharing with you how I studied Digit DP. How I asked myself this question, what was my thought process and while solving and practicing DP, what were the patterns which mostly helped me. Which seems important and on which a lot of questions have come, which is actually correct, I will be discussing in this video, I will also provide the pseudo code and the C plus code to the two one of the questions which I find quite interesting and It is basically easy for a beginner who is doing Digit DP question for the first time or seeing this pattern for the first time. Ok let me show you the question. Numbers with Repeated Digits is hard as you can see it is a very basic question. There is nothing much in it, if you know Digit DP then you can do it very easily. And this is not the most optimized code but as a beginner you will understand it very well. Okay, so let's start. Let's start then see. It is very important to understand the pattern because without understanding the pattern, you will face a lot of problems. The first step is to assume that you have been given a number whose range is anything greater than zero. Do not assume the power of 10. Whatever is the range of two integers, it is okay from one to basically. What to do? You will be asked in the question to tell the count of the numbers which are following some pattern from one to A. Do you understand? Like suppose one to A. Tell the count of those numbers which have unique digits. If we take the example of this question then it is ok. Have unique digits. Now the second pattern is A and B. Two numbers have been given, you have to calculate from A to B basically and this will be the range from zero to 10, it is okay to calculate the same count separately but this pattern is not covered in this video. I am doing this, tell me in the comments, if you want this also, it is quite simple, if you know this, then it means you will do it yourself, you will not even need me, but still if you feel like it then definitely write in the comment, I will definitely make it. In this video ok moving on now watch if I tell you one to a I suppose a is 10 tooth 4 5 6 7 8 na 10 let's take this a little bigger let's take this 1 let's take 12 1 ok tell me the count of those numbers In which there are only unique digits, that means you cannot count, neither has it come twice, nor has it been done twice, there is nothing, so it is clearly visible in this, apart from all of them, they will be counted, but only if I use the power of 10. Understand, if I take it to this range, then how will you do it? Any brute force or any L will work. This question will be asked from DP only. What is the right thing to do? Basically, what needs to be done in this question is that n is your number and you have to convert it into a string. Because after converting it into a string, it is a string of only nine lengths. Now you are feeling that it is a string of only nine lengths, which means that we do very basic. When we come to questions with such small constraints, then it is okay. What is the suggested number? T is a string of length 4 5 6 4. Now what can happen is that every position is filled, I can put any of these numbers, plus the number will sit at the last and it will be smaller than this number. We need to keep these two things in mind, so how do we do it? Basically, we propose a memorization function like this. Basically, an e is equal to the index. If you don't know, let me tell you. Basically, you must have definitely seen something like this. You take a vector, it is divided, okay, take 10 digits, divide it with zero, so now what are you storing in it, suppose you took a number, in the first position, what did you do, you divided it with zero, everything else is zero. It means that all those numbers have not been used till now, the number which remained or is not yet mine, understand that basically it means storing which numbers have been used, it is not connected with Kanan, we have to create a number of one digit, okay, so this mask is basically Because Apna number can only go up to nine digits, then what can Apna do? Because there are only two digits from zero to no, then what can Apna do? Instead of taking this vector Apna, we can give one integer to the power of two. In which we will check from the bit representation that the number is present at one zero position, if the th bit is present then it means zero number has come in the number and if zero has not come in the same position, if it is one then n is in the second position in the number. Presentation of the Mask G et Okay, so you understood, basically this function is something like this: basically this function is something like this: basically this function is something like this: Index, equal, mask, base, there are three things will be useful for you, now see, let's assume, I told you what is equal, otherwise I told you. I have seen that we will go to the same length as the string and I have also seen that we have to connect through the mask, one number will come only once, but as I told you, now I should keep it as 5. What should I keep in my DP, where should I keep it, my month will not be crossed, my code will not be crossed, both are correct but this number is obviously bigger than this, so it should not be counted, neither do we use it for that. Basically now what does equals do? Like suppose initially its value is one when something comes equal to zero. Basically when you are starting the dimension question then you check whether whatever number you are entering in this position is Is it equal to this or is it greater than this? Basically if it is smaller than this means I propose here one for instance two, it will be easier to explain. Okay 3 56 Suppose this is one, so now if I say or 8 I can do anything. If I keep it won't make any difference, if it gets smaller from here, it will be smaller in the future, but if I keep this th then I will have to check for the next index also, so the work of this one is that as long as it is equal to one here, I can place my number only till the number of that digit, that is, if I is equal to one and I am in this position, then I can place 3 then F, some of it can be placed in this position, 6 to 8, yes, I cannot place all of it, ok. Yes but if it is zero then I can put anything from zero to zero. This happens. Okay, so you understand the significance of 'e equal'. I have written it 'i' understand the significance of 'e equal'. I have written it 'i' understand the significance of 'e equal'. I have written it 'i' because it is short for 'e equal' so because it is short for 'e equal' so because it is short for 'e equal' so when I used to code, I used to write names like this so that when you are doing the work, if there is any mistake in the code in the last section then it is easy. If you keep good names then it is ok. Now let's see the basic pseudo code. Let's see in this particular question what is it. See now. It says that given number of positive digits you have to make count in range and to have at least one repeated digit so that at least one digit must be repeated, the question is the same, there is just a little twist. Now let's go back second. Now understand whether the 13 that was your example from your father is this one or now he is saying give me that number in which the atlist is one repeat, so now we have only 11 from here in which the atlist is one repeat and the rest is If it is not there, then your first answer was everything except 11. Now the answer is only 11, so basically from the exclusion-inclusion is only 11, so basically from the exclusion-inclusion is only 11, so basically from the exclusion-inclusion principle you can say that n pw minus whatever is your answer, do not count how many variations there will be, this is your final answer. We will extract this from our DP, then it is simple maths, so this was the foundation of this problem, it is completely fine, let's come to the pseudo code, how this happened, basically, the pseudo code is something like this, C is equal eye and mask, yes, closed. Now see, I told you that whatever is the max, if it is equal, then you should choose the number only till this digit, not smaller than that, not bigger than that, but the max remains which I am saying if it is equal. If not, then we will convert it to max, whatever that string is, its integer value, otherwise we will put our nan or whatever we get. Now we will go from zero to max in the for loop and place each number in the right position and see but it is unique. Also look at yourself, we will check with the mask that if that person is already there in the mask, basically yes, consider it as digit D. IG, if it is already there, then you continue, if not, then consider it as digit Y at this place. Now you update the mass and pass it equal to one, if your digit is equal to max, if the digit is equal to max then don't send it, send zero, simple and no updated mask in mask. By doing this, all the possibilities will be accessed. Do you need a count of answers? Make one answer, make it zero, do whatever you want with the function, return it in the end, and this way your count will come. Okay, understood. Let's look at the proper code. C Plus. This is the code of PS, see the same thing, if it is DP, first I have calculated the max function here, if it is there, then the over number is equal to it, then no, the answer is zero here, this for loop is from zero to max now. This max and one day shift, if means it is within the same month, I am checking through binary if it is there, then it is not a content, no, by doing this, right here, as you can see, I have made a FDI D, it has come from the fourth factor. This is this is also sending some forest in the beginning, is this a small catch, if you have got it, then pause the video and write in the comment. If you haven't got it, then let's explain then see what is suggested. Why will this code fail? Think, now this code will fail because you have not seen this case. You are saying that put any number from zero to max, any one is fine, 00 0 and none are the same, all three are fine but if If you put zero here, then in your code, are you setting it in your mask that now zero has been used, it is written, so now you should not put it back, then if it happens, then you have created this number once or zero again. You can always propose that if you are number two then you will never be able to make it like this. You have kept it zero for the first time. Now you cannot keep zero on this. You will have to keep something, then you will become number one, otherwise you will not be able to reach number one, otherwise you will have to handle that case. A is kept that as long as there are only zeros behind it, you keep keeping zeros, but as soon as another number comes, then I update the A root basically that now I will not use my zero basically because the zeros before it are just Useless and is of no use. Yes, it may be no, but no, these two zeros have no meaning. Actually, it is only 10. These two zeros are their own because they are working in their own string, that is why we have to see this case. Okay, here it is, let's run it and see. Okay, submit all three test cases and see, it shows 'Accepted'. see, it shows 'Accepted'. see, it shows 'Accepted'.
Numbers With Repeated Digits
equal-rational-numbers
Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_. **Example 1:** **Input:** n = 20 **Output:** 1 **Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11. **Example 2:** **Input:** n = 100 **Output:** 10 **Explanation:** The positive numbers (<= 100) with atleast 1 repeated digit are 11, 22, 33, 44, 55, 66, 77, 88, 99, and 100. **Example 3:** **Input:** n = 1000 **Output:** 262 **Constraints:** * `1 <= n <= 109`
null
Math,String
Hard
null
1,328
so today we're gonna discuss this question from bi-weekly contest 18 question from bi-weekly contest 18 question from bi-weekly contest 18 problem number one three to eight break a palindrome so in this you are given a parent drumming string as an input and you have to replace exactly one character by an lower degree settle a little bit so that the string which is sawn should be less so graphically small is possible and that shouldn't be a palindrome itself as you can see from this example this is a and we can put if I convert this B to a then this is the least like so graphically possible string and did not also a palindrome and if it is not possible to convert then we have to turn an empty string as you can see in this because it'll be converted in any other like if we have to at least and put exactly converts one character this is one that if I can apply to any other you like BC it also again remains a Pinto and it doesn't satisfy this condition so we have to return an empty string so what we can do is as you can see in any palindrome which is of even size if we change any tag term it will become non palindromic as you know because it is a mirror image of itself and in odd number of the linndrum odd number window if we have to change if we can't change an alphabet before the index of its middle then it also will not become a below after the things let me tell you in this example so as you can see this is a palindrome if I change a to be so it will not be a Pinto but it will not be the least like so graphically smallest alright so what we do is to be least extra graphically smallest less example just seems like we have to be we have we should have is max - max possible from here have is max - max possible from here have is max - max possible from here from the starting because as you can imagine it the numbers take example with numbers if you have one four five and if you make if one cannot go beyond because it will become zero but if you want to make it a three-digit number it a three-digit number it a three-digit number but smallest what we can do it we make we should make it one also well and if zero is not allowed in this case so we should also make it one so what we do is we Traverse from left to right and if we see any of the element which is greater than P we should convert it back to it so it is very much so if you can write back to it will not be a palindrome anymore and it will be like so graphically smallest so in this case we just converted back to it and it will be the case for this case if the string length is less than 2 then it is not possible at all in this case because this is this if we move it here from here to here then as we can see we draw a middle line so we check with this and this it is a Potomac string but we cannot change both of this as of it to anything most for the small so in this case what we'll do is we'll move from now from back from right to left and if any alpha between counter is smaller than Z will make it Z so take this example only if we have this number so if you cannot change this then we have to change this now at the last number so we can change this to 1 but if we change it will also become palindromic so we can change it to anything like 9 we just put it 9 because it will be a simple logical so let's get it moved here with the code if the size is like less than or equal to 1 then x will be a null string empty string sorry then we first move from 0 to 2 less than n by 2 and if we encountered anything greater than a then we make that position of s equal to a and then return the string if anything is not satisfied in this loop then we move from back to the front and anything we encounter like smaller than said we increment it increment that number because that will be the lexicographically nesting legs smallest one so then we turn that and after that we just return the empty string if none of these conditions are the importance so I hope you understand the logic thank you for watching and I'll see you next week
Break a Palindrome
monthly-transactions-ii
Given a palindromic string of lowercase English letters `palindrome`, replace **exactly one** character with any lowercase English letter so that the resulting string is **not** a palindrome and that it is the **lexicographically smallest** one possible. Return _the resulting string. If there is no way to replace a character to make it not a palindrome, return an **empty string**._ A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly smaller than the corresponding character in `b`. For example, `"abcc "` is lexicographically smaller than `"abcd "` because the first position they differ is at the fourth character, and `'c'` is smaller than `'d'`. **Example 1:** **Input:** palindrome = "abccba " **Output:** "aaccba " **Explanation:** There are many ways to make "abccba " not a palindrome, such as "zbccba ", "aaccba ", and "abacba ". Of all the ways, "aaccba " is the lexicographically smallest. **Example 2:** **Input:** palindrome = "a " **Output:** " " **Explanation:** There is no way to replace a single character to make "a " not a palindrome, so return an empty string. **Constraints:** * `1 <= palindrome.length <= 1000` * `palindrome` consists of only lowercase English letters.
null
Database
Medium
1317
412
hello everyone welcome to the channel today we are going to solve lead code 412 fbus so we'll be given an integer array n as an input we need to return a string array of size n so they have given as a condition four conditions so for each element that we are going to visit in the range n if the visited number is divisible by both three and five we need to open fist bus to the result if it's just divisible by only three we just need to open F if it's divisible by only five we need to open bus if none of the cases match what we are going to do is we just need to open the number to the result but in a string format let's go to an example so given an input number three so we will be visiting three elements here which is 1 2 3 so for each number one we are going to check all these three conditions if one is divisible by three and five no it's not divisible by three and five so the next condition is if one is divisible by three no that's not and the third condition is if one is divisible by five no so what we're going to do is we need to upend one to the result but in a string format and then we going to go to the next element likewise two is also not divisible by three and five so we just need to open two as a string and the last element is three we know three is divisible by three so what we need to do is we just need to open F here and this is our result so likewise we have two more examples here so this is the let's go to the approach first step we have to do is instantiate resultant two store result second step is we need to iterate through all the numbers in the range n so H trate through each number from one to y while we are iterating we need to check if the number is divisible by three and five we need to open Fus to the result if that's not the case and if the number is divisible by just three then we need to append this to the if the number is divisible by five then append thiss to the result if not of the case match just up string of number to the result after this we need to do return result so yeah this is the approach now let's look into the code go so we have in initialized the resultant array and now we have to iterate from 1 to n so we have setting I equal to 1 here and so I will iate from 1 to n and if you look at the end the I will be incremented by one at each run so first run it will be one and the next run it will be two and so on and so for until it reaches n so the first condition we are checking is if I is divisible by 3 and 5 if that's the case then we are opening F bus if that's not the case then we are going to if condition so in a if we are just checking if I is divisible by three if that's the case we'll be appending this if uh I is just divisible I we'll be appending just bu if none of the CES case match es we'll be just opening string of integer to the result and at the end of Y Loop we'll be just returning the result so yeah that's it thank you
Fizz Buzz
fizz-buzz
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_: * `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`. * `answer[i] == "Fizz "` if `i` is divisible by `3`. * `answer[i] == "Buzz "` if `i` is divisible by `5`. * `answer[i] == i` (as a string) if none of the above conditions are true. **Example 1:** **Input:** n = 3 **Output:** \["1","2","Fizz"\] **Example 2:** **Input:** n = 5 **Output:** \["1","2","Fizz","4","Buzz"\] **Example 3:** **Input:** n = 15 **Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\] **Constraints:** * `1 <= n <= 104`
null
Math,String,Simulation
Easy
1316
1,763
welcome back daily lead coders daily leak code lead code daily Elite code day 52 we're back once again uh yeah we're back once again we just got off uh we just finished talks with uh Elon and Joe Byron we're making sure that we're allocating uh I think the about 33 percent of the US's available networking resources and we're rediverting it to the HCC which is the hyperbolic coding chamber so we found a way to get about 100 million more spots so feel free to join it's very important also I missed a comment in the last video by the legendary Thomas Wong it's part of the game Brother Gotta a see those mediums like slicing Butters actually facts brother and so he mentioned 1763 longest nice substring don't cheat with Brute Force so I think we could try this problem but I'm pretty sure we're gonna get cooked we're gonna get baked give me one second so I just pulled it up oh okay it's an easy okay so I thought it might be something crazy I thought it might be like a medium but honestly sometimes the easiest are harder than the hards so we might get baked by this might be okay it's one of those problems those easies where the start right it's easy to get a simple solution rather than getting to linear times where the hard kicks in so I will try my best got done so I don't think we're going to do this problem today actually yeah I don't think we're gonna do this problem today since we have to we're they're still o1 Matrix right actually my brain is kind of fried I don't know if we're going to try a one Matrix again the optimal solution I think the optimal solution is dynamic programming and if that's the case then oof right definitely so maybe we'll just actually do longest nice substring today like Thomas mentions and then see how we're feeling but make sure to join the hyperbolic coating chamber this is a hyperbolic Time Chamber to 10x 500x your current skill levels so you're going to want to make sure you join if there are hundreds of hundreds uh um hundreds thousands of people joining and since we just got about 33 of the US is a networking resource allocated for the HCC you know it's going to fill up pretty fast again so just make sure you join and yeah we're just going to jump in we're gonna do a shorter session today since my brain is a little fried so you have a string s is nice if for every letter of the alphabet that s contains this thing is nice if for every letter of the alphabet that s contains it appears both in uppercase and lowercase for example a b capital A B is nice because a and a appear B and B appear however a b a is not because B appear it's not because B appears but capital B does not appear interesting so we have yazay and I think this should be false right wait oh wait no for every letter of the outfit that s contains it appears both in uppercase and lowercase given a string s return the longest sub ah interesting the longest substring of s that is nice if there are multiple returns ah the string Assumption of the earliest occurrence if there are none return an empty string interesting the longest occurrence or the substring for the longest substring of s that is nice you can return the longest substring of s that is nice if bb is nice string becomes both B and B appear right the longest substring we actually have to return the actual string from the a lowercase large a lowercase a there are no nice substrings this is interesting so I'm thinking there is no follow-up to so I'm thinking there is no follow-up to so I'm thinking there is no follow-up to this our ABA is not because B appears the B is not so just to generate some solutions it seems like I think our best conceivable run time for this we know from Thomas's linear time so linear time is possible but finding the longest substring means we can't rearrange the strings the longest substring the wait is nice because a slash a is the only letter of the alphabet and S wait a and a appear and B and P B and B appear however a b a is not because B appears but B does not so I'm not actually understanding that is a slash a is the only letter of the alphabet in s well z and y are also in the alphabet and both a and they appear a is the longest and substrate so I think maybe we could do a sliding window pattern solution here imagine we have a window right we have y right we know that this is not a nice substring right and then we have a we know this is still a not a nice substring right maybe we have a map of our window right we'll know that it's not a nice string right we'll add Z or add Z right but we still won't be a nice substring then we'll add a into a hmm how is this an easy longest nice substring maybe I'm over complicating it with my potential ideas appears both an uppercase and lower maybe I should have tried this with a fresh brain did like six hours seven hours for example a b a BB is nice because a and a appear and B appear however ABA is not because B appears but B does not sliding window definitely doesn't make sense here particularly because it's hard to know when our window should grow and should shrink maybe we could create the sliding window anyway the time complexity would be pretty crazy but even then if we have a window right I think what we could do is we could start right we'll start with a string we'll say okay we have a nice such thing right and we have another string it's not a nice string anymore so then we'll restart we'll have a we have a string we had another one it's not a nice string we only have Z you add Z it's not a nice string we had a it's still not a nice string then we add a it's not a nice string at a it's a nice string you get another a it's still a nice string we have y it's not a nice string so we'll restart hmm a is a nice string because a slice a is the only literally oh yeah my brain is absolutely fried I shouldn't have tried a new problem and BB is a nice string it's both B and B appear the whole string is a substring and we have overthinking well if we go with our original answer of the next string having to make it a nice string before we start that we miss versions or we could have a lowercase a and then capital a or even the string s return the longest substring of s that is nice if there are multiple turn the substring of the earliest occurrence there are none since they say you want to return the subjecting of the earliest occurrence and we're likely going to be moving sequentially through the array that means we could do what we said earlier maybe there's a way we sub-string right s that is nice there are multiple return the suction of the earliest occurrence that yes a lowercase y this however a lowercase B capital A is not because B appears the capital B does not I think there's probably also a divide and conquer approach here as well um if y a z a capital a lowercase a y let's see if we can get a hint Brute Force well we could have done Brute Force right so maybe let's see if we maybe we'll find some intuition by fluence in Brute Force right foreign double for Loop we'll have y and a so we start at y right we start at Y and then we'll pretty much iterate Until the End right and build a string we're going to see the longest substion that exists at this index and then we go to the next one and so I think what we could you could do that right in that sense we would be generating uh all nice strings set this equal to an array to start and we would have a semicolon we have all nice strings we want to do a double for Loop right we'll start at Y and then for y we'll see how far we can go uh to see if a string is wait a second blue foreign approach where we could act if we wanted to return the longest possible nice string without actually returning the actual string I think we could do that but it would just be like subsequences so that wouldn't actually make sense The Brute Force approach we start at y a z and how does this generate I guess we could like they said check each substring to see if it is nice because we basically have to have an is nice function if you have a function that is nice right we're going to do four lit I is equal to zero I is less than s dot length by plus and we're failing Thomas here because he wanted a non-linear here because he wanted a non-linear here because he wanted a non-linear solution but we'll get there uh I could change the J right J plus and then we'll create a string we'll say con string will be equal to uh an empty string to start and then we'll add a character to the string now we'll check if it's nice first so say is nice string and if it is then we want to do all nice strings dot push string right and then afterwards we'll do string plus equal a string plus equal S Sub J and then for is nice give them given a string or you want to be able to tell that it's nice and I think if we're given a string like yeah then for a particular a capital a lowercase you want to know if it's nice and we could load the values yeah I think the good point to start with this problem is how do you tell if the string is nice you know the string is nice if for every letter of the alphabet as contained it appears both an uppercase and lowercase so I think we could do that in linear time with linear space with the set and so we'll return a Boolean value it'll be two linear iterations to the string one to set up the set will have a set of strings basically these are just going to be one character we could iterate through fur const car of s if there's a new set dot add car so now we'll have every character in s in a map right and then we know that for every layer of the alphabet the S contains it appears both in the uppercase and lowercase so to do that right we'll return false in the case we can't find this actually we'll return true right and then we'll iterate through the string once again and we'll say if set dot has car dot two lowercase or ifset foreign ER case or set does not have car.2 upper car.2 upper car.2 upper case right then we will return false so if the set doesn't have an uppercase right or maybe it has lower case so it doesn't have uppercase or it has up cases have lowercase you want to return false otherwise we'll return true right then afterwards we'll have a list of strings which we'll want to sort right and we'll say strings dot sort a comma B right a DOT length which would be an array is less than b dot length then we could return all nice strings except zero there's always at least one character in s right and if there's another thing we have to check right uh if right we'll say all nice strings that length is not if it equals zero then we'll return empty string otherwise we'll return the first element and let's see if this makes sense forgot to use the function to lowercase let's have a power type string topic does not exist on type strings you mean oh it's a yeah uppercase C and our string is a constant let's change this to a let okay interesting so we're getting nothing so we have a string right called yes a right we start at index zero which is y and start at index J which is zero and then at y we'll say is this string nice right it's not right so we don't push it and then we'll add y to our string then we add a is it nice no then we add Z nice no then we add a nice no and pretty much it's never nice but it should eventually have some output right when we get to this version right here I wonder is nice might not be returning the proper output or we can also test right so just for this case we'll test that the string AAA is nice and we'll print that to start this is to make sure that is nice works so these nice does work foreign string to see what's going on here oh I see what's happening we're starting at right so we want to say J is equal to I to start right so we should be getting some of that we're actually getting AAA as a potential value so we check if a is my string if it is we push it then we add a character then we print it foreign yeah I'm not understanding let me print is nice up here and I think we might have an ordering issue now we should have a year um we're adding the string yeah I'm oh is there no there's not an extra space with printing console.log string we're saying is a console.log string we're saying is a console.log string we're saying is a nice screen oh an empty string is also I see I think we can tell actually if we print right I think if we print all nice strings we'll see that empty string I think is in there right so there's actually a couple of empty strings in there that's actually interesting I wonder oh I guess because we're starting yeah we check if the first string I see so I think we want to do is you can delete this line and we'll basically say right if F dot length equals zero we'll return to false right it's not a nice string that way our data won't be skewed towards empty values oh and then we wanted the longest substring so if we wanted the longest substring I'm also yeah this after we want the longest substring right so if that's the case we can do B minus a DOT length and return the first element which should be the smallest I mean the largest and I remove console.log some reason we're returning empty string here it's just strange you shouldn't have any more empty strings so for I is equal to zero right we're going to start with the string we're going to set start with b right we check if the empty string is nice it's not so we add a capital B which I have capital B is nice right we'll say J equal to I so d0 right we check if the string is nice empty string it's not so we add a character so I'm thinking I think you now actually want this up here this very slow solution and there's actually no solution given up so I think this would be uh this would actually be we have a double for Loop so we have N squared time but our solution to check if something is nice is at worst case we're iterating over the entire string so I would actually say this is n cubed time in the worst case so this maybe there's a linear times solution um what if we remove the pair so if we had this string here a y we removed these two y's that we A and A right there would be three strings left this would be what we have remaining doesn't seem like a viable option what if we only remove pairs that have a uppercase and a matching pair have y here y hearing with a and a that's the case then longest string used to so it's actually not the string you want we want a capital a lowercase a so if we had a how could we make this hmm b we have capital B lowercase I mean this one makes sense right s foreign I think I know what we could do so what if we have a sliding window we have y a z right and then as we iterate through what we'll do is we'll make certain right on each iteration we should be able to tell in constant time whether or not our string is well it wouldn't be constant time this would be I think in worst case it'd be N squared times would be an improvement we'd have y right we check if it is a nice string they would have y a right and it's not a nice string no that wouldn't work either because we want a greedy version hmm want a linear time solution linear time is interesting what if we did this add addition and subtraction right no that doesn't quite make sense okay well if we know that the nicest string has let's read the problem for every letter of the Opera that has contains it appears both in uppercase and lowercase given a string s return the longest substring of s that is nice longest solution is at statistics if there are multiple return the substring of the earliest occurrence hmm none return an empty string that one is yeah the linear time here is very difficult to be like our current version is n cubed related topics hash table dividing I knew there was a divide and conquer a solution to this I knew there was a divided in conquer it's also a bit manipulation I knew there's something there with that so I know you can add I think we could add right we add foreign we can check if a substring one way we can check if a substring is nice we could also use this version uses two for Loops over s another version right you could iterate through the string or I would have y right and we'll check we could have a map right of character to put currencies and basically we'd want pretty much yeah this one I'm gonna have to we're gonna we're definitely gonna have to get back into the lab on how to make sense of linear time solution here but he's been we I did like six or six five six hours today it's been 30 minutes uh on recording uh my brain is just right so
Longest Nice Substring
all-valid-triplets-that-can-represent-a-country
A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not. Given a string `s`, return _the longest **substring** of `s` that is **nice**. If there are multiple, return the substring of the **earliest** occurrence. If there are none, return an empty string_. **Example 1:** **Input:** s = "YazaAay " **Output:** "aAa " **Explanation: ** "aAa " is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear. "aAa " is the longest nice substring. **Example 2:** **Input:** s = "Bb " **Output:** "Bb " **Explanation:** "Bb " is a nice string because both 'B' and 'b' appear. The whole string is a substring. **Example 3:** **Input:** s = "c " **Output:** " " **Explanation:** There are no nice substrings. **Constraints:** * `1 <= s.length <= 100` * `s` consists of uppercase and lowercase English letters.
null
Database
Easy
null
468
hello everyone.welcome the hacker key in hello everyone.welcome the hacker key in hello everyone.welcome the hacker key in this video we will look into solving the problem validates IP address it is a medium problem but it's very straightforward problem before we start please do like and subscribe to the channel hacker d let's look into this given a string we need to determine if it's an ipv4 or an ipv6 so let's look into the characteristics of ipv4 or ipv6 so for ipv4 if you look into this there will be four segments for ipv4 so the total segments will be four and these are separated by dot and for ipv6 these are separated by colons and there are eight segments 1 2 3 4 5 6 7 8 so 8 segments we need to check those and the maximum IP is 255 dot 255 the segment should in be greater than 255 and the values for the segment should be between the each character should be between 0 and 9 that is 1 check we need to do and we also need to check that are not trailing or prefix dots similarly in ipv6 what we will check is the length of each segment should be between 0 to 4 and the character in each segment should be between 0 to 9 or a too small F or capital a to capital F the third we need to check if all this checks are past we would return either ipv6 or ipv4 if none of them passed you just return neither let's go ahead and quit this out so the first thing we need to check is if the given IP is equal to null or IP dot length is equal to 0 we'll just return later now we need to check if IP dot contents of dot we need to check for check IP of IP and IP dot contents : we will just of IP and IP dot contents : we will just of IP and IP dot contents : we will just return check IP v6 of IP all right none of them we will just return neither now we need to define these functions mix check ipv4 IP let me copy this and say few seconds get six so we talked about it we need to check for ipv4 there are no trailing dots if IP dot third of 0 is equal to dot of IP dot butin I'll go ahead and define a string so that I don't have to write neither all the time and now that is done we will divide this IP into segments now we will check the number of segments should be four if not we will just return neither and that's it now for each segment what we need to check is we need to check segment length should be between zero and three and if there is a start in character starts with zero the length of the segment should be one you can check that condition all Sigma dot carat of zero segment dot length rather than one just return and now we check that for each character in the segment we need to check it's between 0 and 9 is I 1009 just written and now we will check the integer value of the string should it be greater than 255 future dot value of segments greater than 55 return and if everything looks good we'll just return for now coming to the attributes we will I'd be dot make the copies in a few seconds it will be looking for Poland not a dot go gesture jump and maybe we will split into segments with all four color and check a sec mins dot length not equal to eight for ipv6 it should be eight let me just return n now for each segment we need to check a segment then put a zero dot greater than 4 in ipv6 each segment is of length four just written on that is good for we need to check that each character is then say twin dot plus the end upon a character I now we need to check if it's between 0 to 9 it is tablet capital f no see rather than equal to 0 or equal to mine and I can cover this and you chose between 1/2 capital a to capital F just between 1/2 capital a to capital F just between 1/2 capital a to capital F just written and everything is good 210 ip6 all right let's go ahead and submit hmm care cannot be converted into cash sequence oh this is string dot always something right bunch of typos sorry about that all right here we go I hope it's clear all we are checking for if it contains dot will check for ipv4 if you don't condense a call and we will check for ipv6 in ipv4 we will check there are four segments and each segment length is between 0 to 3 and the characters are between 0 to 9 for ipv6 we will check there are eight segments if the length of the character segment is between 0 to 4 and for each character is between 0 to 1 9 a 2 small it is smaller and calculated capital F that's all we are doing so I hope it's clear please do like and subscribe to this channel hacker thank you for
Validate IP Address
validate-ip-address
Given a string `queryIP`, return `"IPv4 "` if IP is a valid IPv4 address, `"IPv6 "` if IP is a valid IPv6 address or `"Neither "` if IP is not a correct IP of any type. **A valid IPv4** address is an IP in the form `"x1.x2.x3.x4 "` where `0 <= xi <= 255` and `xi` **cannot contain** leading zeros. For example, `"192.168.1.1 "` and `"192.168.1.0 "` are valid IPv4 addresses while `"192.168.01.1 "`, `"192.168.1.00 "`, and `"[email protected] "` are invalid IPv4 addresses. **A valid IPv6** address is an IP in the form `"x1:x2:x3:x4:x5:x6:x7:x8 "` where: * `1 <= xi.length <= 4` * `xi` is a **hexadecimal string** which may contain digits, lowercase English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`). * Leading zeros are allowed in `xi`. For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334 "` and "`2001:db8:85a3:0:0:8A2E:0370:7334 "` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334 "` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334 "` are invalid IPv6 addresses. **Example 1:** **Input:** queryIP = "172.16.254.1 " **Output:** "IPv4 " **Explanation:** This is a valid IPv4 address, return "IPv4 ". **Example 2:** **Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334 " **Output:** "IPv6 " **Explanation:** This is a valid IPv6 address, return "IPv6 ". **Example 3:** **Input:** queryIP = "256.256.256.256 " **Output:** "Neither " **Explanation:** This is neither a IPv4 address nor a IPv6 address. **Constraints:** * `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`.
null
String
Medium
752
128
welcome ladies and gentlemen so today we are going to solve google most asked question which is longest consecutive sequence this is a google frequency frequently asked question so without any further ado let's start solving this problem okay so to solve this problem what the question is first of all we are over here we say like we given an unsorted area of integers and we have to written the length of longest consecutive sequence element sequence okay you must write an algorithm in one times okay so it says like when you write it one time so like you know it's thing like you can't use sorting like you know if you use sorting then uh it will be of any log so basically initially like in the first step i think like okay why don't we go for the sodium then i just check it over this thing like oh constant of oil in times okay so for the own times we can use hash map to solve this problem okay so hashtag is quite good to use it okay now let us see like what the input is saying and how we're going to use schrodinger has been to okay so first of all what i will do i will gonna use a sorting method okay and i will tell you the approach and everything over here okay so first of all what i will do i will create it and add it i will use edit sort function and i will swap my array so we will use this example so um it will become it become one two three four hundred and two hundred like this okay guys okay after getting this what i will do i will simply gonna say okay now create one current pointer and run my max pointer my current pointer and my max point my current pointer will initially point over here okay so and i will get uh initialize with one let's say like if we have something any value in our uh in our like array that length is one because that value length count is one okay so uh let's see over here so my current is one and what i'll do i have five is next sequence which is two so it is two over here it is true so i will update my current and i will update my max as well okay now my another sequence is three so two plus one is three yeah we have three so i will update my max as well again okay now i will go and check for four does it has four yes it has four even as well so i will update my current and i will update my max as well now it will check does it has five because four plus one is five next liquid is five it will say no it doesn't have five so what i will do i will simply uh reset my current to back one and my max initially i have four okay now what we have another one is 100 so it will say that's 100 plus one it has 101 it doesn't know it doesn't has 101 okay so that like i will not upgrade my max because my max has the uh highest sequence longest sequence value okay why should i update it okay then now i will check for another one which is 200 does it has 201 then i will again check like yeah it doesn't have any 201 so i will simply gonna break it and i will come back from the loop and i will return the maximum of my uh value from the max okay so i have i hope this thing is clear if you still know then don't worry while i'm gonna write the code you'll be definitely gonna understand okay so by looking at this what things are coming in my mind okay what i will do i will simply first of all uh so we are using sorting okay we are using something so first of all i will create a base condition but basically you will say my number line is initially 0 so like my current point has a one length any value has a you can even go for the zero as well but i will say like you know like at least like your point is pointing to someone so it that even that only simple digit lag will become okay now in this one i will first of all check i will check if they are more equal then only i'm going to if they are equal then i will know where to go so i will check if my number of i is not equal to my terms of i minus 1 so if my current value is not similar to the previous value then only i will come into this loop okay if that's the condition then what i will do i will check if my current value has the difference of 1 to my previous value so i will say match dot absolute off of i minus numbers of i minus 1 if it has the difference of 1 then i will simply increment my current okay if either if it has a difference then oh that's good like it will like we find the another sequence as well okay and what i do i have to upgrade my max as well so i have to upgrade my max so for that what i will do i will simply say max equals and i have to reset my current to one back again let's just say like if it's break and like after four it doesn't have five so now it does hundreds so i will uh reset my current back to the one okay guys and finally like once it iterate through all over the array and it to find like the maximum value so that i will again check like does my current has the maximum value of my max and the maximum value then i will check over here as well by measured max of max for my current okay so i have no now the code is clear like what i'm doing over here okay let me just run it and see like is it going very well or not passing all the test cases so it's just taking a little bit time because my intent is little slow down let me want to submit it and see it's passing all the test cases or not and everybody so it's accepting value so i hope the code is still like what we are doing over here so first of all i just sort it over here and then i get one pointer current which initially has one and my similar max has one length as well then i uh run it and then i'm checking like if my current pointer is not similar to my previous one if they are similar then i will just say i will never gonna enter in this one because it could that never be the sequence enough that never be a sequence okay and if they are unequal then i will check is there difference is one of one if there is difference then it'll be like let's say like we have three minus um or three minus two is one so then different is one so it will like we okay then i will update my current and finally over here i have to upgrade my max as well upon into my current and if you let us say like um i found a different one then i will just simply and reset my current to one and then that is the only one and five over here i'm just getting my max function okay so i have to i hope so these things feel like how we are doing this okay so let us talk about this time complexity the time complexity in this one we are dealing with end globe n and our space complexity is one go for okay guys so i hope this i hope so this thing is clear okay but uh but our question is like we have to use sold this in using uh owen types so for that one i will gonna use hash map okay so now let's just focus like how we're gonna uh solve this problem using hash map okay so now let's show like how we're gonna install using hash one so using hash now what i will do i will create uh one integer and one boolean so one key and one value okay so my integer will be my key and my boolean will be my value okay let's just see like i'm just saying like what we're doing so we are using hashbrown so in my hash map i will get one integer one boolean okay now you'll ask why i will tell you just wait i will tell you okay so now what we i have 100 i will write by all the entries over here of my integer one three two and initially what i will do i will mark all of them as true all of them initially are true okay so i just filled my hash map and i will fill all the entries let me just change the color okay guys so here we go okay guys now what i will do i will check done is my 100 is the starting of my consecutive sequence if it is starting like let's select it does not has if it isn't 99 any previous value as well then it never be the starting why should i start from over 100 if it has 99 so i'm going to check does my 100 has 99 over here no it doesn't have 99 over here so i'm just gonna uh leave it and i will come to the next one okay now all right by four i will check that's my four s three four minus one is three so it will gonna look up and see yeah it has three then what i will do i will simply gonna mark this as fourth okay because my phone never be level will be the starting of my observatory sequence okay it is a part of the sequence but it is not the starting okay so now i come over here over 200 now i will check does my 200 has 199 it will gonna check again in my uh loop in my array it says like no we don't have then what i will do i will it leave it as true now i come out to one does one minus one has zero it will check so it's say like no it doesn't have zero so that whatever i will come over here by three now it will check does three has two three minus one is two it will gonna check here it has two over here then what i will do i will mark it as four because my three can not be a starting of my contributing sequence it will do the part but it's not the starting okay guys okay i hope so this thing is like what i'm doing so okay it is now i come over here on my two okay so over here what i will do i will simply gonna check does my two has minus one the two minus one is one it has one it was a yeah it has one so what i will do i will say don't mark it so don't take it at the starting because the starting is will be work okay so i also like these things like how we are doing it okay so let me just erase it okay guys so now what uh we gonna how we gonna check it okay so what i will again run a loop so now i mark the starting now i have the true one so the true one are the starting the older through one are the starting and the fourth one are the parts they are not the starting so what i did i learned two my first loop mark or mark all them has two my second loop mark the startings as two only and we are remaining as phones now my third loop in my third loop guys what i will do i will take again two pointers my current and my max so my current will check everyone lands from initially let's say month i'm over here my current will be initially as one and my max will be as well because it doesn't so i will check that's hundred plus one has it will want to check or complete all this one it will say no it does not have 101 so what i will do i will just simply gonna uh remove it from over here and i will come over here to this one okay now i am on my phone it will check that's okay guys okay so now it will come over here it will check this 200 has to computer no 201 does not help so again my current will be one and max will be one so like there is no need to upgrade because one is one okay guys now again what will happen okay so my mistake okay guys now again what will happen it will come on the another two which is one now it will check this one has two one plus one is two yes it has two over here so what i will do i will update my one two by two okay and my max will upgrade as well to two now it will check this just two plus one has three yes it has three i will upgrade my current to three and my max will be upgrade to three as well okay now it will check because three plus one has four yes it has four so what i will do i will update my current to 4 and my max for 4. now it will again want to check this 4 plus 1 is 5. no it doesn't have to i just completely it take all my loop it does not have 5 and then maximum value which i found is 4 and i'm going to remove my maximum value so that's how we gonna return our maximum value i hope so the approach is here if you still don't i will suggest you to just try to rewatch this video back again uh you definitely want to understand okay guys so here we go so now what i will do is first of all i will create my hash map and i hope so like you will definitely want to understand i will not agree with this thing i'm just using this part okay so let me just say completely and here we go ladies and gentlemen so it's completely okay so now what i will do i will facilitate my hashmap okay so my hashmap will be of my integer and not my boolean okay guys i like to put it so i'm just filling it so i've said map go put i comma uh true i will mark initially as true i fill the hashtag and i might mark all of them as two okay now my second follower what i will do in my second formula is i will simply say do one thing to start it from zero and i have to check if my let's say my hundred and something of back as well like 99 because 100 cannot be a starting effect if it has 99 okay so i will want to check over here and i will mark those one as opposed and i will leave less of them as true okay so whatever okay guys okay in this one what i will do i will check if my map contains key of numbers of i minus one similarly let's say four i think is the starting but it has three so four cannot be the starting so what i will do i will just simply upgrade it i will say map output that number i that pointer has four mark it as phones okay now over here what i have to do i have to get another for loop that for loop will gonna count and it will be the maximum value okay so first of all i will create my max initially zero okay so if you say like don't put a zero put at one so for you i'll put that one okay now what i will do i will just continue i will get my key and check if my map reset i will check whether my if my value is true i will check if my map dot contains key is true if it is true then what i will do i will say get the maximum value like the max of max formula correct so for the current one i will just use a cater function to find that my function find that will help me to get the current value okay so man okay guys and don't forget to release over here now i will make a call to that function which we have created public and file name which you want to create so okay guys now i have to create my hashtag of integer boolean till my map dot contains p of t okay guys if till then it contains key okay then till then what i will do i will simply say increment by k and update my current as well so that's what i'm doing so that's what it's doing like if it is four plus one five then i will say equilibrium current as well okay and finally return my current over here so that's the polar body there in general so after the scaling let me just view it clearly i hope the code is clear that means gonna do all of this thing from over here okay so what i'm doing initially is i just get my hash map and i'm right i'm filling my hash first of all then what i'm doing i'm marking the previous one if it is the previous uh positivity sequence then i will mark it as fourth and over here i'm just saying like don't become true just check their length and give the length of the maximum to give the maximum length possibility sequence let me just run it to see any compilation error will be faced so it seems like we're facing a compilation error over here okay so it's not t is k by mistake okay guys so here we go is judging and we just get a five let me see what is that i think we have to give max zero might be because like you know in this one you have to give my back is accepting very well so you know like you have to give max zero because you know like we are using hashtag so it's counting uh is counting the value so uh in the sorting one you have to give one or zero is for up to everybody in the hash mode you have to give zero so remember this thing okay so let me just want to submit it and i'm going to tell you space capacity and time complexity if this or the test case is accepted very well it's just taking a little time because mine i told you my internet is working right a little bit slower is this good timing in this case okay guys so by mistake i just put content speed so it will become map.cat because speed so it will become map.cat because speed so it will become map.cat because we have to get that key by mistake i use content so let me just gonna uh can i copy this one no i can't copy this one so let me just gonna again submit it to see like mistakes happen i just put consecutive over here so it will come back look at it and here we go so it's something very well okay so now let's just talk about what the time is type compression source problem so okay gentlemen i hope this program is clear and this is a google most frequently asked questions in the interview so thank you very much ladies and gentlemen for watching this video if you still have any doubts just do let me know in the comment section i will definitely release you and till then take care bye love you guys believe me i love you take care bye
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ You must write an algorithm that runs in `O(n)` time. **Example 1:** **Input:** nums = \[100,4,200,1,3,2\] **Output:** 4 **Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4. **Example 2:** **Input:** nums = \[0,3,7,2,5,8,4,6,0,1\] **Output:** 9 **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Hash Table,Union Find
Medium
298,2278
290
hello everyone i hope all of you are having a great time i know it's a monday and everyone's having monday blues but still we have to solve the lead code daily question and the question that we have in today is word search lead code 290. it's an easy level question on lead code and i totally feel the same to our surprise we have already solved this question in the month of september 2020 this was a time when we started a channel and for those who have been associated with the channel since long must be aware of it i just went through the video i have clearly explained the entire concept behind solving the question and i would urge you guys to have a look at it also please increase the speed to 1.2 x for please increase the speed to 1.2 x for please increase the speed to 1.2 x for better understanding and apologies there is slight noise in the video in the starting so kindly please ignore it and do watch it till the end where i have coded it live for you guys over to you i hope you really enjoy watching the other video 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 updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye
Word Pattern
word-pattern
Given a `pattern` and a string `s`, find if `s` follows the same pattern. Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`. **Example 1:** **Input:** pattern = "abba ", s = "dog cat cat dog " **Output:** true **Example 2:** **Input:** pattern = "abba ", s = "dog cat cat fish " **Output:** false **Example 3:** **Input:** pattern = "aaaa ", s = "dog cat cat dog " **Output:** false **Constraints:** * `1 <= pattern.length <= 300` * `pattern` contains only lower-case English letters. * `1 <= s.length <= 3000` * `s` contains only lowercase English letters and spaces `' '`. * `s` **does not contain** any leading or trailing spaces. * All the words in `s` are separated by a **single space**.
null
Hash Table,String
Easy
205,291
435
hey so welcome back and there's another daily code problem so today it's called non-overlapping intervals now I actually non-overlapping intervals now I actually non-overlapping intervals now I actually did this one yesterday but I thought we'd do it today and so essentially uh what you're given here is just a two-dimensional array or I kind of like two-dimensional array or I kind of like two-dimensional array or I kind of like thinking of it as really just a list of tuples that's how I think of it um and essentially all that you want to do is you want to picture these kind of like in a Time series so this will indicate the time and it's basically a timeline starting at zero and you can imagine one two and then three and like so on so this could be like four and so what this kind of looks like in this graph here is the interval one to two without start here and go all the way up to two then two to three would look something like from two to three to four well that's like this and then one to three well that's essentially from here all the way to here and so what you want to do is essentially remove the minimum number of intervals so that there's no overlaps and so if we're looking for that essentially what you can see here is that the only one that really causes overlaps is this one here these ones are fine because well although they touch They Don't Really overlap so that's okay so these two cases are fine the only thing that you really care about here is that this one actually hovers over these other two and so naturally if we just kind of broke this one or removed it that's incrementing our account from zero to one it only took one removal so that none of these intervals are overlapping and that's actually your answer here one all right and so essentially um the first thing that I thought of when I was trying to solve this was okay it's kind of confusing hopping around here to find of these interval ranges so just by sorting them it just made it a lot more intuitive for me and so that in this case is just moving one comma three to basically this location here so it looks like one three all right so it goes one two one three two three four I can't toss in my head of okay what if we want to sort it by the second number and then the first number like maybe changing the Sorting algorithm a little bit but you don't actually have to do that you just have to think about sorting it um from the first value then the second value if that makes sense um and so from here the only things that you have to keep track of is essentially the count because naturally you're going to be incrementing the count but other than that the only thing that you really need to be thinking about is the previous interval or end interval number okay and that's the key to everything here and so initially the previous n interval number will be two like when did the previous interval end okay and so essentially you're just going to be looking at from the first interval like index one not index zero onwards so you set the previous to two and then you look at basically this interval and these ones onwards from that and so you're just comparing okay did this interval end before this one start if not then naturally there's an overlap otherwise you just take the new ending as the current interval okay if that doesn't make much sense I think me showing it you the code and just relating it back to this diagram here it might make more sense so I'll try to stay with me and so once again the first thing that we want to keep track of is naturally the count because that's what we're going to want to return here and we're also going to want to sort this for Simplicity this does cost analog again time complexity so it's going to be the bottleneck up for this um algorithm but it uh it's a great benefit otherwise you're going to be reiterating and pointing back and forth and it'll be more of an N squared algorithm so it's worth the cost and so from here uh what you want to keep track of is what is the previous like end time so I'll call it like previous end as a variable and so this is going to be essentially the first interval in our list and basically the end of that interval and so once again we're just going to iterate through all these intervals um from the first index onwards because we don't want to consider the first index here because that's our previous end so that just looks like in Python like that because you can just use a python slicing to simplify it and so once again there's only two different cases that we have to consider so we can just use the NFL it's for this and the first case is what if there is no overlap so the previous um the previous interval ends before the current one starts that's the key for this first one so if the previous interval ended before the current one even started that's fine let's just update the new previous end date and so what that looks like in if statement is just okay is the previous and less than or equal to because it's fine if they touch they just can't overlap the current interval I will call this interval um it's start time so we check if the current one started um after this one has ended and so then naturally we just want to update our new previous end to this new end to do the starting one we want to do index at zero sorry about the confusion and so from here this case is there is an overlap and so we want to handle that overlap and basically once again increment our account but we also want to update this new previous endpointer and so the reason is for that is because while this the previous intervals end time um has ended between this interval range that we're currently looking at and so the key to solving this problem is we want to take whichever one ends earliest because if you take the previous end time of a date or a time that ends like kind of later on there's a higher probability that it's going to overlap with an upcoming interval so let's just take the one that ends the earliest so you don't have that problem and that's how you basically get the minimum number of intervals okay and so in code what that looks like is let's just compare the current previous end time with the current previous end time all right so let's try running that looks good and success so for time and space complexity well our time complexity is going to be analog again because this sorting is the bottleneck and for space complexity well the only storage that we're really using here is a constant space variables so you don't have any um uh space complexity such as old one or constant space but yeah I hope this helped a little bit and rest your albums thanks for watching
Non-overlapping Intervals
non-overlapping-intervals
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_. **Example 1:** **Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\] **Output:** 1 **Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping. **Example 2:** **Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\] **Output:** 2 **Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping. **Example 3:** **Input:** intervals = \[\[1,2\],\[2,3\]\] **Output:** 0 **Explanation:** You don't need to remove any of the intervals since they're already non-overlapping. **Constraints:** * `1 <= intervals.length <= 105` * `intervals[i].length == 2` * `-5 * 104 <= starti < endi <= 5 * 104`
null
Array,Dynamic Programming,Greedy,Sorting
Medium
452
155
hey guys Greg here let's solve minack which is leak code problem 155 it is a very interesting problem where I think it's super clever once you know the answer and it feels like you can get to that answer but sometimes you just don't quite get it and here you are so let's check it out so this is one of those questions where you design a class and that's actually very common for Fang style interviews they get you to design basically a very clever class so we want to design a stack that supports push so putting an element on the stack popping to taking the most recent one off top simply asking what is on the top without popping it off and retrieving the minimum element in constant time so that's the new interesting one that makes this all difficult so we want to implement the minst class where minack the Constructor simply initializes the stack object you can really do whatever you want there a void push so void just means it doesn't return anything so it's going to push a value onto the stack so it just pushes the element Val onto the stack void pop so that's actually strange that it's void because generally it would return the thing that's on the stack but here it's just going to remove the element on top of the stack and not return anything we have int top so that's just going to ask what the top element on the stack is it gets the top element without removing anything and in get min is going to just get the minimum element on the stack and don't worry we don't have to pop that off that would actually be a lot more difficult and again we must Implement a solution with o of one time complexity for each function so anytime we run any of these functions once we expect that to be constant time now let's say that in order you're going to put on these four values into the stack now what's very clever here is we're actually going to make two stacks and that's totally fine because you're really just using precisely double the space and so we're going to start out with two empty Stacks where this one I'm just going to call it s it's basically our normal stack and here I'm going to call this m because this is the one that keeps track of specifically the minimum now it's put on our first value which is five and so that's just going to be an append where we put five onto this stack and this one is always going to keep track of the minimum in the same place of here and that'll make sense shortly but here for this element of five well the minimum is also five so we're just going to append that as well let's put on our second element of four so if we do that on our stack well we just want to do an append and so we put four at the end and then our minimum what is the minimum well it could add be five or it could be four we know that four is the smaller value so we will append the minimum and that is going to be four now let's say for a second you asked what the minimum was well we could just return the top of our minimum stack which is going to be four now suppose again that we actually popped this element off here so if you called pop that's going to remove this for our minimum stack when we pop we're actually going to pop that as well and notice again here if you were to ask the minimum well it's still five at this point but we're actually going to undo that and just carry on now let's put on our new value which is -1 here onto this our new value which is -1 here onto this our new value which is -1 here onto this deack we're simply just going to add a -1 now for the minimum we want to put on -1 now for the minimum we want to put on -1 now for the minimum we want to put on the smallest value but notice we don't actually have to ask about this because we know that this value is going to be smaller than this one in fact it's always going to be organized like this where we have the minimum on the top here so four is the minimum on the top we want the minimum which is again going to be 1 and so if you asked at this point what is the minimum well you would return the top which is -1 get minimum return the top which is -1 get minimum return the top which is -1 get minimum is always just going to return the top of our minimum because that's always where it's going to be stored as we add our element of 10 well we're going to add 10 over here as expected but then here we want to add the minimum well the minimum is either my newest value or it is the thing that's at the top we don't care about all this stuff because it's still always organized like this where it's going to get smaller as it goes further why is that the case well we always want the minimum to be stored on the top so in this case well -1 is on the top so in this case well -1 is on the top so in this case well -1 is actually smaller than 10 so our new minimum is the same as our old minimum and if you asked at this point what is the minimum well it's -1 we just return the minimum well it's -1 we just return the minimum well it's -1 we just return the Top If we popped anything off here if you popped off our 10 well then we need to simply just pop off this value yet again we ask the minimum in here well it's still the top right here if you were adding a new value like -20 you were adding a new value like -20 you were adding a new value like -20 well that could be the new minimum or maybe it wouldn't be we'd add -20 onto maybe it wouldn't be we'd add -20 onto maybe it wouldn't be we'd add -20 onto our normal stack is that the new minimum well is it smaller than this value the top of our Min stack yes it is and so our new minimum is going to be stored at the top right here we will always keep track of the minimum at the top of the stack so let's just pop everything off here if we take off the -20 we are going here if we take off the -20 we are going here if we take off the -20 we are going to take off the -20 over here you ask to take off the -20 over here you ask to take off the -20 over here you ask the minimum it's at the top right here say we took off the -1 well we take off say we took off the -1 well we take off say we took off the -1 well we take off the ne- 1 here if you ask the minimum it the ne- 1 here if you ask the minimum it the ne- 1 here if you ask the minimum it is going to be four same thing if you popped it off we pop it off both get the minimum it's five same thing repeats if you added another value maybe you added a value of 10 Well we'd add it 10 over here but you wouldn't add the 10 over here because that's bigger than the value on our top which is the minimum and so we would add the same value as it was before so let's write our code we need two Stacks so in the Constructor or the init function we'll make a self. stack to be an empty list and we want self. Min stack that's our M to be another empty list they're both just going to act as Stacks but the Min stack will always be in control of the minimum value now when we push that's the most interesting function here so we always want self. stack. append the value our new stack is just going to accept that value however for our Min stack we need to say well firstly if we don't have a self. min Min stack meaning our Min stack is empty well we know we just want the value so we'll self. Min stack. append the value however if it's true that the self. Min stack at -1 so that the self. Min stack at -1 so that the self. Min stack at -1 so that means the top of our minimum stack meaning our minimum our current minimum so if our current minimum is less than the value well that means that our minimum value is still the minimum value okay our value is bigger so we're not interested in keeping that we want the old one that means we do a self. minst stack. append with our previous minimum which is just the same value right here so we want this one our previous minimum stays the same otherwise if that wasn't true we want self. Min stack. append the value need that new minimum and so we will append that and the other functions from here are really not too interesting you want to do a self. stack.pop you want to do a self. stack.pop you want to do a self. stack.pop whenever we pop and you also want the minimum to match we also do a self. Min stack.pop when we add ask what's on the stack.pop when we add ask what's on the stack.pop when we add ask what's on the top well that means just our normal stack so we want return self. stack at -1 our minimum is not involved there but -1 our minimum is not involved there but -1 our minimum is not involved there but when we want the minimum well we've actually already used that this is our current minimum we want the self. Min stack at -1 that is just the top of our stack at -1 that is just the top of our stack at -1 that is just the top of our minimum stack or our minimum value as you can see all of these functions just use aent or pop that means they're on average constant time so that checks these boxes and we just have to return that value and that's really it if I zoom out here you'll see all of the code if we were to run that then we'll get accepted now you probably wouldn't get asked more about the complexity here but if you were to we' say that the time if you were to we' say that the time if you were to we' say that the time complexity is 0 of one for each operation and the space complexity well that is kind of O of n because in general you're storing this extra Min stack here that really has nothing to do with the question it just happens to be useful to solving the problem so I'd say we're pretty much using an extra o of n here I hope this was helpful drop a like if it was guys and I'll see you later
Min Stack
min-stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the `MinStack` class: * `MinStack()` initializes the stack object. * `void push(int val)` pushes the element `val` onto the stack. * `void pop()` removes the element on the top of the stack. * `int top()` gets the top element of the stack. * `int getMin()` retrieves the minimum element in the stack. You must implement a solution with `O(1)` time complexity for each function. **Example 1:** **Input** \[ "MinStack ", "push ", "push ", "push ", "getMin ", "pop ", "top ", "getMin "\] \[\[\],\[-2\],\[0\],\[-3\],\[\],\[\],\[\],\[\]\] **Output** \[null,null,null,null,-3,null,0,-2\] **Explanation** MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2 **Constraints:** * `-231 <= val <= 231 - 1` * Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks. * At most `3 * 104` calls will be made to `push`, `pop`, `top`, and `getMin`.
Consider each node in the stack having a minimum value. (Credits to @aakarshmadhavan)
Stack,Design
Easy
239,716
299
Jhaal Hello Hi Guys Welcome to Code West Today's Question is Gold and Tons in This Will Play a Game with Her Friend to Write the Number and Ask and Guess What the Number Subscribe Video Subscribe Jaitly in Both Its Position and Humid Number Locator Different Positions on a View To Return How Many Times Hit And Hit The Bell And Sometimes Hit The Cow So Let's Understand This With Example Lake Near Ones Cigarette Stringers 5207 Distance Between 10 And Friends Not Know About Distic But I Do n't Know About Different Is The Present In Distic 9 and to get the order status that is gas given to 781 299 plus extinct is 70 cigarette spring not s president but this position of gas in gas to consume subscribe to that in g string this platform position sacrifice index and Secret Also Its elements for this also indicate that both characters of various positions match Buddhist Babool a Noble Similarly 111 is President Hindi Secret Jai Hind Cigarette String All Shoulder Disposition of one in the same string and position of one Hindi Sequencing Different Shoaib Malik Ko Daku Similar 800 President for the thing but different position Twitter Jahan Gaon Indian Visa to return how many bones and gorgeous hit solved valued by capital one and three cops for a capital also better return this that now let's you create a look at the approach in this regard To traverse through the string and intense pain on the characters and does not matching liquid form 2018 that which will force vacancy are built to the frequency of phone number office secret string and second frequency of service to the characters of the gas string number of times Appearing traversing the character of research in the middle and when both the tractors are different then will update the vs notes only to -do list subscribe intentionally not -do list subscribe intentionally not -do list subscribe intentionally not exhaustive width third front will update subscribe see the secret way with oo i one to per seventh index ki North Point Will Move Forward 9 We Have Wanted Injection And In This Index Tractors And Very Beautiful Same Will Update Kar Bol Variable 122 Close That No These Values ​​Will Not Be Any That No These Values ​​Will Not Be Any That No These Values ​​Will Not Be Any Discrepancy Are They Will Only Be Amazed Mehndi Very Sharp Tractor Adaptive Laker Different Nor will a mouth and not the greatest sin boti the spring of difference they will update or frequency are o the cutter and secret is dros will update jatin tax and character add gas is vansh will update the first day of no value for a main not affected If and different so will update se one drops of secret tomorrow swimming and growth index of first time and hear or tempered glass over phone number butar given brother number drop and given by that bill bramble id number off that person to wear blender valve number off Do that date is shine frequency reddy pregnancy are but testing lab technician minimum number removed particular position on the five updated 212 yesterday morning addressed to formalized frequency proof the address but packing minimum set up particular index live from one day minimum is vansh scars begum one no Hindi Meanings For The Native With This Number Subscribe Now To Receive New Updates Reviews Nov 10 2013 12312 A 98 Point Is It Vivo Index Bodh Tractors Different Sunil Update This Corresponding Value Day t-20 Are A Gift Corresponding Value Day t-20 Are A Gift Corresponding Value Day t-20 Are A Gift This Point Activated Here With These Candidates Will Be Updated No Where Can Move Appointed to Held Nau Liters and Buddhi Strings Have Also Been Updated on That Novel The Move Ahead Solitaire Bodhi Strings of Difference They Will Update The Second Index of the Secret Frequency Are with One Hand in Sikhon Cigarette Fast Index of Being S there was no will hurt oo kuch dar di category and different super will update the third index of the secret here with one and the fort index of frequency are of gas that no know when they are atravarso dheere ki bihar police answer indestructible in Trending Person Calculator Sir Nikhar Jahan Committed During This Too Frequency Is Nobody Would See My Travels Him Zinc Minimum Value From ODI And T20 India Will Look Like A View Of Bihar In Dec09 Act Value In Bodhi Answer Is 90 Sunil 802 Varsham No Will move to This Festival Test Case Number 2018 Number 2019 They Are Straight First Always Giving False Evidence And The Bulls And Guest House Number Of The Question And Will Declare That To Frequency Vectors New Delhi This Hand Idli Hour Having Elements By Karne Limit Bigg Boss This Cigarette This is the element of the following 4 users liked this 1807 maximum number that David Villa a great way to lotus eyes and you will release element 102 will create another factor which aims to the country of a sequence of getting a string in will be named das ji and zero know its worst drinks for internship i will check first name the character of buddhist ring get secret one to one this secret off side ww2 gas of i means cattle and also they will be available on that in this chapter note school will update were Frequency vector with this acigarette was hidden - 0 was hidden - 0 was hidden - 0 a plus b plus c katai is the correct and were converted into in tears for watching the best and similarly e paul will update chief guest on how - 0 plus half people disturbance Books on how - 0 plus half people disturbance Books on how - 0 plus half people disturbance Books free hindi novels to calculate the a knock setting dikhao us bhi have to dead over and frequency address that 1005 plus hello viewers add the minimum of minimum balance a particular index indore possible minimum of and ashok bhai comedy jio 500 ab aadhe bhi hai that mistake Jaan se in breathing ka use answer impossible better return were return of string will declare string answer equal to two with empty string a answer plus equal to will convert per bulls to string yes bol yes sir plus two equal to he that no will convert r ka ujjwal Two Strings Solar Wind Up and Any Answer Like share and subscribe thank you
Bulls and Cows
bulls-and-cows
You are playing the **[Bulls and Cows](https://en.wikipedia.org/wiki/Bulls_and_Cows)** game with your friend. You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info: * The number of "bulls ", which are digits in the guess that are in the correct position. * The number of "cows ", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls. Given the secret number `secret` and your friend's guess `guess`, return _the hint for your friend's guess_. The hint should be formatted as `"xAyB "`, where `x` is the number of bulls and `y` is the number of cows. Note that both `secret` and `guess` may contain duplicate digits. **Example 1:** **Input:** secret = "1807 ", guess = "7810 " **Output:** "1A3B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1807 " | "7810 " **Example 2:** **Input:** secret = "1123 ", guess = "0111 " **Output:** "1A1B " **Explanation:** Bulls are connected with a '|' and cows are underlined: "1123 " "1123 " | or | "0111 " "0111 " Note that only one of the two unmatched 1s is counted as a cow since the non-bull digits can only be rearranged to allow one 1 to be a bull. **Constraints:** * `1 <= secret.length, guess.length <= 1000` * `secret.length == guess.length` * `secret` and `guess` consist of digits only.
null
Hash Table,String,Counting
Medium
null
51
all right guys now we are going to do the next problem with lead code problem 51st and queens the N Queens puzzle is a problem of placing and queens on an any length s Porter says no to Queens attack each other ok when an integer and returns return all the solution to the N Queens prappas it each solution contains a distinct whole configuration of N Queens placement best cook you and dot both and if I indicate a queen and an empty space respectively so this is how we're going to do this but we are going to have create a variable a result variable which we are going to return at and off the algorithm okay so let's define this as the analyst so once we're done with this we're going to have character la T you have n we are going to use arrays dot fill to fill see with pot once this is done we will create a thing Eddie it s new string array I don't after hi I have another area size M I will call the fill function again and I'm going to have a restart copy of C n times then string dot value function convert stuff into Train yep can you character in a string once we're done with this we have a good for us a prototype grid now I'm going to create slacks shell boolean column sag equal to Nu equal to do them array of size because I haven't homes I'm going to the flag but diagonals 45-degree diagonals flag but diagonals 45-degree diagonals flag but diagonals 45-degree diagonals and I lost 135 degree line because I have how much two and minus one diagonals 45-degree angles and 2 into n diagonals 45-degree angles and 2 into n diagonals 45-degree angles and 2 into n minus 1 45-degree diagonals and as we minus 1 45-degree diagonals and as we minus 1 45-degree diagonals and as we know that you know Queen it goes diagonally and it goes by column and rows so then I'm going to have a helper function to it I'm going to pass my sister my thing my bags I have three of them and I zero this was row so quickly you know I mean kick I'm gonna increment my row and iterate through columns and it's like that then wide helper function which going to switch is going to take my return they give my string s boolean flag oh my god I didn't and I forgot the anything okay now I can copy okay I have these please then I'm going to have an increase row and integer and the F Rho equal to M by n minus 1 rows from 0 of course so this would mean that you have covered all the rows so I will just add new array list then I'm going to have arrays dot as see list function as my SLA I'm going to turn it into this and store it in my laser something needs yes district column equal to 0 column smaller than M column plus size nothing out of the ordinary R then an if condition that F column flag for the column is equal to let's speaking about it not I want this to be false then I am going to have not diagnose flag or column Plus really just think about it you know collect through is the 45-degree collect through is the 45-degree collect through is the 45-degree angle yeah number and similarly not I'm sorry so not fat n minus 1 minus Rho plus column because you know great you can visualize this black inner of one forty five degree at is mirror image of what a forty five-degree crossed you of what a forty five-degree crossed you of what a forty five-degree crossed you know a certain column so basically column doesn't changes row if I subtract true from n minus 1 that will give me the opposite Tina and after that will create a mirror image of the 45 degree air diagonals so let's go ahead if all of these are false you can what I'm going to do is I'm going through a sign true to the DS going to get a clue no I now I'm going to have a character array C is equal to new cache of size n are rather let's be a bit clever about it let's take as column two character Eric the CEC we have to yeah okay once I have this let's go to as row and I'll give a queen to it Queen to pit I'm sorry C so C zeros then I'm going to have go to as column and I'm going to you string okay wonderful then let's copy the help function from above and let me close this one then just copy the code from over and say word that the flag one it's my recursion my function called eight returns because I have to check for the other things as well I just cannot really use you know the whatever changes out then I have to reward back and check for other organizations so this looks good let's try this 14th I have a bracket problem at 14th yeah was okay let's look now see is already power okay i'm societies let's try now oh I'm sorry guys okay it's working let's submit it okay thanks for your time
N-Queens
n-queens
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. **Example 1:** **Input:** n = 4 **Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\] **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above **Example 2:** **Input:** n = 1 **Output:** \[\[ "Q "\]\] **Constraints:** * `1 <= n <= 9`
null
Array,Backtracking
Hard
52,1043
392
today's problem is very simple we are given two strings one is a smaller string or it can be larger and another string is the bigger string and we have to check whether s is a subsequence of t or not so subsequence is uh means that you pick some characters from a sentence from a string or maintaining their order for example i pick h then i pick g and then i pick let's say c so you will see that h occurs first then g then c and in this string from where we have picked it there also they occur in the same order that is h occurs first then g then c then h g c will be a subsequence of this string but on the other hand if we write it like ghc although the characters are same we see that very g is here then after this we look for h and we do not find it although it's before so it's occurring in different order in the this string but here it's in different order so this is not a substring subsequence of this and this is a subsequence of this string so here also you have to check whether the given string s is a subsequence of t or not so for this example if we see that is a present or not first of all these characters should be present if the character itself is not present there is no notion of ordering we straight away turn false so we check if a is present or not we see that yes a is present here there can be multiple instances of a as well so we see that one character i have found next we look for b so we pick characters in order in s and we look in t so wherever we found the first character we look for the next character there onwards so we found a in the beginning itself so we look from second character for b and we found a b here so we move to the next character which is d and try to find it and we found it here and now there are no characters left here so we say that yes return true but if this is not a substring let's say we have some other character here let's say a b x then we see that a we found here this is s this is t then we look for next character b we found here then we look here onwards for x we go here we don't find we reach the end of t and this we did not find so we return false similarly let's say we are given a c b so we see if a is present yes it's here then we look for c we continue we found c here and then we look for b but we see that there is no character left so we return false so the algorithm is very simple if first characters match each sub let's say this is the function and we are calling it on smt so if s0 is same as t0 that is first character match then our job is reduced just look for this substring in this substring whether this subsequence is present in this or not so return each sub s one onwards so this will denote this slice will denote first to last character and comma t one onwards else that is first characters are different so we will not advance in s since we have to find all the characters of this s so we did not find a here so what we are left with we will find this entire s in this part from first to last character so in this case we will return each sub s complete s and t one till end and uh if so here we are using recursion this is the main function and we are recursively calling this function on a smaller substring of s and t and finally when should we return if s is non-empty and t is non-empty and t is non-empty and t is empty so if s is empty that means we have searched for all the characters of s and we move to next character only when we found the previous character in the same order that we followed so if we found b here next character we look from here onwards so we never do second scan of this array so if at any point of time if in this recursive call if s dot length is 0 that is all characters are found or maybe that the input was itself zero then we have nothing to find then return true and if s dot length is not zero then we will check if t dot length is zero that is some characters are still not formed but we have reached the end of t so we return false in this case and after these cases just check if the first character of the substring of the substrings match then our job is reduced one character less in each of these if they are different then just look for this s in the substring from one to last of t so that is very simple so let us see the time complexity here we are doing one scan of s and t so time complexity would be order of n whichever is larger or n plus m and we are not storing anything in some extra space so space is order one time is order n linear n plus m and space is order one so let's write this simple code in c plus java and python so if this is subsequence a smaller string is empty that means all characters are found then we return true if that is not the case we will go to next line if it's 0 this function will not execute further but if it goes beyond this that means s is not empty then if t is empty t dot length is zero then return false and if s 0 is equal to t 0 return if first characters are not same then return s will remain same and this will be the substring of t from one to last and let's see it works so let's submit and the solution is accepted and we are here around 63 so you can try some iterative approach maybe that should give some better timing here maybe recursion is causing some slowness but still it's not that bad time complexity is often only and now let's write the same thing in java and this solution is also accepted and here also we are around fifty percent mark so this p could be mainly due to some iterative approaches where you can have two pointers one will be pointing to the current character we are trying to search in the character that we are trying to find so that will be in s so if we are trying to find a that will be pointing to a and the second will be the current position in t so if we found here then we will advance it and if it both then we will look for b so this pointer will remain stationary here the first one and the second will keep advancing and here it will find b then we will advance this by one this by 1 and then we will find c in the end and then we will check that if s has reached the end or not then we will return true so you can try this logic would be very similar to this and that should give a better result now let's write it in python 3. and the python solution is also accepted now let's try that two pointer approach if we can do it better if s is empty return true and then idx one equal to zero or let's call it a s for indexing s and idxt so we will look for all the characters in d if t i is equal to uh this s idx is pointing to the character which we are searching so s i d x then what we will do we have to advance this pointer in s so s i d x plus and this i will anyway advance and if s i dx is equal to s dot length so the last index will be s dot length minus 1 so if it's dot length that means we have searched all the characters of s so we return true so that we don't continue our search even if we have reached the end of s and we don't get an out of bound exception here since this would be less than s of length so we return true but if that is not the case and we have reached the end of this loop then we will see we have reached the end of this bigger string but have we reached the end of this smaller string or not so return s i dx should be equal to s naught length if it's less than that means we did not get a chance to search all the characters of s and we reach the end so let's see if this works uh okay this works let's submit if it passes all the test cases or not and this solution is accepted and you see that our solution is right here it was earlier here around 63 percent now it's 85.4 percent around 63 percent now it's 85.4 percent around 63 percent now it's 85.4 percent and it's just a matter of time that you try a few times it can reach this peak also that is 99 so you see that we get a much faster running time in the case of this iterative solution i think we did not use this one so we can get rid of this and this would work so we needed just one pointer other pointer is this i itself let's submit again and we are still here these are the top two bars but i believe that we can jump to this without too much of effort so now let's try our code the same logic in java and python also and see if there is any improvement there also or not i think this loop this check may also not be required since we are already taking care of this and everything else is fine d dot care at i and this solution is also accepted and now we have reached our almost there we are better than 93 of the submissions so this iterative approach is working better in not just c plus list but java as well finally let's for the sake of completeness do this in python 3 as well you and this is also accepted and here also we are right in the towards the top of the region that is around 93 so i hope you understood both of the approaches recursive as well as iterative the logic is same in both the cases we make one scan of both of these and if we reach t at the end but we have not reached the end of s that means we have not found all the characters of s in the order they are in s so we return false in that case now let me try one more thing this check was redundant let's see if it improves anything and here we are at the top hundred percent so we have reached our destination finally with uh improving our solutions slowly and slowly so that check was not required and removing that helped us jump from here to here so i hope you liked both the approaches feel free to share your valuable feedbacks thank you
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
507
Hello everyone, my name is Adarsh ​​Mishra, Hello everyone, my name is Adarsh ​​Mishra, Hello everyone, my name is Adarsh ​​Mishra, you are watching this Dress to the Nation, today we are going to talk about the problem named Get Perfect Number. The problem statement is here divided into three lines, so before reading it, I Let me tell you why this development is made in the video because this problem has to be created, it parses the list and if it is not submitted then there comes the time limit exceeded hair, it means that the first answer in your testicles. To find the solution to calculate 11 buttons, it is taking more time for input, then how to reduce that time. Time complexity has come here. So, we have divided this problem by 30. I will tell you three solutions. All three solutions will be different from one another in terms of time complexity, so it is important to understand it well. Click here to see the perfect number, what is our pack number, this is the positive entries, that is equal to 10. Subscribe to this link. Teacher's Day and effectively now here quantum means that my number is and the number can be divided into 6, 2030, here it means that when you subscribe to someone, if that number is getting divided, let's see whether it can be divided by any one person. And hatred subscribe be equal, at this time quits positive individuals, it means all the reverses of that which you are seeing in front of you, when we do all this, you will get angry, if who is our ex's then what will be our ex's perfect. The number will be one more point given here that excluding number 80 we should not take that number if we have exclusives then we will not consider six so this is how many number children we have one plus two plus three layer three division more quickly so Now what to do, if not subscribe, I have given the input number, name, use it, 28th gram number is 28, so if you solve first, then who divides the to-do, solve first, then who divides the to-do, solve first, then who divides the to-do, then tell me how 128th is filled with lust. Superhit someone validates Vansh is not able to divide 21 or three, fourth is 01 and the viscosity is that if we divide, then remove the number from the to-do list, if you have a child, then this channel is subscribed, okay then this problem is subscribed. That salt is coming to the fans of accidents, how many meters are you, how many numbers does it divide in between, on top of that, it is not a number, whatever number we have is a number, so what should I do with it, how? Before doing this, we are in the list of Hello Compiler and we have given power tunes of time to solve a test case of the tank, so by doing this, their health gets time and 2018 in this we are not If we get our ghagra, we need it in such a time, so I know it is okay, now you tell me, if I mean, you ca n't subscribe for the news of the screen, if you like it, then you can put it on the video of me. Any can I call you this in the front so the power of activity against anti tank sees a maximum railway station good 2018 if it is in it then it will not work because in the list tank power tune of time my code is my one test case should run if If you don't want to let me come to Delhi then I will have to do it at least. So from here I understood a little bit that we can first see a solution, okay then before doing this let's find a solution, so first of all let me tell you that the way. Whatever it is, Bigg Boss takes it back, so we do the question of quitting, are we able to divide it with water or not, but yes brother, he can do two, three, even 6. So I am four de Villiers, okay in my mind, from the first to the number, I am able to divide all these numbers, so after adding them here, we will take all these like if it doesn't do my numbers and If you do this quickly then this house is happening here, right, you are going from one to the end, okay, you are finding out which number is able to divide I and I, so here you will put a loop, okay now. How much time will it take, that time and time is pathetic here, okay if 10388 time and because of this problem does not come here then please subscribe because I can do it here, so whenever you have any problem If there is a problem then subscribe if others have understood, then this function was given to you, here you were given a number, so I made two functions, one side was extend sum and the other was check perfect, okay, that means whatever number is used. Please check that it is correct and whatever answer is true or false, first of all tell me that here I will check again that I have subscribed to this and now whatever is there has gone above it so that I can understand that. Have you understood this line? Okay, let's move on to the tractor time. If I am inside the tractor, then here we have all the numbers that have made them from one yellow to the end. Okay, if you mean - 12345. Okay, so here. If we are appointed then click on continue here, I pick up this number, I like it, if he is able to divide my number, completely at this time, the mode means our ghagra, subscribe to our channel, like and subscribe number. Let's subscribe and it will last till 65. Subscribe button will be perfect. With subscribe, the workers in the restaurant at Rajghat today have understood this problem. Well, now this is the time complexity of it, so where is the work being done? People walk here. How many times are people running? People are running and minus one time slow. This is how to solve the problem in Vivo. I have seen that the time limit has been exceeded. I have told you and if you get time, you have to fold it. In such a situation, you will answer this. How do we do it, so if we subscribe, then by extracting these and subscribing, it will be made in two ways, two will come, the fiber will go, the number will go like this, de Villiers and here we will show you, read Chikara, do it well with all these numbers and here if the tank power. Had the formation here been quiet, this list would have become bigger. I am checking. Okay, so now the main problem we are facing is that in all these options, now tell us which numbers can be removed. If we are not able to do so then we will have to solve this problem. We have brought butter, we will come and check it till 135, set the number 19 in the filling, so that we can actually divide, we will be able to do 600, we already know the tan device, so the logic came from here that yes friend, now I am one. Why are we doing from to the end? We are going to enter by taking this lineage, from one to nearby, the admin method of vitamin browser, from which of us, why are we worried about the number of admin, we have taken the check from oven to number two, then this will increase our For something good, it means that it is time for them, so what will we do now, this fifth message of 12345, pick out whatever numbers you can in the white part and keep them, it will be a little easier, so do that thing here, yes, absolutely. It was completed here, changes were made in this line here, which I was doing earlier but the value is hundred, okay, so I was running from one to nine and checking any number which our Android can do. But now I know that the maximum number which Ragnarok will not be able to develop its skill is 5051, then why will it not be able to do so, now what should I do, I have reduced it a bit because I am not a Ranger, check from 1st to June 15th, brother, tell me right, this thing For what did I do, why from number one to number two means fifty plus 151 so that he clicks and subscribes to my channel, I have to write, so now I have actually made some improvement in time, if not, it is a big number. If it is from one to 1008, then you should find out by clicking on the number, it will take more time, it is okay, if you are going half the distance, it will take less time for you, hence if you apply this process, even then the time limit in your board will be exceeded. Something else will come, why am I, brother, till date, till the point till the end, even then I have deleted the message to the time, so marriage 1.21 What is a little photo marriage 1.21 What is a little photo marriage 1.21 What is a little photo constant, even if it goes, there is interest that you are in this time. Solving is still not a good approach. Now the question is whether you have done a good approach. So this was the second approach. Now I will tell you how to do more additions. I thought a little that if it is on that side, but if it does not come, then it does not matter. If it is not good, then now let us see what other way can be to fold it, as per your suggestion, our value will be fifty, so basically we will make it 11. According to the first approach, we will see by doing ODI test, others will see. Then we will look at it carefully, it will not come and shift will come. Understand in all these numbers, we have to find out those numbers which can be divided by my invalid. Okay and understand. Now I ask you to pick them up and check them. The reason is that there is a division that you will say because you know that the soil which is there is divided, it gets divided. How do you know, it is not like this, one is festive 15831, more meaning it gets divided, so you can see here. Here you have forgotten, have you forgotten that 15th and 1st are also there, brother, it is difficult to divide, yes, it means that it is good to see here, now tell me, will you do it? Other people subscribe to divide in 2002, so understand. Look how easy it is becoming, actually see there is one number whereas I see the work of two numbers, see here that the value of our loop will be found, it will become three, then brother no, he is not able to do three medicines, he is not able to do four. I would have done five, how would I have done it, how would you know, I will show you a holiday in five divides, 50 feet is fine, so I got 5 feet, I got it, my brother, I picked up five and also picked up the pan, I did not write this, the goods are written here, okay and This is going further, tan has also come from here, okay, we took out the button of 600 first brother, wisdom is fine, 1112 30 subscribe, definitely subscribe number, so now Sanjay, actually till where should I check, I have done the loop only from one to five. I ran mine and I found out the answer for the deputy, what will we do before that, it is running till 2030, it was looped 25 times, I am scared of using cargo planes in the first approach, okay, so now I know from the second one. To separate the Sangh only till five floors, you should understand that this is our giver, training is fine, I will write you and I am and Jaipur to add one of my numbers if I like that also and here along So mine becomes, I am getting a little understanding in between, maybe now we can see this, Meghnad, okay, so now we are checking this potato in this, I have 250, how to get the full subscribe here, if you We will cut down the numbers. Okay, so if we do that, then I will take what is the question and let us also keep this question with you beforehand, it will become easier for you. Okay, you must be understanding a little bit and maybe in future. If we tell you then it will become a little more clear what is happening here, whatever we do here, from this we have understood how far we have run the loop, look at your loop, now what you have to do, you know that whenever I have So, I have a number. Come, people who are running and together can give us the question time. Okay mind, so there is one more time and we will take it. We will take it and these two numbers will be able to completely divide our channel. If you keep to subscribe, then here are two things that will come in today's news activist, one will come, two will come, tan will come, front will come, Africa will come, all these will come, which number should we not take, we should not take the person, which person should we remove f9 from? Instead of two, 25. Well, when we all are trying to find out the value, take out the question, take out these two and keep them, then why don't you keep them. If you have kept them, then what do we have to do with all these and finally - 50 - 121 Paytm App Officer This time we will check whether it is equal to the one I have, if it is then our 50 is the perfect number, it is not opposite, it is simple, now here also something is given that it is Malwa number, it is correct, its very much subscribe my channel. If you find, then if my is being divided by the number, it means like it can be divided by the number, Subscribe Now to Cash Withdrawal number and this which we have appointed here, okay, what can be the maximum value of these two, that this relation Unite me and if I write here the route number * is the route number if I write here the route number * is the route number if I write here the route number * is the route number then it will also decide. Under the route number can be written in your comment, so this is my idea, this is what my nitin22 was questioning, so come, whatever is there, where should the route be taken. Number should be given here, you must have understood now if you read the whole thing then you will understand something else better. How did the route number come here? I am just telling you that what are you doing instead of here, you are driving. Na Ai * Why is ours equal to nothing? you are driving. Na Ai * Why is ours equal to nothing? you are driving. Na Ai * Why is ours equal to nothing? Understanding the above, we raise the High Court and because we raise it, you are right, then how far should the Commission go? If this happens, then because they do something, they should subscribe. Okay, here is the house, brother, please forward it to a list, we will make it real this time, okay, we will run this loop, assume that the value of my name here is 50, okay, understand, from one to where we will go. There are two ways to do the square root of 50, the first is from the importance UID and will give time, the square root of 90 should be simple and on the other hand, it can be done in Ghaghare subscribe definitely subscribe co because we have taken it from here so Get it done so that we can find out the changes that happened from this and here and the power that someone has removed, if the answer is coming and it comes to the rotating point, then it has made changes in these things and plus one that we can make some such videos. There will be under root number here which will have to be stirred because as our break must be subscribed, so I have posted it here because as long as it continues, now we understand that the appointments of this whole thing means till subscribe to our channel. If you do this then I will tell you for free that it has come here, look it has been added, you have understood, after this what else do we have to check, the value will come, if we know one number then we will have to know the second number, let us solve the question. So the question comes, 50 comes, in this case we are close to us, how will it work, you check what I * I, this note is like this, does 121 what I * I, this note is like this, does 121 what I * I, this note is like this, does 121 mean digits are not equal to 50, it means that you can edit the question by explaining 50. If you turn on the number then why does it happen, now you have a unique number, come to the other side that the value of I is Bittu, then the question will be how much, the question will come, if the purchase did not understand that it is two, then we will keep breaking down, you will add time. Then what will we give to this notification? Not subscribe, we will take out the question and put it here. Okay, why are you doing this because do it and after this like definitely subscribe here. Now subscribe school. If there was a 2.5 feet person then I would have come even at 10:00. was a 2.5 feet person then I would have come even at 10:00. was a 2.5 feet person then I would have come even at 10:00. Joined here ok what is happening now this war is over how many years have passed the code will not run on six air will increase 797 ok will the loop run or will I fit in 7010 comes no and then IS will be quiet till then we People are angry with me because my people are running from A to Z. Okay, so how much value did we get here, so we got Vansh with 52255, so one where you can help us with these more here. If you do this in this experiment and you understood that war subscribe then I will do it call my number confused till how much and it has come to the fore now Lalu's salty value is my 25. If you will understand in this case then I have given below Why is the line written here because it is a very important line I * is not equal to a lover, line I * is not equal to a lover, line I * is not equal to a lover, you will have children, okay, from here onwards, subscribe to the number, subscribe, if it comes, then the first number one is now * * * * now * * * * now * * * * Subscribe to my channel. Must subscribe. Useful to that tweet. 25201 property white hota hai nahi hoga nahi hota hai. Have you not subscribed? Is it seen doing the 25th family? If it comes, then we will take it all and keep the face because we have to If it has come, then you have to keep that one leg is found five, good and because why not get five in this case 125 in a completely different object, again five should be kept ready. You think what are the divisions of 25, this is 25 and 25 are from and if If we follow the same logic which we were applying then 125 will come, after explaining first the bangles will come, next four-five and five bangles will come, next four-five and five bangles will come, next four-five and five both are necessary because we can leave the question but when should we not leave the question when I*I will become equal. It was leave the question when I*I will become equal. It was leave the question when I*I will become equal. It was definitely felt here after getting the number that we found that 5 minutes have come here from this line. Okay, now do we need to add five by 5. It is not needed in our time. To stop this, the line has become more conditioned on the force. In this case, we have added the question 'Have you ever added it' which we have added the question 'Have you ever added it' which we have added the question 'Have you ever added it' which was five, so it means that we have removed it by subscribing to 125 and 500. AP, this was important. You must have understood the use of this line now. Okay, so 125 these days. The time is there, we got here, now in this we have to like and share the thing after removing which one, we are checking the perfect number, okay then it will come five plus one means 6 is equal to my number one right, okay so this is understood. You must have come here and stayed here, subscribed to my channel, to remove this, I told you that you do not have to subscribe from, this is very important, if you have these questions, then subscribe twice in 158 125 actresses. 5,000 whereas this is a twice in 158 125 actresses. 5,000 whereas this is a twice in 158 125 actresses. 5,000 whereas this is a cash withdrawal, they have to take it only once but if you put this I here and simply add this time and abuse it that at the time we are adding this number on or like subscribe because Subscribe These people are appointed on this number 9th May Complexity will be done Vivo SQRT of Nam Vijay What is the time of his career that Bigg Boss The quality of the city is constant because we have added it to some list so here But you can be anything.
Perfect Number
perfect-number
A [**perfect number**](https://en.wikipedia.org/wiki/Perfect_number) is a **positive integer** that is equal to the sum of its **positive divisors**, excluding the number itself. A **divisor** of an integer `x` is an integer that can divide `x` evenly. Given an integer `n`, return `true` _if_ `n` _is a perfect number, otherwise return_ `false`. **Example 1:** **Input:** num = 28 **Output:** true **Explanation:** 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. **Example 2:** **Input:** num = 7 **Output:** false **Constraints:** * `1 <= num <= 108`
null
Math
Easy
728
133
in this video we're going to take a look at a legal problem called clone graph so given a reference of a node that is connected undirected graph so undirected graph basically means that if node a is connected to node b that means that no b is also connected to no a right and then we want to return a deep copy clone of the graph so a deep copy basically means that we want to create it we want to create a new brand new um graph in the memory instead of pointing to the same memory location so each node in the graph contains a value int and a list of list node of its neighbors so we want so we have a node like this right has a value and all the neighbor node is connected to this current node and um here the test case form and the test case in this case is going to be adjacency list and basically you can see here this is the original graph and when we clone it right once we clone it will look exactly like the original graph but we're allocating a new space in the memory right we're creating a brand new graph in memory so in this case this is how we basically deep copy right deep copy the graph so here you can see we have given input right so in this case when we return it's going to be exactly the same and the different space in the memory of course so here you can see we have a another example where we have only one node and then we just basically you can see i know that input contains one empty list the graph consists only one node with value one so it does not have any neighbors right so in this case uh we're just returning a clone version of that and if it's null right if it's empty graph we're just going to return empty graph we're going to return null um so yeah so let's take a look at how we can solve this problem so to solve this problem here you can see we have a graph right this graph has one two three four three so one is connected two and four and two is connected to one and three and so on so the um the goal uh the approach how we're going to solve the problem is we're going to use the breadth for search and we're going to use breakfast search to traverse level by level to clone the graph from there and basically um we're just going to use a cue right because to use a to traverse the graph using breakfast search we're going to use a queue and basically q is basically a first in first out date structure so the first element in is also the first one out um when we remove element off of the queue right so basically what we're going to do is we're just going to start from this node right here this is going to be the head node right that's given which is no one and then we're going to add this current node onto the queue right so in this case we have one here on the cube um and then we in this case we're also going to have a hash table to keep track of all the visited nodes right so in this case we have currently visited that node because we're starting from this node so we're going to have no one right that's the o node this is the o node and the value is on this case in this case is going to be the new node right the um the new node that we created in our memory so once we create that node we're just going to save it onto the hash table right and then what we're going to do is we're just going to traverse all the neighbor nodes that no one is connected to in this case two and four right so in this case what we're going to do is we're going to create we're going to um create that in our table right and we're going to the old node is going to be node 2 right this node right here the new node is going to be a brand new node with the value of this node so at the end it will look something like this right and then what we're going to do is because it doesn't really exist in our hash table we also have to add it onto our queue right so in this case q we have node two and no four that we have to um traverse at the um later right so in this case we have no four node two and a four on our table and what we have also have to do is for each iteration right we also have to get our new node which is the node one point to those new node that we created in this case node two and no four because we know that the o node no one knows uh no one is connected to node2 and o4 and then what we do is we're just going to um remove the nest the top element or actually say the first element in the um the prior uh the queue right so in this case um value node two once we remove that and then we're just going to traverse each and every single node that node two is connected to in this case node one and node three and then what we're gonna do is we're just going to see if no one is there right if it's there in the table then we're just going to get new node in this case node 2 point to that node and then if it's not there for example node 3 we're going to do is we're just going to create that this is going to be the node 4 node 3 which is going to point to this node right and then this is going to be the new node which is going to be a brand new node 3 right so a brand new know that with the value of 3. so what we're going to do is we're going to get node 2 point to this node okay then we're going to do is we're going to add three because three is not was not um contained in the table so then we're gonna add it on to the prior uh the queue as well so now we have four and three right we remove two and uh we remove two and then what we're going to have is four and three right so three wasn't there so we added three onto q now we just remove four out of the q right so what we're going to do is we're just going to um traverse all the neighbor notes that no 4 is connected to in this case 1 and 3. we check to see if 1 is there one is there then we're just going to get no 4 is 0.2 is 0.2 is 0.2 no 1. and then we also check to see if no three is there no three is also there so we're going to um get no fourth point to know three right so if it's not there we're just going to um create that in our table and in our memory and we also have to add it onto the to the queue as well so then what we have to do because we didn't because those nodes are all contained in our tables then we don't have to add anything onto our cube right so now what we have to do is we're just going to um remove four right no four and then we're just going to move on to the next element in this case note three so now note 3 is basically um the next node we're just going to traverse all the nodes and no 3 is connected to node 2 and o4 and then basically we see if no node 2 exists no 2 exists then we're just going to get node 2 pawn to the new node of node 2 and we also going to see if no 4 exists in our table in this case we do right and we're going to get no three point to the no force new node in this case it's gonna be this node right here right and then at the end it will look something like this right and then our q is finished right there's no element in the queue and we can just return this top the first element right here in this case no one right so let's try to do this in code so how can we do this in code our first step is to do perform our base case because here you can see there could be a situation where the current node is not right so if node is null then we can just return null okay then we're going to do is we're just going to create our table right we're going to have a o node the old vertex um as the key and uh we're going to create a new node the new vertex as the value right so we're going to have hashmap is equal to hashmap and then we're gonna have a cue right basically we're going to store the adjacent nodes onto the queue right then we're going to because we're currently like visited that node right the current node we visit that node we're going to start by adding that node onto the cube right so we also have to add that onto our hash map as well because we're starting at this node so put okay so what we're going to do is we're going to perform now we're going to perform our bfs right so while the q is mt is equal to false right so if the queue is not empty what we're going to do is we're going to get the top or the first element off of the queue so it is equal to uh q that remove right this will remove the top element off of the queue then we're going to do is we're just going to traverse all the neighbor nodes that the first node is connected to right so for each node let's call it current so current node so first dot neighbors right so in this case all the nodes that the first node is connected to then what we're going to do is we're just going to um have two scenarios right so one is that the current node is actually contained in the hash table where we visit that node the other situation is that we didn't visit a node right there's only those two cases but at the end what we have to do is we have to get the new node the clone version of this current node um add it to the uh the new node of the first the clone version of the first node so let's have this clone version so first clone right is equal to map.get clone right is equal to map.get clone right is equal to map.get first right this will give us the clone version of the node that we removed from the cube right then what we're going to do is we're going to see i'm going to have a current clone a clone version of the curve node so if the hash table right the hash table the hash map dot contains current node right because there only can be two situations where either we can either visit that node or we didn't visit a node let's say we visit a node right let's say we visit that node then what's now what's the current clone is going to equal to hashmap.getcurrent to hashmap.getcurrent to hashmap.getcurrent right this will give us the clone version of that node the current node and then if we didn't visit that node well what we're going to do is first we're going to add the current node onto the queue right so because we're going to traverse the node later then we're going to do is we're going to create a node so we're going to have currentclone right is equal to newnode it's going to equal to current.val and it's going to equal to current.val and it's going to equal to current.val and then what we're going to do is we're going to save it onto the hashmap okay so then we're gonna do is we have to get the um the first clone dot neighbors dot add the current clone right so this will give us this will add this current clone onto the list okay and then we're basically going to continuously do that until the queue is finished right the queue is done uh there's no elements in the queue then we're just going to return hashmap.git node right so we're hashmap.git node right so we're hashmap.git node right so we're returning the clone version of the given the input node right so let's try to run the code linked list cannot find this simple link list okay yeah so this is how we let's try to run submit yeah so this is how we solve this problem so the time complexity in this case is going to be big o of v plus e right so v is going to be the vertex e is going to be the edges where the connections and um space complexity in this case is going to be big o of v right so number of vertex that we were given right
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
1,830
hey everybody this is larry this is me going with q4 of the bi-weekly me going with q4 of the bi-weekly me going with q4 of the bi-weekly contest 50 minimum number of operations to make strings sorted so this is uh to be short you know uh hit the like button to subscribe and join me on discord before i forget and yeah so this is just a very hard problem there's no way about it um i recommend you watch me salvage live during the contest you know you can fast forward to skip ahead or whatever but i'll have it after the explanation um and the way that i did it was and i actually i think i left my code in there which is that i generated the brute force solution and then try to figure out a pattern and the math here is not as you know interesting um because it's just about figuring out the pattern but the idea is that you know um you know key component about this problem is just trying to rephrase the problem in a way that you can implement the code um so here let's say so you know we're gonna go over the property of this problem right so that here we're basically one at a time what this algorithm or these operations trying to do is one at a time starting from the end keep everything sorted and yeah and so then here's we start with d and d sorted so that's good now we insert the d uh that's also solid so that's good now we have ode right now we have to sort this and the way that this gets sorted is by okay first the o becomes and i'm explaining it um without any proofs you really have to just figure out the properties um like i said if you watch me stop it live during the contest i actually like wrote down all these things and try to figure these things out manually so then what happens is that it takes the it converts the o to a d outside to the next letter um that's smaller than it so it converts to e and then now it's trying to sort the rest which is o and d so we're trying to sort the rest into d and e uh sorry uh dno and then now the next one the yi is going to um speech to uh the let the next letter which is d and then now it is going to be sorted in d o and then now this thing is sorted and then now we add in the next letter c so c it looks good because c is already sorted um and then now the next letter is t um and then here's the suffix we want to sort this into the next letter as i said so it's going to be oh i don't know it doesn't matter what this is but it just sorts it into this and yeah and then the next item after that is e so c d o t um d c e o t and then now at the very end it sorts it into this um cool so that's basically the idea that's the pattern that you sort it one at a time in these ways and then just you know that part is hard to figure out as is because you have to figure out the second part of well how many operations does it take to sort a suffix well it turns out that it actually is just um the total number of combinations with those characters so in this case because all the characters are unique it is going to be four factorial because they're four factorial so it takes here from here to here four factorial from here to here is four factorial and then so forth um and then it gets a little trickier when you have to do another when they're duplicate letters um but it's still the same concept but let's say we had which one was the one i have something like this i think yeah so then first it does b second b a second a and then now it has this and then it tries to get to this the next letter b uh aabc and the number and actually it starts i think by you know the reverse so the next one after this is actually this and then you want to sort it into this um and the number of operations that it takes it's actually just this formula of 4 factorial over 2 factorial times 1 factorial and i don't know how you know and this is a very uh common uh combo tourist counting thing so i'm not gonna do the proof here um because the proof is a little bit tricky i think what i would recommend as a prerequisite is just doing more commentorical problems um and this form this is a common numbers that should stick out to you when that happens um so yeah and once you're able to do this um you know from here to here and then now the next letter is just a b c and then now you're done um so yeah so that's oh wait no this hmm so c oh yeah and then this goes to a b c oh no a h i this and then now you have the second c to add so then now you have this and then it goes to you know um and then a pvcc right and of course in this case this is this would be you know it would take five factorial over two factorial one factorial um so that's basically it and my implementation is um is this and it i don't think i'm gonna go with that deeply because it requires a lot of maybe there's an easier way to do this but it requires some power and uh math with respect to uh modular inverse which i'm not gonna go over either because that's you know you these are things that are kind of what makes this problem hard and yeah i mean these are things that you have to or for this problem you would i would recommend learning it from other problems uh before you are able to tackle this one um and yeah and basically everything follows uh after this pattern after i discovered this i basically just implement this pretty quickly except for i have a i had a minor um bug that took me 15 minutes to debunk so it really tanked my ranking but yeah but i'm happy that i solved this without any uh errors so yeah so basically just going up really quickly you know um but i'm not gonna go into diamond details just going over the problem so this is you know just setting up the problem this is just me pre-calculating the this is just me pre-calculating the this is just me pre-calculating the factorial um you know given the mod and the modular inverse given the mod and then here you know for each character that we add in we keep track of a counts table which is just basically the count of every alphabet uh which is 26 and then for each and then say this is a c we look can we change it to a b if there's a b then we can change it to b and then we keep on going downwards that way um here we use this character we calculate what we said earlier with respect to the factorial times the ma the product of the modular inverse we mod that and uh um and then yeah and then we add that counts back on so that it can be you know use the next one and that's pretty much it and then this is just to keep track of the number of characters that we used we got it in another way but that's fine um but yeah and then at the very end we return to mod um yeah and this is what i had on booth first to kind of check my answers on a couple of cases uh smaller cases obviously but yeah um let me know what you think uh i actually go for my thought process as i was doing this during the contest maybe not 100 clear but you can kind of see my thought process as i do it so i definitely recommend it so what is the uh complexity right well for each character you know this is going to be of n loop and this of course will just be at most o of 26 because uh 20. sorry 26 square alpha squared which is the number of um number of characters in alphabet because we for each character we look at all the previous characters which is 26 and then we do this thing which is also of 26 we could have probably done some math in some funky way but we didn't do that like we probably could eliminate this loop but it was not slow enough so i didn't we have to worry because this is only three thousand so yeah it's gonna be three or n times alpha square um which is fast enough for this problem uh cool uh that's all i have watch me sub it live during the contest maybe it'll help a little bit like i said don't feel that bad if you don't get this one because i don't think i there's a lot of components that you need to know and it's very muffy every component is pretty muffy um so i don't i wouldn't i don't think it's gonna come up on an interview anyway unless you're doing something like crazy quant stuff so i wouldn't worry about it that much but it is a fun problem hope you enjoyed it and yeah i will see you later uh yeah watch me let's stop it live during the contest next m oh just is okay so this is bna oh just a say what this is impossible to understand okay examples don't make it really that much better j um so largest index i so that's b it is one index 7 x now that's a then such that 2 is less than b okay so that's a j is such that i mean j has to be two at this point but swap i might as well check okay reverse that string i don't know i know this one's impossible to read that along yourself okay example here is three and then okay so the biggest number that's so that's four okay let me slow down b and then reverse the string started at three some sort of weird insertion sort so what is this doing it takes the first instance of an inversion in this case well the latest inversion so b o d it swaps you has to be stretched largest index chair this is what the numbers are okay so then it's the first instance where swap by minus one and three uh you index eye i never know how to do this so just as well i can't even make trivial code correctly why that one seems fair why i always um i can't even get this code right bac so that now b and i should be z that should be one is another one oh i see okay so fun i mean we don't expect this one to be right but that's fine see okay so now we have the correct code just gonna be taking way too long yup 60 25 263. okay so then now we can see what the is doing delete code and see if we could skip steps um okay and yourself here two people solved it let's see so you and this is some like weird bubble up sort hmm how many people cutting this place what people have gotten it hmm so this is sorted so now that the suffix is sort of what happens it goes to the next one which is 19. let me even just look at the third example 63 this may be a hint actually two to the fifth times two all right let's look at that one first actually so the last two okay and then and what happens when you have a new number so everything after that it should be sorted right so now we look at b and we have to try to figure out the pee yes the number of inversion isn't just n squared because this is already bigger than n squared hmm so i'll look at it from the back but i don't know that i can get anything from that it's like a weird insertion sword what does this do what does the reverse do i'm trying hmm what does adding to t so this looks at the next suffix just these two i can't find any property with this that i can figure out hmm this suffix is done what happens when you see a new letter it takes it's about to be ended so then now that means that this will be sorted but reverse and then the reverse we're sorted we're trying to get it back to the front and it ticks i don't know but then now this is sorted c looks at c d so then it needs to do the prefix of huh and it does be until it and then it just does stuff until this is sorted again which is 30 24 moves away 4 factorio is 24. and then it does it for and then b and then now we know that it can't do that move the a to the front so then now you have these things which is four fractal 4 factorial again which means that this is 24 is that right i guess that's right so it takes n factorial to sort to thing and now we can bubble sort maybe so now we take the pee okay i mean i have some intuition but now i struggle a little bit and now a and then d has to go to the next character i think i get the idea but i don't know what to enter if this is of course okay so now we find ont and then now we sort this it's already done with move tests to you g and then we move this to a d so the c is good i wonder if this actually runs before okay just good that we have this a little bit yeah i'm close closer now i have to figure out how to get it oh and i have to figure out how to handle dupes bring this to a yi would require let's take the suffix looks good it's sorted so that's still good at the oh it does not sorted so then it ticks four moves is that right because the first move is moving the yi and then moving to d so it's two factorial times two factorial and then now we have to sort it c is sorted so that's okay and then the t will go from the o which is in theory this should be 4 factorial and we go from 4 to 28 and now we move it to the g just to press 24 yep okay let's see i have an hour how many people have gotten it so far people are really smart and fast it seems like um what's up do i need inverse path for this maybe okay i have to figure out one more okay that's what i expected roughly it's 4 factorial over 20 factorial i always forget how to do modular inverse okay um you um ready oh okay that looks roughly right you forget this by accident so we assume everything after this is sorted and now we take the count no that's not right what i want to do is okay now we're looking okay well you have to look at the next one so 4x in i don't know one that's not good oh my god uh um that's why i put in the math as well so now this should be now this is well this should be how do i do the math because then now we're swapping with x and then we won actually half white that's well good start topic i'm probably off by a little bit of a constant let's try something dumber we should be able to solve this given that we have a lot of time but still tricky i need to do this locally so that doesn't give me this stuff but okay why does that the case so i think that my mouth is started as fewer that's too hard to print out hmm something about the uniqueness that's why i'm a little bit oh i was wrong why is this particularly 210 hmm maybe i just need to suck it up and figure it out does this is this work okay so it is definitely something with the duplicate letter handling that i'm not handling well trying to reduce the case a little bit that's good maybe let's have a good uh case okay so let's go oh it's good to see it's good c so the first thing we're going to do is actually t and c and now it's trying to figure out how to do this t going to o is oh it's three it's for fact it was four maybe but i think i've i thought it was six so that's not right it's teague so just to get an o is here so we have t c o to sort out i don't know okay no this doesn't know okay i'm looking the wrong thing this is an oh so we need to sort this thing which in my math should be 4 factorial over 2 factorial so that's 12 and here we go 13. right and then here 13 it goes so see we're trying to sort this out so that's gonna be again four factorial over two factorial which is 12 so 25 okay so far so good and now this is an o so to sort this thing out it's going to be five fret so that's dirty so 55 i mean i'm i think my math is right so my implementation is a little bit off okay um oh that's awkward now one two three four that's why 18 is after it does all this which is definitely not right so okay so this first four is fine yeah and then now this is four yeah that looks like that would make sense nope okay so now this is singer c goes to one gets what hey hmm so it should be true that seems right um now see that's right so it was 12. that math on the whatever is side hmm yeah i mean this is right it does have the 12. and then it goes another six oh this is another 12 but oh i am dumb okay and this is a bad time for my computer to be running slowly oh but on it's so close okay oh come on of course now is the time that it is choosing to be slow my computer gonna cost me some points or whatever oh there we go my chrome always fixed the worst time to be whatever why is it pending oh come on old computer oh because it's printing a lot okay that looks like the right answer let's run it again now without the printing code okay it still has some printing code please cool that was tough i mean i don't know how other people did it um people are very smart in doing these maps but uh hope you enjoyed that you know this video let me know what you think hit the like button hit the subscribe and join me in discord hope you did well in this contest this problem uh let me know your questions um yeah so take care of yourself take care of others stay good stay healthy stay and to convert to health i'll see you next time bye
Minimum Number of Operations to Make String Sorted
count-good-meals
You are given a string `s` (**0-indexed**)​​​​​​. You are asked to perform the following operation on `s`​​​​​​ until you get a sorted string: 1. Find **the largest index** `i` such that `1 <= i < s.length` and `s[i] < s[i - 1]`. 2. Find **the largest index** `j` such that `i <= j < s.length` and `s[k] < s[i - 1]` for all the possible values of `k` in the range `[i, j]` inclusive. 3. Swap the two characters at indices `i - 1`​​​​ and `j`​​​​​. 4. Reverse the suffix starting at index `i`​​​​​​. Return _the number of operations needed to make the string sorted._ Since the answer can be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "cba " **Output:** 5 **Explanation:** The simulation goes as follows: Operation 1: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "cab ", then reverse the suffix starting at 2. Now, s= "cab ". Operation 2: i=1, j=2. Swap s\[0\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 1. Now, s= "bca ". Operation 3: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "bac ", then reverse the suffix starting at 2. Now, s= "bac ". Operation 4: i=1, j=1. Swap s\[0\] and s\[1\] to get s= "abc ", then reverse the suffix starting at 1. Now, s= "acb ". Operation 5: i=2, j=2. Swap s\[1\] and s\[2\] to get s= "abc ", then reverse the suffix starting at 2. Now, s= "abc ". **Example 2:** **Input:** s = "aabaa " **Output:** 2 **Explanation:** The simulation goes as follows: Operation 1: i=3, j=4. Swap s\[2\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 3. Now, s= "aaaba ". Operation 2: i=4, j=4. Swap s\[3\] and s\[4\] to get s= "aaaab ", then reverse the substring starting at 4. Now, s= "aaaab ". **Constraints:** * `1 <= s.length <= 3000` * `s`​​​​​​ consists only of lowercase English letters.
Note that the number of powers of 2 is at most 21 so this turns the problem to a classic find the number of pairs that sum to a certain value but for 21 values You need to use something fasters than the NlogN approach since there is already the log of iterating over the powers so one idea is two pointers
Array,Hash Table
Medium
1,1798,2220
79
hey hello there let's talk about today's recording challenge question word search given a two-dimensional board of given a two-dimensional board of given a two-dimensional board of characters and also a search word we want to determine whether we can construct the word by sequentially connecting adjacent letters on the board the adjacent here means horizontal or vertical neighboring so it's a four directional moves note that the letters cannot be used more than once so once we choose to use certain letters to form uh the prior part of the word in subsequent choices we couldn't use it again so that's pretty much the question let's look at this example we have a board with three rows and four columns now we are trying to construct the word abc cde obviously we want to start this construction from the positions on the board that starts with the first letter a so because the word starts with a so once we match that we try to find the next character we're looking around the neighbor of a and find b so now we match the two characters the third thing the next step is trying to match the next character in the word so it's a c so we see that we're now gradually building out this candidate passed in the world in on the board so once we match abc we try to do that even further we moved on to get another c for this example and eventually we will basically match everything so the path in the end has the same length of the word so that's the time when the candidate pass be promoted to the solution as long as we find one solution we can return to in the other case let's see that we are trying to construct the word abcb the partial pass candidate passes this highlighted here abc in the first in the next step we're trying to grab b around the neighbor of this highlighted c here we find there's no neighbor that's a character b so this candidate has been pretty much destroyed so we go back to a b and try to find c in other directions since that there are no other c's we'll go back to a uh at that time we will try to find b in the other direction but it's an s down there so it's not possible so we declare that starting from this a there's no way that we can find a solution to this problem so we will start with other positions and pretty much repeat this process so in short is backtracking or dfs so to handle the case that the letters may not be used more than once there are a couple of ways one thing is to as lo as we are growing this candidate to pass a candidate crossing of the characters in the board we can use some extra data structure to memorize the word we have used the character we have used or we can just simply replace the cell on the board by some non-character stuff like empty space so non-character stuff like empty space so non-character stuff like empty space so that in a subsequent search we would never really use it so that's also possible as well yeah so let's code this thing before code the because it's backtracking it's pretty much to try all the possibilities the time complexity is the number of cells on the board that's all the possible starting positions for this kind of candidate building uh tracking process and so that's m multiplied by something the backtracking would take a 4 to the l time because at any given particular cell in the maximum you are looking at the four directions and if the length of the word is l you're going to repeat this for 4 to the power of l times so that's the time complexity and for space complexity it's basically the lens of the word so yeah let's just start code this first thing we grab the size of the board because we're going to do the looping with this in mind the next thing we do is to basically lay out the main part for this function we're going to examine the board cell by cell if we have the matching in the first position then we start backtracking or we can in the backtracking logic to deal with that if the character doesn't match we term it early so it's easier to it looks easier obviously in the main part we're trying to look at the first character in the word so that's the main part for the code then what we need to do is to lay out the detail of the spark by tracking process it takes three things the current position on the board and the eyes position ice capture that we want to match from the word so if i is equal to length of the word that's the case when we successfully match the whole word then we just return true otherwise we want to determine so this means finished we want to test whether the character at this given position on the board is equal to the character that we want to uh we need so the condition is that it's a valid position on the board and also it has a value that's what we need if that's the case we want to look around the four neighbors and kick off this backpacking process from that position trying to find the next word but before we do that we want to mask this current character so that we don't revisit it but we have to restore it in the post order so once we determined there's no way we can match the whole thing uh in some later stage we want to go back and restore this character on the board so we have to first to remember it so here i'm just replacing it with empty space i'm looking at the four neighbors now and kick off this back tracking again from the neighbor's position with this uh aiming at finding the next character if we can successfully doing this over and reach the end when the eyes position when the i becomes equal to n indicating we match the whole word we're going to return true otherwise we pretty much do nothing return of force we can ignore it as well so in python if nothing happened it would just be known so this should do oh it's called board it's not green ah sorry i have to restore the character in the back tracking order uh yeah so that's it that's the backtracking solution to this problem uh basically uh usually when i analyze backtracking i think of the candidate that's growing and inside the back tracking logic here we are making a choice here that's basically this four directional moves and once we make a choice the next position we go we are growing the candidate by extending that by one more position in this case it's not a physical candidate i'm carrying in the backtrack it's rather the empty space on the board is marking the candidate sequence of characters that i'm using to find the word so i have to go back and restore that after i made the choice and determined that the choice is invalid so that's why i'm restoring it here i guess the distinction between backtracking and simple dfs is that once you make a choice and you determine that choice is fruitless there's no meaning that you have to restore the modification you did so that's a that's an extra step on top of dfs that makes backtracking slightly different from dfs yeah so the time complexity is all the possible starting locations indicated by the nested double loop here and the four to the l is indicated by the this for loop here we try four positions and every position we just recursively call this backtrack so it's a forward to the length of the word uh for space complexity it's the call stack of this backdrop this can go as long as the i become equal to the length of the word so that's the levels of recursive call that's going to happen so that's the space requirement because i'm modifying the board to indicate the current path is not using any extra data structure uh yeah so that's uh this dfs backtracking solution to word search uh if you're interested i have a video about the word search two which is nothing but you know which is nothing but uh search for multiple words with this uh backtrack procedure so instead of just using uh the in index and find the eyes position of the word uh it's trying to match the try pass so the stuff you put on the backtrack core is a node object in the try and the current position so a slightly more complicated but the main part is pretty similar you have the nested loop here and you have a backtrack which is nothing but can we promote this candidate to the final solution if so we add it otherwise we're going to verify the current matching and mask of the board position and go make a choice of the four directional movements so in terms of the main logic in the code it's uh it's pretty much identical to this one except that uh it's using a try note try data structure to do the matching but with that you can match a c uh you know a set of different words on the board so if you're interested you can check out the video over there um i'll try to put a link up there so that's the code that's the question for today
Word Search
word-search
Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_. The word can 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. **Example 1:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED " **Output:** true **Example 2:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE " **Output:** true **Example 3:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB " **Output:** false **Constraints:** * `m == board.length` * `n = board[i].length` * `1 <= m, n <= 6` * `1 <= word.length <= 15` * `board` and `word` consists of only lowercase and uppercase English letters. **Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
null
Array,Backtracking,Matrix
Medium
212
208
hello all welcome to netset os today in this video we will know about dry data structure before going for any data structure array binary linked list heap data structure and also stack we have seen pros and cons of each structure in an effort to make it easier to see what type of problems that structure was created to solve now today's data structure is dry try is the data structure which was created to solve the problem of representing a set of words here throughout the video we'll be looking for inserting nodes how we can insert node in a try searching nodes how we can know the words starting with a particular letter and with that we will know the practical usages of drive so basically try comes from the word retrieval here there is try so however tries basically a tree data structure whose note stores the letters of alphabet by structuring the notes in a particular way words and string can be retrieved by traversing down the branch path of the tree we'll see this first let's see the usage of price so that will be more excited to know how it works internally so if i go to google and if i type like sp a the words coming with spa are spanning tree spanish to english spanning tree algorithms bandana spa online spa near me spanish flu spaghetti spain basically auto complete feature as i typed here in google search engine it will complete so here we can imagine how typing three letters into a search box would retrieve a subset of a much larger tri structure it can be spanning trees spanish to english spar now if we see the other usage it is used for matching algorithms and implementing things like spell checkers so it is quite exciting to know how drive works internally so throughout this lecture we will be seeing how we can retrieve the words so let's start with how we can insert a node in a try so let's start with first inserting nodes so we know tries are often used to represent words in an alphabet here in this example we can start to get a sense of how exactly that representation works each tree has empty root node like this and it will be linking to other nodes so that the shape and structure of try is always a set of linked nodes and these link nodes are connecting back to a empty root node so each node contains an array of child nodes as we can see this is a parent node which is empty and it will have the child nodes starting with the letters of the alphabet the letters in the alphabet are 26 so we can say starting from a with a b c up till z so there is one thing to note the size of tri is directly connected or correlated to size of alphabet that is being represented here we'll see this with example here we will take an example where we have a try that contain empty node now here in this example we have an empty try which is referencing to children nodes here if we notice we have two things over here first a value which might be null over here and the second the references to other nodes so here it is an area of references to child nodes all of which can be null also so basically each node in a try includes the root node itself when i try representing the english language it consists of single root node whose value is usually set to an empty string the root node will have an array that contains 26 references which at first will be pointing to null as try grows those pointer starts to get filled up with references to other nodes as well a can be referenced to other nodes then that particular node will be referenced to other nodes similarly with all 26 references of english language and here it will be indexed starting from 0 and there are 26 letters that means it will be starting from 0 index to 25 and why they are 26 since there are 26 possible slots for 26 letters of alphabet so enough of theoretical things now we will start with first inserting nodes let's say we have rhyme of words over here in front of our screen and we have to make a try so as we have seen so first we will take the first letter which is b so i'll start with the first letter b over here now after b there is u so it will be making its children node with u then g then l then e perfect now we have the first word completed in our tribe now we will start with second word which is b e so we will see the first letter is b available in a try yes so here only we will take this b referencing to the second letter which is e so here itself it will draw e let's say if we had here instead of u e we will have taken the help of this e itself but earlier it was u now it is e so we'll be making the other child node which is e over here then after e it's u so we will take u here then g then e and thereafter we got l now after this we'll be turning to third word which is blue gill so we'll start with first letter which is b we are comfortable we have b over here as our first letter now we'll be searching for second letter which is l but we don't have l over here so we'll be making the next one with l then u then e then g then i and then l s given here now starting with the other word which is b u g e l now for searching for b we have b here then for u also we have here so we'll be taking the help of this b then this u then we have third letter s g we will be taking the help of this as well then e but we have here l so we'll be taking the other letter e after this g as g is referencing to l as well as the other letters apart from l also as we have seen here it is referencing to all 26 letters so taking the help of this feature in a try we will point e over here and then the last letter which is l then we'll be going for the next word which is starting from f earlier we have seen all the words which was starting from b but this time it is starting from f we don't need this b right now so we'll be taking the another letter which is starting from f and here we are pointing to our empty node that's why we used to use here the root node with an empty string so that it will be referencing to all 26 nodes similarly we are doing here as well it is referencing to b as well as f and similarly to the other letters of the alphabet let's start with f now here we have f then u then g then a then l then proceeding towards the next word here we have f so we will take the help of this f then u wow we have u also here then g yes we have g also over here we can take the help f u and g then proceeding further we have e but earlier we had used a now we need to divert our path to e this time and then we will have l so with this we have used our earlier memory of fugal and using this memory we have made the other word f-u-g-e-l the other word f-u-g-e-l the other word f-u-g-e-l now proceeding towards the next word where we have frugal so frugal will take the help of f first yes we have but then we have u so we need to divert our path from here itself r then double o i'll be taking double o over here and then g then l and then we will have e so till here we have seen each node that each node has 26 children even though we are not using it but they are there now what if i want to add one more word which is flugal the new word and i want to add to our existing try so before adding the word to our existing try we need to take care of two points first we need to check that this new word is existing in a already made try or not if it already exists then we need not to add that particular word so first we should be confirmed that the word which we want to insert in a try should not exist then next if we have traversed down the branch step by step because we have already seen whether this word exist or not we have traversed that means we have traversed throughout the try so now we will insert a value into the node referencing where the word should go simply as when we have this flugel first letter is f so we'll be going for first the empty root node and we will traverse down and we'll look for f here we have f because the other one the other child node is b so we will be leaving this and going for f over here then we'll be going for l here l is not there so we'll be making the other branch for f as the l the child node of f and it will be going to make its flow girl as like this let's try to understand this in the other way here i want to insert let's say fly simply f l y and i want this fly should be given the value as six this is a key for fly and this is value as 6. now you'll say if you have to insert a key with a value you can make use of hash or a dictionary right we can make use of dictionary where we just need to give the letter fly and its value so there is a difference between hash and try we'll see this in the couple of minutes now we'll see how we can insert this word fly with the help of try as we know there is an empty root which will have an empty string firstly and an array with 26 references let's say from a to z and you can see we will find our null link at f pointer so we create a new node over here with f as we have to insert fly so the first letter is f over here so somewhere in the between a to z we will have f over here which will be linking to the other child node but before that it won't be having anything null link we will encounter the another null link which will be referencing from a to z then we will create the other l over here the other node l similarly it will be referencing to other a to z now we'll be seeing for y over here and as we reached the last character which is y it will be allotting its value which is fly value is 6. so this is the one way to tell that our word is completed by here we have fly as soon as we encounter this 6 over here we will be knowing that this letter this word is completed by now otherwise if you are going for fl we won't be having any value so let's say here it will have zero so whenever it reached till l there it won't be encountering any value that's why it will be knowing that it is an incomplete word so basically we will first look for pointer for f since the try does not have anything apart from a to z the reference at f in our root node will be null before and the root will have all the empty slots from 0 to 25 as soon as we get this f it will be going to the fifth index and will fill this f towards this null link that contain a reference to one node now we have a node at index 5 holding the value of f but our string is fly now we will be doing the same thing it is referencing to f then it will be given l will be at index 11 and similarly it will be referencing for y as well and then it will be allotting its value of that particular key which is six though there are other ways as well we'll discuss one by one so in the future if we want to retrieve the value for the key let's say fly we will traverse down from one array to another using the indexes to go from nodes f then l then y when we get to the node at the index for y we will stop traversing retrieve the values from that node which will be 6 over here now we have this fly over here and we want to search for the key let's say we have already drawn fly and i want to search for fly in my try and want to find the node at the last letter we can look to see its value if it has null value it means the word is not a currently a key over here as here first it will go to the empty node then it will go to f is here fine enough then it will look for l here l is there then it will look for y and as soon as it will see this value to the fly that means it found the word is hit in the search list we got our word now if we want to delete from a try let's say we have fly with 6 value and flies with 14. that means there is an empty node where we have f l y with 6 value f l i e s with 14 value now if you want to remove key value pair we first find the node for that key and set its value to null so that when it will encounter flies let's say i want to delete this flies so as soon as i get after traversing f l i e s it will delete the complete word over let's say i want to delete flies so first it will traverse down and as soon as it will get flies the value it will start deleting let's say first i will look for its parent node whether e has another child or not because if this parent has another child then we won't be able to delete this because it is also referencing to another child also so s has e as parent which don't have another child node so we will delete s from here then we will look for e whether he has the parent which has the other child so we will delete e from here then for i it will look for parent which has the other child yes here l has two child y and i so we will delete just i o y and our flies is being deleted from our try and also as i have searched in the google engine for spa here it is giving all the words which are starting from sba so let's write a program for implementing a try for a prefix tree which is a try here we will insert search as well as we start with so for inserting first let's define its children so i'll write self dot children equal to all 26 letters let's define by default none into 26 as it is referencing from 0 to 25 now as we have seen the value allotted for the key value means that a word is completed now we can do one more thing we can simply write at the end of each word let's say here as the flugel completes here it should check of each end letter of the word whether it is and or not so for this i'll write self dot is and of word by default we will define it as false and we will see for each word if the last letter is set to true then we will be thinking it as a complete word so let's start with insert so for insert first let's take the current as first we'll define itself then we will iterate letter by letter so here i'll write for i in word here you can also define with the length there you need or to use this n keyword then i'll be looking for this if current.children looking for if current.children looking for if current.children looking for each letter or we can say the index here let's define index which will have od of i minus the first letter so that it will have the index that particular index of that letter so here i'll write a and we'll be checking for each letter which is index if it is none then it will be going to try so here it will go to try and then we will store it in current only which will have current.children index current.children index current.children index and as soon as the word completes we will give the end of that word which is end of word set to true so that will be confirmed that a letter has been inserted completely similarly we'll go for search i'll take this then we will iterate one by one where current will have current.children for index and here we will be looking for each current value if it is none then it will return false and then we will look for the end of word if it is last letter it will return true else it will return false so search will be searching like this whereas in starts with we are not at all concerned with the last letter so we'll be simply copying this and we will delete this last line instead of this it will return true now when i run this code let's see oh rdi here i have used square brackets instead of this i should use i with braces all the places then i'll run the code again here it's prefix so i need to use over here prefix let's run it again and here this is accepted so we'll submit here and we'll return back now we see the difference between hash table and try basically hash table comprises of array plus linked list whereas tries uses arrays plus pointer or we can say references now if we see bigger notation runtime for creating a try structure is completely dependent on how many words the try contains so it will have order of m n m for longest word and n signifies total number of words where we can search insert delete from the try depends on the length of the word so we can say total number of words the complexity it will have a n a signifies to the length of the word so in the try introduction we have seen how we can insert node how we can search node and also starting with letters how we can go for it and also we have seen the code for it and also we have seen the practical usage of drive which is its auto complete feature retrieving the subset of much larger tri structure as well as it is also used for matching algorithms and implementing things like spell checker so hope you got the introduction of try now in the next upcoming videos we'll be taking questions on try though we have covered lead code number 208 we will take more questions based on it so let's meet in the next video till then bye take care
Implement Trie (Prefix Tree)
implement-trie-prefix-tree
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: * `Trie()` Initializes the trie object. * `void insert(String word)` Inserts the string `word` into the trie. * `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise. * `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise. **Example 1:** **Input** \[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\] \[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\] **Output** \[null, null, true, false, true, null, true\] **Explanation** Trie trie = new Trie(); trie.insert( "apple "); trie.search( "apple "); // return True trie.search( "app "); // return False trie.startsWith( "app "); // return True trie.insert( "app "); trie.search( "app "); // return True **Constraints:** * `1 <= word.length, prefix.length <= 2000` * `word` and `prefix` consist only of lowercase English letters. * At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
null
Hash Table,String,Design,Trie
Medium
211,642,648,676,1433,1949
202
hey guys persistent programmer here and welcome to my channel so in this channel we solve a lot of problems and today we're going to look at the problem happy number so let's go ahead and get started right away this problem states that write an algorithm to determine if a number n is happy so what does this mean if the number n is happy um they say that a happy number is a number defined by the following process starting with any positive integer replace the number by the sum of the squares of its digits and repeat the process until the number equals one so let's look at this example over here so we have 19 um and what they have done here is they've taken the square of 1 plus the square of 9 so that's 9 square is 81 plus 1 that gives you 82. and then now they've taken this 82 and then they've done 8 squared which is 64 plus 2 square which is 4. so 68. so this is the way um the algorithm needs to work to determine if we can get a final sum of one so that's what the problem is asking so if this is the case then we need to return true um otherwise we need to detect if there is a loop so if a number is not a happy number then what will happen is the sum will keep repeating itself and we'll see an example of this when we're discussing the solution so in that case we need to return false okay so let's dive into the solution okay so let's look at this example over here where n is two so if we were to take all the sums of two so two square is 4 and then 4 square is 16 and then at 16 we take the square of 1 and 6 so 36 plus 1 37 and if we kept going like this we would get a sum of 20 and if you look here that um if we take the digits out of 20 and if we um add them up so that gives us 2 squared plus 0 squared which is 4. so we've already seen this 4 over here and what this means is that um there will be a continuous cycle when there is an input like this so again we'll take four and then square it and then we'll get 16. so it's just gonna go in this endless cycle over here and this is what um we want to say is false right so it's not a happy number so we need to return false in this case um and then the example that we looked at in the solution is where uh once we keep taking the sums we get we eventually get a one and that's what is defined as a happy number so in this case we are going to return true okay now a few things to keep in mind here um while doing the code is how to get each digit right so um one of the ways that this can be done is to use the mod operator over here which looks like this so what this does is anytime we take the mod um we take the mod of the number uh mod 10 it will give us um this number so like 19 divided it will give us the last number um of all the digits so here in this case we have 19 mod 10. so um 19 if you divide 19 by 10 you will get a remainder of 9. so that's how we can get the last number and you can practice over here i've put in some logs if you haven't used the mod before but um this is one way to get the last number and then so that's okay but how do we get this number before it right and any other numbers before that so how do we move forward so what we can do is we can take the 19 and we can divide it by 10. so what this would give you is one point some number right so if you do math.floor math.floor math.floor what this function returns is um anything that's any integer that is before that um decimal value so it's it'll it won't round up so it won't take any decimals into consideration it will just return you um this one over here for this case right so what do we need to do after this so what we need to find the squares um and we need to keep accumulating them so we need to add 9 square which is 81 and then we need to add 1 square which is 1 right so this is how you would get 82 right so that's how you keep getting the numbers and if this all makes sense we can quickly do a walkthrough of what the solution would look like so for this type of situation where we want to check if the number is repeating or not um using a set is a good candidate because um a set only stores unique values so we can check against the set to see okay does this is this number repeating is the sum repeating itself or not um and then if it's not repeating then we're good that means it could still be a happy number so what we do is we add that number to the set and then we will uh we will initialize this square sum so what we saw over here right so we need to do this accumulation here we need to square the digits and then add them right and then finally we can check if the square sum equals 1 then we know it's a happy number so we can return true otherwise we're going to return false because this if this condition does not meet we can just return false because uh let's take this example here right after this case um we're gonna see a four from if we take the input as 20 and when we see that four we can see oh the set has this four so we know that this would be a cycle so we can just return false awesome so i'm back in the code and i've put the question um example up top here so we can refer to it when coding so the first thing i've done here is created an empty set called scene and this is going to be used to track whether we have seen that number or not so i can say while um we have not seen that n so this is our auger while loop and now what we need to do is if we haven't seen it we're going to add it to the set um so for next time we're not tracking the same number right so i can say um scene dot add that number all right now we need to go through each digit and we need to uh find the square root sum so first of all i will initialize that square sum variable so i will say sq sum is going to be zero and this refers to the fact that okay like we need to have um a first sum so first let's initialized to zero and then now what we're gonna do is find this nine square and this one square and then add it up and get the uh set the end value to 82 which is going to go back up here um for analysis again so to see if that 82 exists in the scene right so we have initially put that squares up to zero and now what we're going to do is have a way to iterate over each digit so we'll say while um our number is greater than zero right um what we want to do is go to that nine first so we're going to say square some is going to be equal to we're going to add to it um the n mod 10 so this will give us the last value of the n and we're just going to uh times it to itself so this is how we're going to get the square you can also use the math power function here um if you want so once we have that square sum what we need to do then is get that uh value before that number and also add it to the sum so to do that we can use the floor function so we'll save mata floor and we will get n divided by 10 so that's how we're grabbing that uh digit before this number before it and what we're going to do is we now have this one for example here and we need to um we need to set the um n to this so it goes back up here and then adds back to the square sum again so we want to add that one square uh back here right so we are going to set n equals math.floor n equals math.floor n equals math.floor and divided by 10 yes so that's going to give us if our n is 19 in the first iteration it will give us the one okay so this is going to be said come back up here and yes one is greater than zero so it's going to add itself to the sum so this is how we can create a loop for the number to keep um adding the square of itself all right awesome so now what we need to see is if we're able to get that square sum equal to 1 or not because if that is equal to 1 then we can just return true so we will do that check here so we can say if square sum is equal to one then just go ahead and return true and if it's not one yet so for example if we're at 82 and we need to keep going and check um if we have other numbers that can get us to that one we need to send it back up to this while loop here so what we're going to do is just going to set the n value so we'll set n equals that square sum so what we did here is we just set the n uh to 82 here so then in the next iteration it's going to go and compute the 2 squared plus 8 square 68 and then set n to 68 and then go back up again so it will keep doing that until it finds a one um so that's what we're doing here and then if we don't find a one um after we have gone through all the numbers um then or we've encountered the same number over that means we're not going to get to a one um so in that case we will return false so we'll go ahead and return false here okay it looks okay to me i'm going to run this okay accept it and submit yay success
Happy Number
happy-number
Write an algorithm to determine if a number `n` is happy. A **happy number** is a number defined by the following process: * Starting with any positive integer, replace the number by the sum of the squares of its digits. * Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1. * Those numbers for which this process **ends in 1** are happy. Return `true` _if_ `n` _is a happy number, and_ `false` _if not_. **Example 1:** **Input:** n = 19 **Output:** true **Explanation:** 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 **Example 2:** **Input:** n = 2 **Output:** false **Constraints:** * `1 <= n <= 231 - 1`
null
Hash Table,Math,Two Pointers
Easy
141,258,263,2076
753
hey guys welcome back uh today in this video we gonna solve a problem uh from lead code uh number 753 cracking the safe so this problem is from graph data structure and the solution we use is dfs or dipped first search and also google was the last company that had this problem in interview so let's go and learn more about the problem at the beginning and then start to solve it okay yeah so problem is uh name is cracking the safe but for sure your interview are not gonna tell this to you so if they're being really good then they give you texts like this for you and some example that you can take this and move forward so but sometimes even they come with an empty uh you know description and they just verbally tell you something so you need to write it down yourself so uh my approach usually is going to be like this so as soon as i start i go for a problem also let me write down time here to find out you know how quick we can do this so 2 23 is the start time so first of all we focus on the problem to understand it and then right after in middle of the writing problem we will write markdown comments to make it organized and get signature of a problem and then we will go for visualize problems and actually examples this is very important part so at this point uh hopefully you will remember what's the problem or you will some solution come in your mind so we will go for code and uh for unit tests uh and at the end we will go for complexity okay so to start this we will start from where we gonna write down our unit tests which is uh the best part is uh top and then where we will come with the solution yeah so solution and language we're using it's a swift today so maybe this been there or not you're going to type it but you don't have signature of the function or api of the function so you need to start from this point so first of all we say okay we're looking for a function to do what yeah so that will tell you yes there is a safe protect by password the password is sequence of n digits so here i start from parameters and then my first parameter gonna be n which is n digit uh and so it's digits so it's gonna be integer so first question you will ask from your interviewer what's the range of n make sure to ask this they need to clear this for you so uh here in this example it's between one and four and k is between one and ten so just keep in mind okay so if this is one and four is digits and then here we will say n digits so sequence of n digits the very digit can be in range of zero until k minus one so okay gonna be the second integer we will get so uh and it's between one and 10. okay so we almost got all information for inputs here you can write down description of the uh your problem and don't forget to write down you know to mention yourself about time complexity and space complexity we don't know at this point uh we'll figure it out at the end usually and uh for sure we need to find out what we're gonna return so what we return is uh kind of s string but let's see what is yes here we will see return any string of minimum length that will unlock the save at some point of entering it so it's gonna be a string which is the password and any string here let me write down description here okay but it is important that we know what is the problem and how idea yeah so here i will write the description of the uh comments uh sorry description of the problem so this we will be looking for technically this minimum length that unlock the safe at some point so we write a function to find crack to unlock that you know safe so to understand this problem now we need to go for visualize you know for now we get that we have two you know two digit and we'll have one and put that string so and from base of these two digits we will find you know what is the you know what you know our output supposed to be as end digits gonna be number of the password and digit and k is range of the password characters could be so based of all of this before i jump to visualization i try to write my you know function signature so function crack safe underline n which is integer and underline k which is integer and we return one string so this is going to be my function but to find out what exactly we're looking for we need to visualize it so i start from example number one so in this example we learned that our length is 1 and k is 2. so if we want to write down our all of our possibilities we say okay we have possibility was zero and we have a possibility of one so base of this i will say if i say yeah my string can be zero and here zero one or opposite so this could be you know one and zero which match with uh you know our outputs that we're looking for but still we are not clear let's go to example number two so in example number two if you want to visualize it we need to make something like this we should say okay so zero could be one the answer okay so i can go by this uh that say okay if i start from zero you know and my output is this one so i put this output here okay and yeah i say okay zero okay and at the rest gonna be one zero so the second possibility of uh you know pro answer will be zero one so i can go by this so here's okay zero and zero one and a again one zero so this is the answer yes and it's gonna open it for me the other possibility is one so if i go zero and then bond one is gonna open and then and the last possibility is could be one zero okay so 0 1 and then 1 0 which is the answer i put answers separately it is important that you do visualization first of all you will get the solution in your mind also you will get you know some answer sometimes this help you to you know figure out what bill could be an answer so okay so now at the visualization i write down my time is to okay i actually forget i have the interruption between this so uh i'm not gonna go over that okay so uh let's go for uh solution now so for solution uh you know i can say my approach will be dfs which is deep first search and backtracking because uh you know i'm i have to guess and find out if it's true and then if it's true i can move forward and if not and i go i come back and continue and i use dfs because uh if i want to say okay my decision tree is gonna be something like this uh so for example i just say okay 0 is my first decision actually 0 is going to my first decision so the second decision of me could be 0 1 and 1 for example uh or one zero so uh i need to go and uh do you know by this three uh as a you know deep first search uh so means that i go uh you know by uh this way not by level okay uh if it was breathes first search then i'll go by level but you know i need to go from my tree down in one line which could be answer okay so let's go and start solution to keep this uh video short so first of all i start from my base cases and so for best case i just say if n was one and k was equal one as well so my solution or the only solution gonna be zero so i can i will return my only answer gonna be zero because k minus one can be zero okay and then i'm gonna start for memo or memoize okay so here i declare one variable i name it visited as usually we do for backtracking and so i make this to be a set in swift from type of string yes and i do parenthesis which is means that fill it with empty value for me then also i'm gonna create one value one variable by the name of start so this variable will be equal with a string so i'm gonna cast the fill it with the string by repeating with zero in there and with a count of how many it's gone it's gonna be n minus one so this is gonna be my string for zero then i'm gonna call dfs but i did not declare this but uh signature i like to be for dfs we're gonna be uh get starts here and also gonna get k here and at the end gonna get visited but i make a visited as a pointer because i want to make it make change on this visit that i need i want to keep updated okay so after i called dfs then i should have a result okay but uh first i am coming here and on top of this in my class i'm gonna define results so i just say where results equal empty string okay so i just say result that happened what's for me i want to say append for me starting there and at the end i'm gonna return results so this is gonna be my main function and then i'm going to write my dfs function which i call it here so i write a function by the name of dfs and so what gonna be signature so uh underline uh starts from type of string and also underline from type of integer also underline visited different type of sets of a string so this is to be capital also here s need to be capital okay so i gave my signature here something that i forgot is that this should be in out because i'm gonna move you might want to take this so i use in out and i use and sign here to be able to changed it still you know i add here start but uh here i don't think so i changed that one so let's uh see what is work uh for i'm gonna look at it later okay so here i write one in one for loop above index in range of 0 to k not exactly just k minus one and so from this range i want to do my loop okay so here i write a variable i named a variable by the name of neighbor and i say okay this value will equal what equal back slash and again practice okay so here i use start and here i use index and then i'm gonna write some my logic so if not visited uh so if you could apply maybe visit it then with not it's going to be true so if you cannot find it then go through and do this for me so what i'm going to do is i'm going to add this to visited what i'm gonna add neighbor yeah i'm gonna add neighbor in visited first then i'm gonna say okay variable char array equals area over characters and neighbors filled with the neighbors and again now here i'm gonna call give us so i'm gonna call dfs so this is recursive as you see and uh so this time i'm gonna say okay a string of char array we just i just defined it on top from one to end and also k and also and visited and i'm gonna save my results which is public up on top i'm gonna append one string in there of index okay think we've done just one part uh remain because uh i use you know access to uh string which i don't have it there so i have to go to extension of string protocol and define subscript for that so subscript of index from type of int return for me character how come how by this space to return itself and self.index then the self dot start index and offset by index so i add this to a function that you know two is a string protocol then on top you will see that i use it so i'm gonna run this to see if it's work mostly there will be some typo and i need to fix them so i go by and get to 29 line 29 here i return 0 which is uh not correct actually it's returning string so i can run so line 43 this time and what's the problem line where the three set of string has no member contains so i think i mistyped this yeah so that fixed and now i go to line for this six this time and the ad sign visited i think again uh my visited is not typed correctly let me see so it seems okay so let's see what's the problem and say visited in scope solution cannot find yes oh i wrote end sorry dollar sign should be end okay here we go yeah we're done so uh as you see we got you know i test you know right actually we got the minimum test uh done uh so but uh you know to be more professional and convince your uh you know interviewer you need to write test case as well for that you know i use assert because uh you know xc test not working inside here but you can write a exit test if you have time as well to make your interviewer convinced to hire you so example number one make sure to write all examples and so first of all i'm gonna create an object uh from my solution and then i'm gonna write my inputs and actually define my input then i'm gonna define my output so i'll put supposed to be this and here i use asserts okay so inside asserts i will call my you know object and then my function and inside function i will pass n and k and output should be equal output so if this is not working fine we will write failed example one two we know that which example failed okay so now i run it again yeah here you will see that solution yeah miss typing yeah it's working fine so now you will see everything into this unit test is independent so i'm gonna write my second one which is available here i advise you to write couple more for base of your self and should i submit that but anyway let's submit this it's working fine and you know that's the speed is not too bad and yeah it's uh street and time is 36 seconds and you know if i run this when this submit pushes one is work and you can add more test cases okay yeah that's it uh for today and i hope you liked this video and if you like it please make sure to give it a thumbs up and uh don't forget uh to be subscribed and if you have any idea or any advice about this that will be helpful could be helpful for other folks just please make sure to leave a comment below have a good one bye
Cracking the Safe
open-the-lock
There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit. * For example, the correct password is `"345 "` and you enter in `"012345 "`: * After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect. * After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect. * After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect. * After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect. * After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect. * After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks. Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_. **Example 1:** **Input:** n = 1, k = 2 **Output:** "10 " **Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe. **Example 2:** **Input:** n = 2, k = 2 **Output:** "01100 " **Explanation:** For each possible password: - "00 " is typed in starting from the 4th digit. - "01 " is typed in starting from the 1st digit. - "10 " is typed in starting from the 3rd digit. - "11 " is typed in starting from the 2nd digit. Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe. **Constraints:** * `1 <= n <= 4` * `1 <= k <= 10` * `1 <= kn <= 4096`
We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`.
Array,Hash Table,String,Breadth-First Search
Medium
null
1,305
Hello Everybody Welcome To My Channel It's All The Record Problem All Elements In Two Remedies At Trees Should Give Into Binary Search Tree And Root To Return Ali Containing All India From Both Recited In Ascending Order Showcases 28500 Subscribe Combination Problems Like To Travel In To- Do List To- Do List To- Do List Will Solve This Problem For The Self Actually History subscribe for Live Video 0 That This Vansh Wednesday List For The Tree Will Exist This To-Do List And Will Get Answers Exist This To-Do List And Will Get Answers Exist This To-Do List And Will Get Answers Active 1234 Sudhir and Souhard Universal Soul Will First Go to the Left Most Famous Channel Subscribe Video Channel Veerwal The Video then subscribe to the Page if you liked The Video then subscribe to the Channel subscribe Kare To Bilkul Channel Affidavit Communal Forces Will Come Back Shabbir Will Go Back To Subscribe School Me Mid-Day Mid-Day Mid-Day Meal Distance No Problem Solved List Play List New A Relaxed Also Defined As Too For The Road Too Soon You Will Call In Adhruv Veer Will Call In More Trending &amp; Share &amp; Subscribe Civil Hospital List In Turn Will Help Sexual Aid In Untouchables Channel Subscribe List Check Root Canal Ki dance simply return form hair otherwise call in order for daughter of a ki and similarly id list start and into new delhi in to-do list call log into new delhi in to-do list call log into new delhi in to-do list call log in 9th 1540 e hai so disawar inverter method vishal soni to write a march list sudesh will be A private and will return list of teachers in summers list will guide you to list in danger list first class list of teacher a place to enter in the fair will create another list which means to return to find job merit list is latest and will screen Two Points On A Gift For Tracking Also Index For List 2 And Jobs For College Students Will Spoil That I Lash 0 Electronic List 0 Electronic List 0 Electronic List Play List World Outside That And Jewelers In The Least Two Dot Size Page Will Check List Dot Festivals List two daughters will be at least not at least one so that data side plus similarly it will do males will hide from the list play list on based of five elements and after that will also on is half of wild life India and like one of the Amazed with the time element in its earliest size invalid discuss e-mail se contest will do for ne which e-mail se contest will do for ne which e-mail se contest will do for ne which important elements of two boys and elements from delhi to that happy next z plus 2 directions india and will return list samridhi implementation former subscribe element from wild Life Is The Chief In More Calling Subscribe That And See Its Passing Dedicated Answers Flat Submit Record The City Has Accepted So What Is The Time Complexity Of Dissolution So Lets Say Electronic Bulb Screen Saver Mode On Is The President Times The Time To Time Complexity Of Total subscribe to that similarly space complexities also fine that Bigg Boss this is a are using also I like it is a sorry for treating them I quit Saudi cigarettes teams were that using to states first of all will guide you all the child into This text by Calling Labs will always love you to my channel subscribe and they will fix element from drought and flood water values ​​where drawn from drought and flood water values ​​where drawn from drought and flood water values ​​where drawn in to-do list appointed electronic for the element from subscribe and subscribe the Channel and tap on the subscribe thanks for watching this Light a
All Elements in Two Binary Search Trees
number-of-visible-people-in-a-queue
Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_. **Example 1:** **Input:** root1 = \[2,1,4\], root2 = \[1,0,3\] **Output:** \[0,1,1,2,3,4\] **Example 2:** **Input:** root1 = \[1,null,8\], root2 = \[8,1\] **Output:** \[1,1,8,8\] **Constraints:** * The number of nodes in each tree is in the range `[0, 5000]`. * `-105 <= Node.val <= 105`
How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start. Keep popping from the stack the elements in sorted order until a value larger than arr[i] is found, these are the ones that person i can see.
Array,Stack,Monotonic Stack
Hard
1909,2227
1,981
Hello friends, in today's video we are going to discuss about delete list, question number three of 225, minimum tax, difference between target and suji, is the language problem, what is the problem of labs, what can you do, you have one element out of every two, you have to do CR. And you have to take a committee of all of them and together you target them - that is to tell you the updated answer, - that is to tell you the updated answer, - that is to tell you the updated answer, what comes at minimum, to give minimum distance, what you can do, from every summer, you have to use one green chilli, it is serious. And at that time, you can definitely subscribe by doing , , , you have the option here, either, what can you do, if you use one of the two nets, then if you do all your rover missions, then you will get bread from romance. What are the options for you to do, either you can get the certificate by taking flowers, then set your floor here, you can get it by taking real number three marks and salt, you can do it from excessive consumption to active chocolate syrup. Guys can see then we are okay here too so this products is going to be Ankita one plus 7 inch how much and 1234 you school 3330 - subscribe now school subscribe to but 8 - 8 - 8 - 3139 settings duty you will have pair armstrong if you have You do not need to check that this can make your dry ginger, but if we talk about the method, then I will come to you personally and if you go there and buy it for ₹ 10, then you can prank him with water for as long as you want. If it is a buy it for ₹ 10, then you can prank him with water for as long as you want. If it is a buy it for ₹ 10, then you can prank him with water for as long as you want. If it is a quarter of an inch, how much will it cost from this side? 3 - By subscribing, do not forget to subscribe to School and Gas and if you subscribe, then you subscribe, secondly, if you are trained here, then you will learn about something in chapter 789. In the channel, you have to repeat for free what is your use, if you have any problem, if you submit all the western tips in a lovely question, then what is your time complexity going to be and to the power and how many explanation complexities you have. If the work doesn't work then what will we do? Here we will have to put a DP. Let's see how we do it. We will leave Abu Zuhari. We will break his duty. The best decision is that he got his room, which means that he is real and in the column, you should have read his modern volume. Okay, you test your Aadhaar number to see that it is zero from time to time. This Raju 2008, start doing 0.5 inches from time to time. If I will start doing 0.5 inches from time to time. If I will start doing 0.5 inches from time to time. If I will kill you, I will train you. You will do cash withdrawal from shampoo to electronics along with your job. Custom what is going to happen part plus matrices RJ please it will keep its first element Tamil Nadu Yagya then definitely everything will be fine on Play Store I will be updated with it at the life time of the members of the districts rally and whenever you now reached the last If you become belligerent then you will check the return of Superman on this target. If you have selected here and want to use it in your phone, then you have done something here, then you understand that it is the best. If you reach below this, then your Know this minute what the rule number will be, if it is equal, then you update it from here, the difference here, how much will be returned, the third camera setting day is declared, so you returned the updates and the same thing happened and the same problem again and again. Do not repeat in which the audio system and if it is behind the previous one then we will return you the videos that what will happen due to which you will not have to change your taste now and whatever update you want to do with the power and what happened after the previous 500 600 By doing this, we compete on how to know that whatever number of winning numbers are followed in Profitable, when all the maximum is the same thing, next time if it happens again, then you have made the first hit of that, then there will be more contact and contest. Apart from this, by dividing it into duplicate developed, from here, what happened to the meeting which is received in medium form, along with which you said that I am present, I have taken my Ajit element, you blacklist his roll number. Gone like this, every west difficult crore of your time, like once you have taken Schezwan, shatter one by taking the photo and making any judgment of all the animals of your heart and at the same time you are seeing this, the way the answer is going on this. There is an answer option of 'Submit' and you will see answer option of 'Submit' and you will see answer option of 'Submit' and you will see that you are 'Accept Pregnant'. I hope that after getting the that you are 'Accept Pregnant'. I hope that after getting the that you are 'Accept Pregnant'. I hope that after getting the explanation and understanding yourself that apart from this, if you do not want the code, then you can ask in the comment section if you want any other code apart from this. If you want to take a particular topic and understand how to give good gifts, then you must tell in the comment box and if you got it in this way, then yours is very light and also like the channel and subscribe, this will keep you motivated. Thank you friends, thank you.
Minimize the Difference Between Target and Chosen Elements
maximum-transaction-each-day
You are given an `m x n` integer matrix `mat` and an integer `target`. Choose one integer from **each row** in the matrix such that the **absolute difference** between `target` and the **sum** of the chosen elements is **minimized**. Return _the **minimum absolute difference**_. The **absolute difference** between two numbers `a` and `b` is the absolute value of `a - b`. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], target = 13 **Output:** 0 **Explanation:** One possible choice is to: - Choose 1 from the first row. - Choose 5 from the second row. - Choose 7 from the third row. The sum of the chosen elements is 13, which equals the target, so the absolute difference is 0. **Example 2:** **Input:** mat = \[\[1\],\[2\],\[3\]\], target = 100 **Output:** 94 **Explanation:** The best possible choice is to: - Choose 1 from the first row. - Choose 2 from the second row. - Choose 3 from the third row. The sum of the chosen elements is 6, and the absolute difference is 94. **Example 3:** **Input:** mat = \[\[1,2,9,8,7\]\], target = 6 **Output:** 1 **Explanation:** The best choice is to choose 7 from the first row. The absolute difference is 1. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 70` * `1 <= mat[i][j] <= 70` * `1 <= target <= 800`
null
Database
Medium
null
1,706
hey there flow coders welcome back to another episode on COD master sequest in today's episode we are dealing with a captivating physic based puzzle in a 2° captivating physic based puzzle in a 2° captivating physic based puzzle in a 2° so without any further delay let's find out the problem statement and Le code where will the ball fall you have a 2d grid of size M rows and N column representing a box and you have N Balls uh and the Box is open and on the top and bottom sides so each cell in the box has a diagonal board sping two corner of the cell that can redirect a ball to the right or to the left we have two kind of cell in this grid right a board that redirect the ball um to the right spans the top left corner to the bottom right corner and is represented in the grid as one and a board that redirect the ball uh to the left spand the top right corner to the bottom left corner and is represented in the grid as minus one and we drop one ball at the top of each column of the box and each ball can get stuck in the box or fall out of the bom a ball gets stuck if it hits a v-shaped a ball gets stuck if it hits a v-shaped a ball gets stuck if it hits a v-shaped um you know pattern between two board or if a board redirect the ball into either wall of the box and at the end we should return an arrow answer of size n uh where answer R is the column that the ball fall out uh of at the bottom after dropping the ball from the column at index I um or minus one if the ball get stuck in the box so if you look at the example number one if we receive um you know a grid like this one and if we drop one ball from each column you know for B1 we will um you know get a stuck in the Box because we have a vshape pattern here same thing for B4 the B4 will be stuck here in this vshape pattern and for B2 and B3 we will get a stck in this vshape pattern right but for b0 at the end of the move we will um you know it will fall out from column number one right so for this example we should return this array uh for b0 it will drop out from column number one so we should return minus one actually one for B zero but for other um you know for other balls since the balls will get stuck in the grid we should return minus one so this would be the return value you um you know for other BS now to solve this question let's get back to the visual studio code and try to solve it to solve this question let me mention a few number of observation let's come back to the browser and check this example we have two kind of cell in this screen right left diagonal and right diagonal cells a right diagonal cell would be same something like this and we are representing these cells in the grid with one and left diagonal cell would be something like this one row zero and column 4 and we are representing this kind of cell in the grid with minus one to solve this question we need to have two observation what is the U the position of the ball after one move in this grid and what is the U condition to get stuck in a v-shaped pattern so let's get stuck in a v-shaped pattern so let's get stuck in a v-shaped pattern so let's get started with B1 if we started with B1 from row zero and column one since we are facing with a right diagonal cell we would move to the right and for B4 we would Mo move to the uh left uh because we are facing with a u left diagonal cell and since we are representing this um this kind of cell with one and this kind of cell with minus one uh to calculate the position of the ball after one move it's good enough to uh calculate the column number by increasing um the value of the previous uh column with the value of this cell in the grid right and U to find out what is the condition to get St in a vshape pattern if you look at here for B3 if we start from row zero and column 3 we would move to the left because we face with the left um diagonal cell and the value of this um this cell in the grid is not equal to the previous one right so the condition to get a stuck um inside the vshape pattern is that um the next position of the ball in the grid uh have a value different from what we have in the previous uh you know position so this is the condition to get stuck in the vshape pattern now that we have this observation let's come back to the visual studio code and try to solve this problem same as always and as a first sh let's define the function signature here so let's say fun find ball then input for this function which is an a grid an array of integer a 2d array of integer actually and at end we are going to return an array of integer and to sort the return value for this function let me Define a variable here result area of integer and it's empty by default and at the end we are going to return this result right so in the body we need to define the movement logic uh and for this purpose to implement the movement logic I want to define a helper function that will receive the coordination of above and calculate the movement for a so let me say find ball drop column it's going to receive the coordination of a ball in this grid so let's call row column integer and for sure we need to have the grid as well so and at the end of this function we are going to return uh the position of the uh the ball right so to find out whether uh this ball is already dropped out from the bottom of the grid let me say if row is equal to grid. count then this means that we follow out from the bottom of the grid and we need to return uh column as a result now we need to find out the column after one move and based on our observation we can say next column is going to be column plus G for row and column right so this would be the position of the ball after one move regarding the column now it's we need to check whether we get out of the grid system from the Wes or we suck in a vshape pattern so for this purpose if next call is less than Z zero or next call is greater than grid z. count minus one this means that we are out of the grid from the right hand side or grid for row and column is not equal to grid for row and next column right based on our observation in this case we should return minus one based on the question description otherwise we should find out with the recursive call to the same function right so let's say return find ball drop column for row + one and find ball drop column for row + one and find ball drop column for row + one and next column and we should pass the grid as well now let's come back to the movement Logic for I and zero to um let's say grid z. count let's say result that appen find drop ball column or find ball drop column actually for row number zero column number I and gries great right and this should be the correct implementation but to make sure about it let's come back to the browser find out the input here where's the input yeah there we go here and now let's come back to theual Studio code paste it just right here maybe I can copy this part let's say let grid equal to this one and print find ball for this grid right should be a correct call to our function okay there we go let's see whether it's working uh sa problem let's see we expect to receive one minus one and minus one so it seems we have a correct solution as the last job let's submit our solution to Le code uh change the browser and paste our code just right here and hit the submit button there we go here's the solution for this question thank you everyone
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
141
we're looking at leak code number 141 linked list cycle this is a classic linked list problem very classic pattern definitely one to know definitely shows up all the time highly recommend to be familiar with this pattern also once you know this pattern you can solve many other com questions that come up with linked lists and even other types of data structures that don't involve linked lists but follow the same principles so what are we doing here we are based we're going to be given a linked list and we want to detect is there a cycle in this linked list and if it is we return true and if there's not we return false so here we have 3 2 0 minus 4 and we can see that if we go from three to two three to zero to minus four and then this goes back to two and we can see that there's a cycle here we return true this is also going to return true because we have a cycle here this two pointer points back to the one and then here we have a one it doesn't point to anything else so it's false and so let's think about this there's a couple different ways to approach this let's go ahead and move over to the conceptual room we have 3 2 0 -4 so here we have a list 2 0 -4 so here we have a list 2 0 -4 so here we have a list with 3 2 0 -4 let me write this again and just give a little more space so we have a list with three two zero minus four okay and now this four points back to this two and that's where our cycle is and so what's a brute force way we could do this well what we could do is we could say if there's a cycle then what we could say the number will have already been seen right so let's say we had pushed all these numbers into an array and we had 3 2 0 minus 4 we could even just put all these nodes in that array and then when we come back here to 2 we can say well this has already been seen it's already in there and if it's already in there then we have a cycle that is one way to do it the only issue with that is we're going to create a bunch of extra space and it's going to also be extra time because if we have an array which is a contiguous structure every time we want to check if something's in there we're going to have to iterate over that entire array worst case so immediately we're looking at linear space and we're looking at quadratic time which is not great so what's another way we could do this and that is using the method called using uh two pointers okay and this is a very classic pattern definitely one that you want to know and the idea is you're going to have two pointers you're going to have a fast pointer and you're going to have a slow pointer and every time you iterate the fast is going to move two steps and the slow is going to move one step okay so let's just kind of step through this on our first iteration the fast will move one two steps the slow will move one step fast will move one and two steps it'll come back here to number two and slow will also move over here to zero and then fast will again move two steps back to the minus four and slow will move here to the minus four and when we get here if these two nodes are equal then we have a cycle and if they're unequal then there's not a cycle because they'll never actually cross each other okay and so that's it that's how you detect cycles in linked list it's very simple you just want to use two pointers one fast and one slow and if any time during that traversal as they're going through the list two nodes intersect you both those pointers point to the same node then we have a cycle that is that's where that cycle is okay so let's go ahead and jump into the code okay so all we want to do here is we just go ahead and get a fast pointer and go ahead and set that to the head and we get a slow pointer and set that to the head okay and now we just want to do while fast and fast dot next okay and now what we're going to do is uh we're just going to update fast and slow so fast is going to go fast dot next and slow is going to equal slow dot next and if fast equals slow return true else we'll break out of this loop we'll get to the end of the this the linked list and we'll go ahead and return false let's go ahead and run that and yeah we're good okay some things to think about here now why fast dot next right this line right over here why do we have to do that okay let's go ahead and jump back to the whiteboard here so we need to make sure that we get to the end of the list and that every everything that we're iterating over we don't have a null value on the next okay so let's say we have here we have 1 2 3 4 5 and 6 right and this is going to point to null and there's no cycle in this right and so now we're going to have a fast and a slow and so let's just kind of walk through this so here fast is going to increment 2 and slow is going to increment 1. we're going to check does fat is fast true and is fast dot next true okay if they are go ahead and increment fast twice to the 5 place and increment slow ones now we check is fast true and is fast dot next true if it is then this fast can increment to this null that's where it's going to be and then this slow we'll go ahead and increment over here and then fast is not true and we can go ahead and exit out of the loop okay and so the reason we want to do fastfast.next is that fastfast.next is that fastfast.next is that when we get to the next iteration we're not calling fast dot next on a null value that's the main point of it because if we do it the other way we're going to be calling fast dot next on null which will throw an error and so that's why we are on this line over here we're using while fast and fast dot next okay so just something important to remember when you're um doing using two pointers this is a pattern that you want to have memorized you want to just know this uh it's very common in a lot of linked list questions that you're gonna have to traverse find a cycle find the start of the cycle it just comes up all the time so this particular pattern it's just you know it's probably good to just have it memorized that way when it comes up you don't have to think about it too much okay that is linked list 141 or that is sleep code 141 linked list cycle hope you enjoyed it and i will see you on the next one
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
144
hey everyone welcome back and let's write some more neat code today so today let's solve the problem binary tree pre-order traversal we're given the root pre-order traversal we're given the root pre-order traversal we're given the root of a binary tree and we want to return the pre-order traversal of all of its the pre-order traversal of all of its the pre-order traversal of all of its values so this is a really simple problem to solve if you're doing it recursively it's kind of one of the first algorithms that you learn when it comes to Binary trees but solving this problem iteratively is a bit more difficult and it's definitely useful to know especially for interviews so that's what we're going to be focusing on in this video let's say we're given a binary tree like this first of all what is the pre-order traversal well we're is the pre-order traversal well we're is the pre-order traversal well we're going to start at the root and pre-order going to start at the root and pre-order going to start at the root and pre-order basically means that we're going to process this node AKA in this case add it to the array that we're trying to build we're going to do that first and then we're going to recursively run pre-order traversal on the left subtree pre-order traversal on the left subtree pre-order traversal on the left subtree and then after that run pre-order and then after that run pre-order and then after that run pre-order traversal on the right subtree so our output would look like this we visited this then we'd go left we would visit this so add 2 to the output array we'd try to go left at this point but we can't there's nothing there and then we would recursively pop back up to our parent node and then try to go right again we can't there's nothing there so then from here we would pop back up to this parent node and then from here we're basically done running pre-order we're basically done running pre-order we're basically done running pre-order traversal so then we would pop back up to the parent here and from here we know that we're done with the left side of the tree and since it's pre-order we've the tree and since it's pre-order we've the tree and since it's pre-order we've already done this node so then we'd recursively run pre-order traversal here recursively run pre-order traversal here recursively run pre-order traversal here so we'd get to three we'd add 3 to the output then we'd go left add 4 to the output try to go left can't do that try to go right can't do that pop back up here then try to go right we'd add 5 to the out output and then at this point we can't go left can't go right we'd pop back up and then we'd say well we're done here because we already went to both sides then pop back up here and we're done here because we already did the left and right subtree so then we'd basically be done so how do we take this solution and then emulate it iteratively well the main thing that we need to do is we'll have a single pointer that will tell us like what the current node we're at is that's the easy part but the hard part is after we go left or after we go right how do we go back up because there's not a pointer connecting a child node to its parent so we kind of have to do that ourselves and the easiest way to do it is with a stack data structure and actually recursively that's what the problem is doing well that's what our function recursively is doing it's not explicitly creating a stack but there is an implicit stack aka the recursive call stack so we're basically going to emulate this pretty similarly so I'm going to go ahead and draw that out for you so this is our stack we're also going to have our result that's also going to be an array so now we start at the root we're running pre-order we're going to take running pre-order we're going to take running pre-order we're going to take this value and append it to the result it's 1. now we want to go left but we know that after we're done with this left subtree we're going to need to go back up to the root so what should we do should we take this node and add it to the stack let's just draw it like a node one and add it to the stack so that we can pop back up to it that's definitely a valid way to do this but what I'm going to do is just skip that all together I'm just going to take actually the right child of one and append that to the side because this is pre-order We to the side because this is pre-order We to the side because this is pre-order We Know by the time we pop back up here we've already added this to the result there's no need to visit this again why not just skip that step altogether and just add Its Right child to the stack because we know by the time we're done with this left subtree all we want to do is do the right subtree next not the root so that's what I'm going to do here before we go left let's append three the right child not the value we're gonna append the node because we want the pointers as well I'm just writing out the value to make it simple I guess I can put a circle around it if it makes it more obvious but then we're going to be at the left child over here so then add 2 to the result now from here we're going to do the same thing even though we don't know that the left child is null or that the right child is null we're still going to follow the same algorithm because it doesn't hurt us it still works in this case so what we're going to do here is before we go to the left child we're going to add the right child to the stack even though it's null so I'm just going to draw an N to indicate that it's null and then we're going to go left we're going to be here our pointer is going to be at a null value there's not thing for us to do by the time we get to a null value we know we can't go any further with pre-order we can't go any further with pre-order we can't go any further with pre-order we're trying to go as far left as we possibly can until we reach null and when we reach null that's the signal that we need to pop back up in this case that's the signal that we need to pop from our stack so I'm going to do exactly that I'm going to pop the last value from the stack which is null so now our pointer is going to again be at null so when our pointer is at null we just pop from the stack so once again I'm going to pop now three from the stack so that means now our current pointer is here at three so it's a non-null node so we're going to add the non-null node so we're going to add the non-null node so we're going to add the value 3 to the result now we're going to go left but before we go left make sure to add the right child to the stack so I'm going to add 5 to the stack and then we're going to be at four we're going to add 4 to the result we're going to try to go less but before we do that we're going to add null to the stack so I'm going to add a null value here we're kind of running out of space but you probably get the idea at this point now our current pointer is at null so we're going to pop from the stack popping null so now our current pointer is again at null so we're going to pop from the stack one more time popping five so now our current pointer is at five we're going to add five to the result and we're going to try to go left adding null to the stack and you probably get the idea at this point we're going to add null to the stack we're going to go here to the left we're going to be at null we're going to end up popping that null from the stack and then at this point our current pointer is going to be at null and our stack is going to be empty so if we try to pop from the stack we can't pop anything that's the signal that we're done when our current pointer is null and the stack is empty so that's basically the algorithm you can see we're pretty much still visiting each node twice we are kind of visiting some null nodes but that's not going to change the over overall time complexity this is still going to be Big O of n time complexity we visit each node once and we do have extra memory for the stack which is basically going to be the height of the binary tree which in the worst case could be Big O of n or if it's a balanced binary tree it could be log n so now let's code this up so what I'm going to do first is initialize our current pointer and initialize our stack the current pointer is initially just going to be pointing at the root pretty simple and the stack is going to initially be an empty array we're also going to have our result which is also initially going to be an empty array and as we talked about we're going to iterate until our current pointer is non-null or our stack is non-null so non-null or our stack is non-null so non-null or our stack is non-null so then we have two choices either our current node is null or it's non-null if current node is null or it's non-null if current node is null or it's non-null if it's non-null then that's kind of the it's non-null then that's kind of the it's non-null then that's kind of the case where we're going to take the value and append it to the results so current dot value append it to the result we also then want to move left we want to say current is going to be equal to current dot left but before we do this we know we have to save the right child on the stack because we need to get back to it so here I'm going to say stack dot append current dot right the right node actually not the value but this could be null and that's not a problem as I kind of showed in the drawing explanation but the other case is if our current node yes is null then what do we want to do well first we want to pop from the stack and then assign that to be current and then what would we want to do well we would basically want to check again is that node non-null if it isn't then we're going to non-null if it isn't then we're going to non-null if it isn't then we're going to move left and add it to the result and also add Its Right child to the stack so basically we don't need to take this code and copy and paste it down here because this Loop is going to run again as long as this node is non or our stack is non-empty that means there's still is non-empty that means there's still is non-empty that means there's still nodes to visit so we don't need to copy and paste this we know the next iteration of the loop is going to handle that for us but if the what we popped is null then we're just gonna have to pop again nothing wrong with that so after all that's done we're going to go ahead and return our result so now let's run this to make sure that it works and as you can see yes it does it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a ton of free resources neatco.io it has a ton of free resources neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Binary Tree Preorder Traversal
binary-tree-preorder-traversal
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,255,775
146
hello friends I hope you and all your near and dear ones are safe and Hildy these are difficult and unprecedented times and among all the talks discussions and panic around Cove in nineteen I think the best I can do for you right now is to create a peaceful state of mind through distraction via education so over the next eight to ten minutes let's zero in on another lead code problem called Ilario cash this is a frequently asked question by Amazon Google Facebook Microsoft and quite a few other companies I'm sure most of you who are watching this video would be familiar with how elodie cash works but let's quickly spend a couple of moments to understand about it so to start with a cash is a small amount of memory it can either be hardware or software component that stores data so that future requests for the data can be processed faster now due to the limited size of the cache when this memory is fully utilized we need efficient eviction techniques so as to accommodate new data one such cache eviction technique is LRU which stands for least recently used as the name suggests in this policy the least recently used items are evicted from the cache when the cache is fully let's go through the problem description design and implement a data structure for least recently used cache it should support the following operations get input gate key will return the value of the key exists in the cache otherwise it will return -1 what key otherwise it will return -1 what key otherwise it will return -1 what key value will set or insert the value of the key is already not present when the cache has reached its maximum capacity it should invalidate the least recently used item before inserting a new item now let's go through this example so we are - with the given capacity of 2 and are - with the given capacity of 2 and are - with the given capacity of 2 and then we have a set of instructions let's you know what try to understand it more pictorially our first instruction as cash got put 1 comma 1 so since the cache is empty we can just insert this element next we do a cache got put 2 comma 2 since there is still room for one item in the cache we can simply insert it and update the position so now 2 comma 2 is the most recently used and 1 comma 1 is the least recently used next we try to fetch one from the cache so we do a cache not get one now we return the value 1 and also update the position of 1 comma 1 in the cache since now 1 comma 1 is most recently used so 2 comma 2 now becomes the least recently used item next we get 3 comma 3 now we will have to edit 2 since the cache is already at its capacity and 2 comma 2 is the least recently used item will evict 2 comma 2 and also update the position of 3 comma 3 next we do a cash market - since the 3 next we do a cash market - since the 3 next we do a cash market - since the item is not present in the cache we simply return a minus 1 then we have to insert the element 4 again we find that the cache is at its full capacity so we'll have to remove an item which is least recently used in this case it is 1 comma 1 so we remove it and also update the position so that 4 comma 4 is the most recently used and 3 comma 3 is the least recently used next we do a cache dot get 1 and return -1 since item is not found next return -1 since item is not found next return -1 since item is not found next we do a cache not get 3 again if you see we have updated the position of 3 comma 3 now since 3 comma 3 is the most recently used and foe come of or becomes the least recently used here next we do a cache target 4 so again we'll have to update the position of 4 comma 4 and make it the most recently used and similarly make 3 comma 3 the least recently used and return the item 4 comma 4 so let's think about our data structured first before moving on to the code so since we have seen that we have key value pairs in the cache we'll need some sort of a hash map which can retrieve the values pretty quickly given a key but the only problem with the hash map is it is unordered but here we need to form some sort of ordering so that we can always get the least recently used item from the cache in constant time so for that we can use a linked hash map which will solve both the purpose of a hash map and a list which will give us ordered elements so let's try to write the code now so we'll have to define two variables when that holds the capacity of the cache so it is in the capacity next we'll define a linked hash map and it will hold integer command issued since both the key and values are integers now let's initialize the constructor so this dot capacity is equal to capacity and we'll initialize the map to a new length hash map here and we provide capacity which will determine the size of the harsh map now let's try to implement the gate key function so as we have seen if the key already exists in them hash map so it is map got contains key then what all we have to do is first get the object from the cache update its order in the cache and then return the value so for that we can write int value is equal to map dot gate key will do I put key comma value this will update the position of the item in the cache and finally once this is done we just may put return this value now let's say if the item is not found in the cache then we just need to return a minus 1 let's try to implement the put function so if the item is already present in the map we'll have to update the position so as to make it the most recently used so first we will check if map dot contains then let's remove this key from the map and again will be inserted so as to update the position else if the map has already reached its capacity then we'll write a check for that so if map dot size is equal to capacity then we will just iterate over the map and remove the least recently used item so how do we do that let's define an iterator of integers SMAP not is it not iterator now if you haven't used the iterator before I provided a link in the description you can read more about it so whenever we have to remove an item from the iterator we need to call iterator dot next and only after that we can call iterators remove method so we write IT dot next then we call I T dot remove so this will remove the current element which is also the least frequently used element once we are all done with this the only thing remaining right now is to actually insert the element into the linked hash map so when I eat mom dot put e comma value and we are done let's try to run it works let's submit it great so it's accepted hope you continue watching my videos please subscribe to the channel like this video and leave your feedback thank you
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
79
welcome back to algojs today's question is leak code79 word search so given an m by n grid of characters board and a string word return true if word exists in the grid the word can 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 so in example one we have this board we are looking for the word abc ced as you can see this can be found within the board so we need to return true in the second example we have c as the word which is in the board and lastly in example three we have the word abcb which is not in the board so we return false so with this question uh we are going to be utilizing a dfs recursive solution because we need to check all possible solutions within this board to find if it potentially holds the word so how would we do that well we'd start off at the first position we'd loop through this entire board and we checked to see whether we have this letter at the position we're on if we do then we can start a search so we can start the dfs recursive call and check the next letter in word and also traverse through this board so we need to check all positions so we need to go right down left and up and this would be a good idea to suggest that we need to have some kind of inbound function or just an if statement that says if columns is less than zero or rows is greater than board dot length or columns is greater than board zero dot length then it's out of bounds right so this would be too far over this way row is less than zero will be up here column less than zero will be over here and rho is greater than board.length and rho is greater than board.length and rho is greater than board.length will be too far down this way so we've checked all directions to see if it's inbound so moving from a we can't go here because it's out of bound we can move either to s or b if we move to s does not equal the next letter within the word that we're looking for so we can't go down that path we have b here so we can start the dfs function on this and then we repeat the process so we check all our potential solutions check whether they're inbound so here we have an issue right because we're going to be going back to the previous value which we've already checked so this has been checked we don't need to go back to it so in this case we could use something like a set to store all the letters we visited or we could simply change this to a value like a hash okay so we exclude it from the board now by adding this hash so there's no point in going back that way so we can't go this way we don't go this way because the next value in the word is not equal to f so we go to c which is the next value b has now been seen okay so we can update b with hash we do the same with c we check all directions we move to the next position which is this position we check all positions we move to e repeat the process and we move to d now at d so we've checked now at d so we've reached the end of word so the position we're on say the index which we could keep track of is equal to word dot length minus one and if that is the case we can return true so we'll return true at the stack all the way up until we get back to the original position so true will be returned from here and lastly here so this will hop out of the dfs recursive call stack we'll have true as our answer and then we can just return that boolean so time complexity is o we have to traverse the board so we're using a recursive call stack so that's going to be of n operations the difficult part is in the first iteration we can go in four different directions right but moving along we can only choose three other possible directions right so we've got these three we can't go back to the previous one because we've already looked at that so we have three potential solutions so that would be 3 to the power of l where l is the length of this word so it is going to be of exponential time complexity so to begin with we can start off by creating the loop through the board and check to see whether we have the initial letter that's in word so that i equals zero r is less than board dot length r plus so we're looking through the rows here and then we're going to loop through the columns as well so c is less than board zero dot length and if board at rc is equal to word zero then run this dfs function which we're going to create and pass in the row the column and 0 for the index now if this returns true then we can return true from this else we need to return false okay so now we can create the dfs function so dfs takes in row column and index if word dot length is equal to i we can return true because we've reached the end of the word and we found all of the letters within the board we need to carry out the inbound check so if rho is greater than or equal to or dot length all rows less than zero or column is greater than or equal to board zero dot length and finally we need to check if the board at r c does not equal word i so when we start recursing through we're going to check all four positions or after the initial we're going to check all three positions and if the letter at the current position in the board does not equal the letter in word then we can return false so before we carry out the recursion we need to set border rc has visited and the way we'll do this is by setting border rc to a hash and now we can carry out the recursion so if dfs are plus one c i plus one so we need to increment row here and also index or so we need to traverse all four directions so r minus one c plus one c minus one and if one of these positions returns true then we can return true finally within this dfs function we need to reset the border rc to equal word i and that's it for this code let's give it run submit it and there you have it
Word Search
word-search
Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_. The word can 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. **Example 1:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED " **Output:** true **Example 2:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE " **Output:** true **Example 3:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB " **Output:** false **Constraints:** * `m == board.length` * `n = board[i].length` * `1 <= m, n <= 6` * `1 <= word.length <= 15` * `board` and `word` consists of only lowercase and uppercase English letters. **Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
null
Array,Backtracking,Matrix
Medium
212
784
hey everybody this is larry this is day 16 of the february code daily challenge uh hit the like button hit the subscribe button join me on discord let me know what you think about today's prom ladder case permutation so i usually solve these live or attempt to and i go for my thought process but i'm and i just woke up so i may be a little bit slow so feel free to fast forward skip ahead whatever you need so today's problem is ladder case permutation so given s we can transform every letter individually or lowercase to create another string um okay so yeah so i think the thing you need to do for this one is um are been given okay so you so one thing that i notice in the test cases is that they don't give you the upper case characters but so if they give it to you have to fix that case but in any case what you need for this problem is something called a power set put it here for now uh and the way you use it is just that for every uh every very lead letter um you just choose whether it's uppercase or lowercase and that's pretty much it um so the way that i often do it is that i try to avoid recursion because i don't know i think it's just a force of habit because python is a little bit slow uh but so i do you know because we just took take advantage of power set we can use the bit mask way of doing power set but today because of that i want to try something new and then i'll just do it recursively um and that should be good and because we can return the up in any order uh though i think try to store it in uh in alphabet order right in lexographic order because why not so here so let's get started this is just um brute force and there's no better way to do it because you have to ch because you have to output every possibility that means that you can only generate them for proof first because that's the lower bandwidth of your um complexity right so because of that you know because it is good for us i don't worry about um i don't worry about complexity as much um i mean i worry about it but i know that if i do brute force in an intelligent enough way it's not going to be you know too slow um and also n is 12 right so 2 to the 12 times 12 it's going to be fast enough so yeah so let's kind of go do that let's see how do i so depending on how you want to write the recursion there are different ways and i think this is a good practice for um for like dynamic programming and stuff like that where you know maybe one way to do it is just take the pre uh the suffix of s right so that you know maybe you can have current string or something like that and then here in the body of the function you would write something like if the first character of string is you know if this is alphabet or something like that right um but and a good practice in general is to convert this into something that's takes less space and something that is you know because this is this s string isn't going to change and we don't want to change it um and actually we have to put another one for existing but what i'm saying is that you could use the index instead um but you also still need the ongoing uh string and here we're going to use the um let's just say current um and we want the current to be in a way cone is an array and the reason why we want it to be array is so that it doesn't i think it's slightly more efficient um but given that s as you go to 12 maybe it doesn't matter that much in the sense that you know in a lot of languages if you do if you can candidate 10 times you create 10 strings for example um so i some so i try to avoid that um but maybe for now it doesn't matter so let's just keep it a string and then we need to optimize for optimize but i want to keep it you know keep it uh what's it going keep it stupid symbol stupid something like that so just try to do it as much as i can um okay so if that set n is equal to length of s i always do this so that i don't have to write as much and also because it's a function in python so uh if you do it a billion times it actually does make a difference but if index is equal to n then we just return because we don't have any characters left in the string otherwise we um okay so if also i want just to keep it off uh in lexographic order we can lower this to lower something like that is it too low or low to lower case i always forget the python does have this function so yeah okay so it doesn't complain so that's a good sign and then if s of index i think this call is alpha maybe i'm well let's return let me run it again i don't know so we will generate and then return answer okay so it does okay i forget the name of these functions i would have to google it that's why i wanted just to make sure yeah uh if this is alpha then we generate index plus one current plus sub index uh is uh lower we also want to generate the uh what's required the uppercase version and in theory because we already did a lower this should already be lowered but i just want to keep it this way for symmetry so that i don't uh because sometimes you outsmart yourself and you get confused when you have to go debugging um and for now i'm going to keep it like this so that you know these two lines and when i say symmetry i mean that these two lines should look very similar and the same um and i keep it in there as long as i can pretty much um otherwise this is a number so let me just do this but i haven't yeah there you go oh i forgot to actually put in the array which is what we do at the very end so yeah answer that append uh and that should be good uh i think we can test a couple more but i am confident ish oh and i think we want to add one more where the input is in uppercase because that's not one of the inputs as we talked about one two three four five and zero okay fine cool um this looks good it feels good so let's give it a submit again this is going to be you know before so it's n times n factorial which is um you know for n is equal to 12 is fast enough in terms of space is also 12 factorial or n factorial or at 12 factorial which is fast enough because that's the size of the output and you can really do better right um because yeah so time is equal to n times n factorial all of that why is it end times yeah and the n comes from the fact that um well the n factorial comes from the fact that when we wait no i'm thinking of something else sorry i meant two to the end wow i am sorry i just woke up and i got a little bit confused about because i was talking about brute force and i read permutation and i think i this is a way and when you think but when you see the word permutation you always think about like n factorial as one of the things and i think i just got a little bit um i think i got a little bit mixed up sorry about that i don't mean to confuse anyone i really don't but it's two to the end because um you can imagine a word where there's no numbers then we branch out twice for every um every character and then at the very end we have to append it to the answer string which is the number of characters like this takes all of n times if you want to call it that because uh because copying this string into because the string is of n length and therefore copying it into answer will be all of n times right um and then the space is just over two to the n because yeah because you that's the size of the output you can't do any better um because literally you have to return that many items right uh and also i guess you want to be more precise given that now we do it's actually n times 2 to the n if you want to call it that as well because um i guess yeah maybe that's a better position because this two to the n strings each string is length n so it's n times 2 to the n i just want to be really clear because sometimes i would say um i definitely mix these up sometimes um where i'm inconsistent from time to time but that's my bad uh thanks for commenters for catching me when i do that so um so now i'm trying to be a little bit better so you know i'm learning a little bit as well okay but yeah um that's all i have this is you know i'm trying to keep uh i think this code is about you know without some comments and spaces about like 15 lines of code and i think you know this is as simple as i could want it to be so yeah i think one time i don't know if it's this particular problem but it was a similar problem during a contest where i forgot about the lowercase um i forgot about the uppercase and i changed it to here and it doesn't change the assign to submit it again for another five minute penalty that was kind of sad uh i do remember that though um it was a similar as i did this problem with similar problem but yeah uh that's all i have for this farm though let me know what you think hit the like button hit the subscriber and drum and discord and but if you don't that's fine but you know you take care of others if you can stay good stay well um stay healthy and to good mental health i'll see you next time bye
Letter Case Permutation
insert-into-a-binary-search-tree
Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string. Return _a list of all possible strings we could create_. Return the output in **any order**. **Example 1:** **Input:** s = "a1b2 " **Output:** \[ "a1b2 ", "a1B2 ", "A1b2 ", "A1B2 "\] **Example 2:** **Input:** s = "3z4 " **Output:** \[ "3z4 ", "3Z4 "\] **Constraints:** * `1 <= s.length <= 12` * `s` consists of lowercase English letters, uppercase English letters, and digits.
null
Tree,Binary Search Tree,Binary Tree
Medium
783
1,832
so we need to check whether sentence is pan gram or not this is an easy level problem and we will understand step by step how we can solve this question also uh before moving forward if you haven't subscribed to this channel make sure to subscribe to learn about Pro for regular liquid videos like this the question uh first discussed about the panchrom is the pan grum is basically a sentence of where every letter of the English alphabet appears at least once fine so uh it's like uh it's compulsory that every letter should appear at least one so that's what necessary now uh if we just look carefully this is a sentence given to us fine this is the one you know that the quick brown frogs jumps over the let's talk so this is a sentence and this sentence you will find it true because you'll find every letter of our English alphabet from a till z everyone is there at least once like there's one time we will find it here fine so the sentence like this at least one of the every letters so uh the other case is like lead code if we are given this is the false because it's not uh to that point okay it's not there whether everyone is there or not fine so uh our main target is to find out if uh there's like a uh if related is there at least once right the question for this is like we are given the string sentence containing only in lowercase English letters so everything is lowercase written true if the sentence is a paragraph or other response so is a pretty simple question so you need to check for that now what should your approach to this question the first approach that must come to your mind as a uh array based approach what is that you create an array of size 26 fine and initially you know the array uh default values are zero uh make it an entire and then for each of the characters users do like uh or the character minus um this a okay so whenever you do something like this okay so you do something like this returns your index or a number so how to work say this is the character of that um a sentence how to find out it's like uh B fine so what is happening so B uh minus a so this happens and with that case we will return it uh so B is uh 90 uh 98 okay p is 98 and uh in terms of that a is 97 so you will find one as the answer fine so that's what you will find out of it now uh this is the first thing this uh that it was and that's one big the index of that make it a 26 uh letter uh array and then you find the index out of it and then put the index and uh just keep adding to the particular index like incrementing the index so at the end once the sentence is over you just Traverse through that whole uh array and find out if any character remains 0 there is not a paragram as if the whole array gets over and all characters have some other at least one value so it's a pattern so that's our basic idea you can do now to improve that what you can do you can actually shift this like uh not using array rather use a map or set in that uh you just uh like keep on adding all the valves in the set fine so at the end you just check whether the state size is 26 or not fine so that's a pretty much easy but the exact size is simply return as that so these are like two ways that you can do but there is another way uh which you should learn okay uh these are the ways you uh can come up easily but maybe if the interface is not looking for these are the ways to can you improve it further so what you can do is like use a bit wise uh approach okay like uh in bits use this and that approach will be helpful for us so how uh we'll go ahead with that the first thing we will do is like uh this particular concept that I explained it to here that this will be helpful okay this will use that so what we'll actually do we will uh we keep a like a in type uh okay in type uh screen variable or a variable that will help us to know whether we have seen a particular number or not fine uh fine that will do and then we will continuously uh lab shift our uh value so whatever this uh value we are coming up like uh C minus a this particular for each character we're doing this so whatever this value we are coming up we'll do a left shift of how many times we'll do something like one left shift uh this say this value being uh C1 or something like the CI so we'll continuously do a left shift of this so what will happen say there's uh B like the character is B so it comes a one so the value will ultimately come up to something uh like it will be one zero okay so that's a value we'll be looking for because that's a b uh like if it is B so that n value will be something like one zero fine because that's one shift being moved if it was a so it is being 0 1 okay for C it will be 100 one zero so you can see that like the characters are like uh not at the same place so at the end like at the end of the traversing the whole sentence you should have 26 once okay you should have 26 once 26 times fine that should be there in your uh like after doing that after doing each of the left shift fine now what exactly we are doing at the last we will simply do uh we'll simply check if uh we do a one left shift 26 fine we'll do a one left shift 26 and we'll check whether this one lap shift 26 is equal to this particular value that will come up okay this particular value that will come up it should be 26 once so if this particular Value Plus 1 okay what will happen uh everything is one and when you plus one to it will be like 27 bit will be one and then 26 zeros will be there okay so that will become so we'll take one left ship 26 will again be that exact thing for 27th bit will be one and there is like 26 zeros how why is it so remember when you had to be that is one over here okay when you left shift uh like uh one left shift this B that comes up to be something like this that is uh second bit is one and the first there are like one zeros are there fine that's what it is so how whatever the left shift is like how my baseball laptop it basically means there will be that much zeros at the end fine so this is the idea so it should to be like 26 zeros at the end and also 26 bit characters plus one like all the 26 ones and rate of one like if you add a 1 to it should result in again the same thing so that's the pretty much check we can do so what's the Improvement we come up over here why now firstly when we are using arrays as a example in that case we didn't have like uh we have to Traverse the whole sentence and then we have to Traverse again 26 letters array to find out if there's a Mystic or not so it's like going into like order of n uh in being the length of the array to twice or Thrive like at least twice you are going but like overall order is not changing for the overall time it will take it will change because first you are traversing to the sentence one each of the characters and this and they are then you are traveling through this whole array fine so that's the uh what you need to do there but when you improve to uh say you will find out like you keep adding them all again you Traverse the whole sentence that order of n is there and add it to that you need to find the size of the like calculate the size of the set okay so set size you know you can use directly uh the function but that function also takes an order right it calculates that in internally so uh that is the text step but what is the Improvement you come up over here yeah first of all that traversing to the whole sentence academic actor is same for all approaches but over here you are not using much of the additional space as if you are just doing additional space to store this one uh okay that 26 character uh letters or the same variable it's just an entire variable now using this you can simply find a solution to this but remember there is a small catch in this question the small catch is uh here you are looking for like a 27 bit is one at last and then 26 zeros are there that should be the ultimate result they were looking for returning true right but how is this holds true so this holds true simply because the entire variable wherever you take it is a 32 bit fine so it has 32 bits so that's why we can easily go ahead and uh use it there but say in other programs they gave you something but there isn't like 26 characters of the English alphabet only that there are more characters there they have added some characters so if that is the case you need to check whether it comes up in the 32-bit or not whether it comes up in the 32-bit or not whether it comes up in the 32-bit or not if not we have to go with the set fine now this whole stroke because of that because we have only 26 characters and in that case it is less than or 32 bits so we can easily uh use this bitmus operation to do that so uh quickly let me quickly go ahead and write this code and then show it to you how fast or slow it works uh with our respective file let's quickly go ahead with that and there is come up with a one minute sensation obviously it's a zero medicine solution but at times liquid is there what is madness but it doesn't matter let's look at the solution again um understand it again what we did so first of all as I said we took a interior variable see and this variable we are like doing a character uh by character we are traversing character in our sentence okay and then we are doing this operation like you do uh in C1 is equal to C minus a so as I say whenever you have this C minus a is basically finding out the index of the value okay so let's understand this uh centers so we have this uh take a case like we have this variable ABC well that's only given to us right uh now what's happening exactly is like we've come up with a first so C minus a is like zero fine so that C1 initially becomes zero and then we're doing C is zero itself so scene is zero so C or we're doing all operation of one left shift equals zero so once left shift zero is so this zero because one left shift zero is like one itself okay that is like uh zero then one fine that's happening and then uh we are doing an or operation this thing what is the scene was initially zero like all characters are zero right so we're doing the all operations so after all operation it simply becomes zero one right uh that's what it becomes now uh filter what will happen we'll come up to the next character is B fine next state is B so B is like B minus that a but it happens it simply becomes one okay y because 90 uh 98 minus ninety seven uh that's their uh values okay so 19 minus 97 you will find out to be one then uh you need to do a left shift one so one left shift one is like one zero fine so there's one left shift one so I'm setting additional zero before it because like giving it three bits and then uh we are doing all operation with uh scene so what is seen previously zero one so what if we just do an all operation over here see over if we do an all operation over here x simply becomes 0 1 right that means that simply means we just found this uh characters or we just found this bits uh or the characters are there then what do you come up we come up with uh c over c will find uh the character C is they're fine so then uh this C minus a will give us two so it's two main so one zero why we're left shifting one two bits so that's one zero that is two zero so then how many places where left shifting is like adding to that much zero at the end fine then we are doing all operation with the c so C inverse one zero one uh sorry zero one and we are doing all operation of one zero in fact we're doing this so what comes up as a result so it's constantly one right and further like you may think like what comes up next say father if there's another one like another age another a will be like zero one right so that will be there so we'll do a uh like after two we'll do our operation so it's like zero one so what is the order operation of one and one like two and true is true itself right so that's what if it will result in one step so once you have found this character it will remain one continuous there's no problem with that but if any character so at the end it will be at least it will go ahead with 26 item we need to find the or every letter right so it will go up to 26 seconds so you and then we should be having a number that is 26 times 1 right that's 26 times 1 should be there fine that should be there over here now uh what's going on next is like we just found out say we just found out there's 26 S1 now what if we got this training system one in our scene variable fine in our scene wherever if we add one to it see we just didn't add it here we have to subtracted it on the other side it's just same to just take it make it add over here so what is it what if we add 1 at the end so if we just do some binary addition then you'll find it will become like 27 bit as one and then 26 zeros will end up having fine so this will end up having and then again one left sheet 26 is the same thing if this happens exactly right if this is exactly what we come up to as an answer then it is something we will say okay we found our answer like this is a true but in case there's any weight which is not uh one say there's a bit over here that is 0 then what will happen or subtracting one or addition like adding one to this won't result in like uh or all bits being like this fine it will just add up one over there like after this zero all the updates will be zero and up for before this all episode we want and this bit will also change one after adding one so this will happen right and plus we can say whether it's in uh whether it's an uh particular value like a paragraph or not so I hope this is understandable how you can go ahead with the solution over here so thank you for watching this video uh make if you have any doubts with this make sure to comment them down I'll be happy to help you out in the comments as well and also like this video And subscribe to the channel for regular liquid videos like this thank you for watching this video
Check if the Sentence Is Pangram
minimum-operations-to-make-a-subsequence
A **pangram** is a sentence where every letter of the English alphabet appears at least once. Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._ **Example 1:** **Input:** sentence = "thequickbrownfoxjumpsoverthelazydog " **Output:** true **Explanation:** sentence contains at least one of every letter of the English alphabet. **Example 2:** **Input:** sentence = "leetcode " **Output:** false **Constraints:** * `1 <= sentence.length <= 1000` * `sentence` consists of lowercase English letters.
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
Array,Hash Table,Binary Search,Greedy
Hard
null
272
hey what is up it is thursday april 14th 2022 and i am here again this morning for a new problem closest binary search tree value 2. uh welcome to coding with chef and thanks for joining and watching and if you like this video remember to like subscribe and um comment on the link below let me know how i'm doing and uh yeah um just uh give me some feedback um so yeah today another tree problem i'm doing this a little late later than i wanted to uh i got um kind of again this mornings are rough right what can you do but anyway let's get to it um right so this is labeled as a hard okay it doesn't look like a heart from first read but uh let's go through the details uh given the root of a binary search tree a target value and integer k return the k values and the bst that are closest to the target you may return the answer in any order you are guaranteed to have only one unique set of k values in the bst that are closest to the target okay all right so um this is the example four two five one three this tree that's rooted at four it's a binary search tree so um that means that we could um traverse through it pretty quickly uh that means that an inorder traversal through the binary search tree is uh going to pretty much give us a sorted array so um that's good that's uh one way of doing this i have a few ways of doing this i'm gonna actually um do this in probably a little bit of a less efficient way for now because i'm trying to get some practice with certain data structures but what you could do is one thing is that you can iterate through this binary search tree and efficient solution in order uh of traversal and you essentially could create some kind of like um sliding window which does this uh you know pretty fast i guess and it the window is constrained to k values that's something that i'll do in a another solution so i'm going to label this as a solution one and have a another video where i do a faster solution so in solution um solution one what i'm going to do i'm not going to take advantage of the binary search property because i want to just do a plain uh iteration through the tree so first what i'm going to do and just see if this works integer double i'm going to have a data structure that sorts a binary tree so basically um in i'm going to keep track of the values in the tree structure this way and i'll explain in a second what am i doing here um okay so i'm using a comparator you'll see why i'm using this in a second and this comparator so basically what i'm thinking of doing let me before i go into the comparator uh if i iterate through this tree in like a pre-order traversal or some kind of pre-order traversal or some kind of pre-order traversal or some kind of traversal uh i'll get values like one two three four five and so just to get the values the k closest values um pretty much this difference if the target is 3.7 the target is 3.7 the target is 3.7 right 1 4 8 6. all i have to do is just subtract value by value from this value right and see which ones are the k closest okay so that's pretty intuitive right because in this we have 2.7 i'm gonna not round in this we have 2.7 i'm gonna not round in this we have 2.7 i'm gonna not round it i'm gonna round it just for brevity i have two seven one seven point seven uh one seven okay so what are the k closest values okay so the k closest values are basically going to be and k is 2 so that's going to be these two guys right or these two guys whatever um and there's actually the difference is larger so um yeah so how do we get the k closely oh and then i let's see one two three four five let's from these values but there's there may be more values but anyway let's okay let's um look for the solution right uh let's see if we can determine uh what the k closest values are um intuitively so if i use if i put those on a heap as i iterate through the tree the k closest values will automatically be sorted right and i don't have to increase the heap size uh indefinitely right i can do something like i can always have for example if i have a max heap i can have only the smallest values added to this max heap at any time and i can pull off this max heap so that anything larger than k whenever k is exceeded the heap size k is exceeded i can pull off that heap and remember a heap of time extraction for the top level element in the max heap is one of one so um the and the reorganization so essentially the heap will reorganize itself every time i add an element to it and take an element off of it and i'm only going to have the smallest elements in the end of the bit at the end of the maxi we would ask why i'm not using a min heap so because a min heap orders elements one two three four five well max he orders elements five or three two one the reason why is because at any time um the maxi will order elements right let's just say these are just some other elements uh then it'll put three in front but let's say i want the cake largest value since k is equal to two equals two remove three and then two and one will be left and i can just help i can always prevent the heap from uh putting elements that are larger than the smallest elements on by just maintaining the same heap size okay so uh okay let's put a comparator for a max heap if i'm writing this out because i can compress this notation that the point of this is learning so a comparator uh in a comparator since we're comparing values of doubles right the double is the second value of the pair i'm using a pair to maintain why am i using a pair here because the pair is going to maintain both the value and the difference corresponding to that value i could have used an array i could use some other data structure but i also sometimes it's nice to work with something semantically nice like a pair okay so now this is what the comparator does and again max it's a maxi because b is larger than a right so b is going to if b is larger than a then essentially the value is going to be uh less than zero uh then the larger value gets stuck on the heap first the ordering gets stuck on the heap first and then the smaller value gets second uh and so on and so forth so if it was a min if this was a min heap then we just reverse these and then uh we can have them in because then the order will have the smallest elements in front of the heat okay let's go so that's the list that we're returning integer double and java is wordy i could obviously in kotlin or something like that i could have a much more semantically cleaner uh piece of code but i'm just trying to get through this here so the priority queue is the heap that will organize and then okay so um that is the uh that is the priority queue um and now this now we're going to go through the iteration of the tree so i'm just going to do an in-order traversal i've never to do an in-order traversal i've never to do an in-order traversal i've never entered a pre-order traversal now entered a pre-order traversal now entered a pre-order traversal now because those are the easiest to write um but uh in the future i'm gonna do it um is ordered in order traversal because that takes advantage of the property of the binary search tree property um okay but this is also useful for any general stream not only a binary search tree so that's a nice another nice thing about this um okay double so now this is just this is basically um you should be familiar with in order traversal iteration uh or pre-order traversal iteration to a or pre-order traversal iteration to a or pre-order traversal iteration to a binary tree if not then i will quickly go over it but it's not too bad minus target okay so here this is where we add to the priority queue this is where the work of the tree is done if pq dot size is greater than k remember i'm using a max heap here so whenever i use a max heap to get the smallest elements i have to make sure that our smallest k elements i have to make sure that remove elements that are in front of the heap when the case size is exceeded okay because at that point then the heat will uh not allow us to get the values we need the minimum values we need if we don't do that okay so uh when we write this out you know right not equal to no okay so what's going on here so this is basically um the in pre-order traversal uh we could have in pre-order traversal uh we could have in pre-order traversal uh we could have uh also written this in a recursive fashion but the iterative fashion is more compact you have a stack here and in the recursive uh implementation of the pre-orders implementation of the pre-orders implementation of the pre-orders traversal the stack is implicit in the stack frames uh so that's basically um what it you know what the traversal looks like if you want to add if you want to emulate adding the values remember the stack is last in first out so first you add the first thing you add is the root right and then you add two i'm going by this example on the right here you add two right and uh then so if the left child is not equal to null then you add two but the right channels is not equal to no you add five right and then uh you essentially your for the next this stack that pop you pop off the top element so i popped off uh the top element which is four right and so and then i added two and five right because the first thing i did was add four okay let's make sure i do that because this is important you have to push the root so we have the root of the tree we push the root of onto the stack right so that would be four we pop the left shell in the we pushed our left shot we pop it off before we push two and five then on the next iteration we pop off um five right and then five doesn't have any children so all that's left is two so we pop off two in the stack and then we add a one and three and then on the next iteration we pop off um one and three okay so basically the order of the stacks uh popping and execution uh will determine the value of the tree the traversal okay so that's in order because uh just compared to the recursive version when you get a chance of what the value should be when you're i'm not in order pre-order what pre-order in order pre-order what pre-order in order pre-order what pre-order version should be so okay cool and so let's do the last thing is now we have a priority queue empty result don't get key again key and return so basically what's going on here is that we have the priority queue filled with values up to k and these are guaranteed at this point to be the smallest values even though this is a maxi because all the larger elements have been in an online fashion or an active fashion been popped off before the heat could come away so whatever is left is still going to be ordered from largest to smallest but it's going to be the smallest elements of the explosive k elements of the total uh differences that are computed throughout the entire tree okay so let's run this of course let's see what i'm missing here there's always something missing new comparator uh no comparator there let's check if double val less than zero oh yeah but i decided to opt for the long route for this so public and compare be okay um let's make sure i get all the values right here i don't need this there we go again the right parenthesis and then resolve integer okay yeah okay exception new pair integer double oh let's see cannot be cast to comparable okay so okay why is that the case uh pq that integral double is uh i need to pass the comparator and see these little things sketching okay cool and so yep there you go that's the solution uh yeah uh so that's basically it could be faster and we could in the future do a faster solution but this is what i'm uh doing for now um this is slower because essentially this is an k log n solution because you're adding two you're popping off the stack in you know each element you're visiting only once but since you're reordering the stack each time you're uh essentially doing okay uh log n operation on each iteration so uh since you're doing it most k of them right uh you're doing this ordering is going to be uh login our k log n and uh yeah and then this is another k uh removal in k log n right so uh yeah so that's it for now a little bit of a bumpy ride today but getting into the swing of things so i'll see you around next time and stay coding and we'll do another solution in the future okay
Closest Binary Search Tree Value II
closest-binary-search-tree-value-ii
Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**. You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`. **Example 1:** **Input:** root = \[4,2,5,1,3\], target = 3.714286, k = 2 **Output:** \[4,3\] **Example 2:** **Input:** root = \[1\], target = 0.000000, k = 1 **Output:** \[1\] **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104`. * `0 <= Node.val <= 109` * `-109 <= target <= 109` **Follow up:** Assume that the BST is balanced. Could you solve it in less than `O(n)` runtime (where `n = total nodes`)?
Consider implement these two helper functions: getPredecessor(N), which returns the next smaller node to N. getSuccessor(N), which returns the next larger node to N. Try to assume that each node has a parent pointer, it makes the problem much easier. Without parent pointer we just need to keep track of the path from the root to the current node using a stack. You would need two stacks to track the path in finding predecessor and successor node separately.
Two Pointers,Stack,Tree,Depth-First Search,Binary Search Tree,Heap (Priority Queue),Binary Tree
Hard
94,270
1,091
welcome to february's leeco challenge today's problem is shortest path in binary matrix in an n by n square grid each cell is either empty zero or blocked one a clear path from top left to bottom right has length k if and only if it is composed of cells inside of our grid now we can move in eight directions basically we can only move the cells that have a zero not one so this is a straightforward path finding algorithm they tell you straight out in the hint do a breath first search so we're gonna do that we're gonna start at the top left and do a breath first search in all eight directions we just need to make sure that the cell is in bounds that we haven't visited and it also is a zero not a one and then we can just continue to see if we can get to the bottom right and as soon as we do that would be the shortest number of steps that we take could take to get there since we're doing a breadth first search so let's start by initializing a couple variables let's start with the mnn which should just be the length of the grid as well as the length of grade zero we also want to have a visited set to keep track of the cells that we've already visited because if we've already visited in our breath first search we know that this is the quickest path to get there so we don't need to recalculate that we also need to have our cue and i'm also going to make a list of all the directions that we can go into to make it a little bit easier there are going to be eight directions now starting with let's say zero one and give me a minute to do this so we can move up down left right and we can move a couple diagonals here one and we can also go negative one we can also go one negative one so great these are all eight directions we can go in so let's begin and write our algorithm now before that we got to make sure that the first cell that we start at is actually a zero because if it's a one we can't even begin this algorithm right so if grid zero 0 is equal to 0 then we could add to our q and what i'm going to do is add a tuple with the number of steps that we've taken to get here start with one as well as the another tuple indicating to us the cell number that we're at i will also say visited dot add here zero and all right let's begin algorithm so while q first thing we'll do is pop off our pop off this whatever's on the queue and what will it be here we'll have the number of steps as well as i'm going to call it temporary for now and this would be q pop left now the rc would be the temp 0 and temp 1. okay so we have all the information we need now we're going to move in some directions we'll say 4ij in directions let's calculate our new r and new c so new r and new c is going to be equal to r plus i and c plus j so if this is in bounds so the row isn't in bounds and the column is in bounds and it's a zero not a one and we haven't visited before so if new our new c not and visited oops okay then we can append to our cue a tuple with the number of steps plus one and a tuple of the new r and new c make sure to add to our visited as well so that we don't revisit places we've already been now i guess i should add our base condition here if r c is equal to m minus one and n minus one whoops then we know that we've gone into the bottom right so we can just return the number of steps otherwise if we follow this fall out of this while loop then we can turn a negative one because there is no path that exists to get to the bottom right all right so let's see if this works um directions not enough values to unpack expected two but got one that's weird um all right let's see here what did i mess up okay my fault made a typo there okay so looks like it's working let's go ahead and submit that and there we go accepted so this is a n times n time complexity because we won't be revisiting ones that we visited we do use extra space one way you could avoid doing that is you could just update the grid itself to equal one each time we visited so instead of this we could say grid you know zero plus one and similarly we can do something like that here and this will allow us to not visited places that we've already said so this depends on whether we're allowed to update the original grid or not if we are then we can save some memory and do it this way so that would work too alright so thanks for watching my channel remember do not trust me i know nothing
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
498
hello guys welcome back to another video today we'll be talking about 498 diagonal traverse so it says given a matrix of M times and elements M rows and columns returned all elements of the matrix in diagonal order as shown in the image and the below image so I actually put this into this white board so it could be better visualized so I put the eye index here and then the J index here so from this what you should realize is that each element on the same line has the same I plus J value so let's take this line for example so for has a I plus J of one and then two also has an I plus J of one and if you take this line for example eight has the I plus J of three while six has the I plus J of three as well so this is actually the pattern that we're gonna use to identify the elements that are on the same line and you can realize here that when I plus J is odd then the diagonal is going down so here I for one I plus J is at zero which is even and it's going up when we're here on this line that I plus J is 1 so it's going down and this is even so it's going up and this is odd so it's going down so when I plus J is odd the diagonal reverses and another thing to notice in this question is that the J index this is actually a very important part because it wants you to go by order so which means you can't just go one for two so the J index actually organizes to order say when the diagonals going down the smaller J index gets put first in the inter a that we're gonna have when the array is going up the bigger J index is gonna go last so basically there's a pattern here and the solution here is what I wrote here so you want to use a 2d array to store each element along with the column index and the I plus J index with the element value then you can use a comparator to sort this 2d array and then once it's sorted you just Traverse the 2d array and take the element values and plug it in to the intr a so that's how we're gonna approach this problem and I hope it makes sense to you guys so let's get code in here alright so right here first things first what you always want to do with these matrix problem is that if matrix that length there's equal to zero you want to return turn a new in array with nothing in it okay so now we can get the coding part so here what you want to do first is call your could be array I'll just call it 2d right now actually I'll give it a better name I'll call it array me okay so we could equal the commute and matrix rain times matrix 0 dot length and this is because we wanted to hold every single value in the 2d array matrix and then we make it 3 cuz I stated here we need to store that I plus J index and just store the column index and we need to store the element value so it's actually going to be a width of 3 and then for our array we'll call it rez and it's equal to new int RV but right okay so now that we have this we can start traversing through this array so for int I equals 0 I was less a matrix length I plus or and J is equal to 0 J is less than matrix we can just say at zero but if you want to say I it's fine because it's stated here that it's an M times n so the width will not change and then J plus okay so for here I'm gonna call a and that's variable to tell us the index of our to do right here so I'm gonna go are that index plus so what I did here is that because the plus is after the index it's gonna call this index and then it's gonna add 1 to the value so I don't have to put any index plus here all right so that's what it does but basically same thing alright so it's equal to new in array index sorry I'm making int array here so you want I plus J value and then you want the J value and then you also want element value so matrix I and I J alright so now that you've stored this in you can go out of this loop and there's the complex part of this problem so once you have all the information that you need in there in to sort the array and luckily in Java there's actually a very easy function using comparator to sort this 2d matrix so all we do here is we call arrays dot sort and then you put the array you want to sort the name in here so ARR G they are Rd and then comma new comparator your new you might be new to this but um the pretty interesting function and you should check it out so you have your comparator in here I'm just gonna put a semicolon here just in case I forget so inside here make sure this parameters and int array and so you have public and compare and beside this you want and write a and then a rate B for compared for comparing reasons and then here you can say if a at zero which is talking about this I plus J index I say at 0 is not equal to ax B at 0 sorry so what this statement does is that let me finish this for so you there's a - a at zero - speedmaster at there's a - a at zero - speedmaster at there's a - a at zero - speedmaster at zero so right here remember how we held the same I plus J values on the same line so therefore if it's not the same it'll sort the I plus J value so this will actually go in ascending order and then we can just get it so that's the first part however if you remember me saying here that when I plus J is odd the diagonal reverses so what this basically means is the J index instead of organizing the J index from the smallest to biggest we're going to organize it from the biggest to smallest so what we're gonna do here whoopsies ok so what we're gonna do here is that if a at 0 mod - there's not equal to it if a at 0 mod - there's not equal to it if a at 0 mod - there's not equal to it well this is my bed there's not equal to 1 sorry 0 and then what we're gonna do here is return the opposite of a at 1 minus B at 1 and remember that yeah 1 is the J index and then else we're just gonna return the same thing but without the negative in front of it so this flips the value of this which is why we do it so now that the sorest finish the rest of the process is fairly easy now all you need to do is reverse through this 2d array and get your value so int I is equal to 0 is less than our length and remember here why there's a so here I'm only going to use one for loop and the reason is because these three values this is for this part so the only value we actually need and here is this matrix value which is at the second position so we only need to traverse through the rows of the array and get the second position of each row so what I'm gonna do here is raz anti is equal to Rd at I and at 2 so this calls this value which stores interests and then all you need to do next is just to return rest and then you'll be done with the problem so this check of we got the test cases right done looks like we had the right um just check our one more test case make it a square and see how it does alright this looks good that's turn it in and looks like we passed so that's how you do this problem so the time complexity here this sort is and login and this is N squared so we'll just take an own skirt so this is actually an N squared algorithm and that's how you solve diagonal traverse all right guys I hope you've enjoyed this me solving this problem if you want to see more of these problems check out my channel page and don't forget to Like and subscribe
Diagonal Traverse
diagonal-traverse
Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,4,7,5,3,6,8,9\] **Example 2:** **Input:** mat = \[\[1,2\],\[3,4\]\] **Output:** \[1,2,3,4\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `-105 <= mat[i][j] <= 105`
null
Array,Matrix,Simulation
Medium
2197
1,905
Hello hi friends welcome back today we are going to solid problem 1905 account sub violence this problem voice of pay Google Facebook Amazon in the last interview sub let's go through this description of the problem you are you remember in binary matrices grade one and two containing only 0s and 1s Suzy Rose Water and Voice Land and Ireland Is Group of Bones Connected Directionally Horizontal or Vertical Sugar Sales Outside of the Great and Considered Water Sales and I Lending Rates Considered All Identification of Land in Grade One Day Contains All the Sales Date Make-up Decided and agreed to return Contains All the Sales Date Make-up Decided and agreed to return Contains All the Sales Date Make-up Decided and agreed to return number of violence in great to that was considered sub violence 210 have given 30 to examples for has ndri knowledge dish constraints show length of freedom in the and great you don't drink there and equal and any equal to means the column patrons Columns Her Shopping Read 132 Requested Same and the same column between 1250 and you will contain 0 800 This is a medium level problem a Facebook Google and Amazon So let's take this example over and we can discuss how we can unite for this problem so let's change colors Basically so the problem should be come that Jitni Distic 3100 This is the Great 153 Doraemon and Shizuka grade too short to give its argument was right and preserve if you look at this great too right citizen island in the great too basically are you can see This human rights highlight one day high blood development ireland convid it connected 22 landfill sites and air connect vertically and horizontally side by side so as you can see delay all correspond engagement in the grade one with which maps year it's been hit max like this basically 512 basically it Back to Year Highlighting Iss Pani Ko Respond Zinc Iodine Grade One Such Means the Best All the Sense of This Highly Learned in Great You're Late in Grade One Ulcerated Time Extra Celebrates It's Okay Mother Can Have More Schools But Every Saint That Shailendra Singh Every One Should right men's land sell foot where present in life right of great you should be present in screed one day when called violence 34 red is dynasty now high alert all ireland similar if you look at this one day is another one piece late loan ponting Mapping Bright Like A Same Shell Ireland Celebration This Another Child And Soon S Another All Pilot Clear Light Bill Gets Another Mapping Clear 500 1000 All Violence For This One S U Can See Enemy There Is No Mapping Key Brightness Vande Resume App In English Of Us Emphasis Central Means Its Water And Destroys Land ₹10 Note Account When Destroys Land ₹10 Note Account When Destroys Land ₹10 Note Account When Ireland Similar Tags Country Ireland 3096 Counted As A Pilot Why Because There Is No Corresponding Mapping Beg This 30 UPSC That Government According Sales Birthday Are Not Fall Land Sale Price Vikas This is Water ₹100 Note Account Dr to the Balance and ₹100 Note Account Dr to the Balance and ₹100 Note Account Dr to the Balance and Total Sub Pilot Skin This Great Spirit Freezer Total White Dishonor Red Color 246 Miles 123 KM To Have Written Number of Serenity Hui and Finding in Poor to Thought Present in Every Day End Night So As You Can See Hair Definition And Decided That Destroyed Because We Find The Number Of Ordinary Women So Let's Reduce Highlighted Things Became Just Smiled And Use This Per Saket Hai To Aap Nau We Are Going To Solve This Problem Which Using Different Dates For Search And Deficit Reversionary Defense Morning And Defects Can Work In This Case Will Go And Will Approach Like You Will Read Through Grades Right From This And Top To The Bottom And They Will Never See Any One Should Go Right With Land Sale Will Start Doing Defense Fennel Example Absolutely CDS One Should Rise In Hui Start Doing Anything For Direction Correct Pro For Directions Pimples Us And Vertical And Horizontal E Give This Is Still When You Can Take For Example Late Se Enemy Israel Ko Enjoy Celebrate Life Enjoy List Free Mode White Layer So Icon Reason Leader Cell Tax Barrier On To You Will Look Into Forests Of - 101 Is Deep Sandwich Upwards Yo Of - 101 Is Deep Sandwich Upwards Yo Of - 101 Is Deep Sandwich Upwards Yo Pyaar Ko In Upward Koi Download Din This Tel Will Be I Plus One J Correct Wicket Next Roll Andar Right Side It Will Be I Plus One Zeta Plus Subscribe An evolved saver of birth column on Plus One will increase clear 100 Z Plus One and you are going on in the left side and will be IJ - are going on in the left side and will be IJ - are going on in the left side and will be IJ - 08 2010 For directions to you will go away I will never find Any cell with land right one and will give what do you trying to consume water and the silent for example if i have land cell in the given subscribe and will going on alarm hear yudhishthir right only will consider cell suvichar-1 there are any only will consider cell suvichar-1 there are any only will consider cell suvichar-1 there are any four land cells Takhi t0 Will Not Consider Yudh Return Chaumu Gaya Hai Yaar Tu Yaar Boeing Of Birth Download And Left Side UC Of Child's Affair Going Outside Of The Boundary Of The Matrix Relative Website The Matrix Villages Will Not Consider Dost Excise Vikas 2009 Valid Only Will Always Consider Velvet Silk Luxury All Elements In One Like This Difficult To Validate Only And Decisions Were Valid CSS Valid Inference Switzerland Also Want To Consider And You Will Want To Key Checking At 10M Location Same Position In Jeevan Matrix Rack Every State Will Consider And Secret In The Same position in the GM Jeevan matrix with every metric and this will find all correspond which are right thinking but case will just account when all iodine profit account will be first t20 now you will increase your account on one side and exact same Time Hui Just Make Distance Like Mrs. Chocolate Mixture Ko Yudh Khol Solve Will Give In Just Changes Tel Vansh Visit Will Change It's To Sukhram Wave Market 251 Maruti Salute Ooo All Sets Mitthu Right And Why They Are Doing But Because Hui 152 E Don't Want Ooo Again Ignore Reduce Flight So Good Behavior Change Into Two Solve Will Have To Do Calculator Sales From Wasteland Least One Life So Will Avoid 0.15 Inches Marketable To After Visiting 0.15 Inches Marketable To After Visiting 0.15 Inches Marketable To After Visiting Research On Devanagari And Nau After Which One Will Visit Enemy Right Facility Is Ireland Will Find A Bird Candy Crush Ponting's Her Absolutely Clear Junior Science In Its Water And So Will Not Written Content Is Available Now Visit All This Data Is The Correspondingly One Here Right Will Contest All This Ireland Right Directions In This Direction Shrouded in Darkness Can Do Anything In This Right Only Once Every One Shall Ireland Basically In To-Do One Shall Ireland Basically In To-Do One Shall Ireland Basically In To-Do List Will Held As One And Will Do You Will Be Able To Hear What This Point No Data Is Not Responding To Here Right subscribe and subscribe the Channel Please subscribe and subscirbe ki mitrata selvan right only 101 Land Sale In Prevented 238 Basis Of Proper Implementation And Solve This Problem Using Defense Solitaire Look into the implementation of is so as you can see this is the function that is give great freedom and great two three one two three studio me 2800 will create One now winters available conducts of violence and will create one set of bullion right time to explore new you have created and they will hold fun of which create one today I am here for details visit and because you don't want to one to your visitors and vent To revisit the same again writes will just keep track of words you have visited using visited metrics and in this receiver we are now traveler lite travels and tours and grade to is great to basically and we first start live with clear set and will start doing deficit Which Was Now Have Found One Island In Grade To Do You Want To Say Activities Say No Toe Tattoo Yer Checking Using Facebook Given Porn Its Return Type Is What Toe Were Passing Two Mattresses The Position Come Light Of The Sale Starting Sale And Will First Set Regulations And Will Power Visited Her Hair Soft Things You Want To Check Is Accused Going Outside Of The Founder Of The Matrix Rate Sudesh What They Are Taking Care Been Going Outside Of Boundary And Iss Aloo Yaar Visiting 1507 Bin In That Case How I Just Want To Return To Prithvi That Is Not Valid Only And Only Have Already Written Updates And Right Clear Those Viewers Return From This Point To You Will Not Go Forward Bigg Boss That Is Not Valid For Visiting Not And Up To Date Vtu Check The Self That Were Visiting Correspondent in One Cell in Matrix Hundred Years to Correspond in One Cell in Matrix to Value Your Cigarette's Array in C a Beneficial and Corresponding Matrix Cell is So What is Mintu Se Whenever Listed This Out Line Plain You Again On and Delicious and Rights For correspondence and where taken for this and here right side effect is not one basically rectify this not one year since I did not match these days then forms will be our satellite and return basically reset is useful to get the information of did this Function Because Devise Function Will Not Written In Its Return Avoid Solve Understand Your Fit Before Two Not Were Going Through Use This Flexseed Basically Right Some Where Is There Is No Match Matching Just Former Value Gift Size Zero-valued Right To You Will Gift Size Zero-valued Right To You Will Gift Size Zero-valued Right To You Will Not Withdraw Aside and other wise in normal scenario where hui and finding matching se nuvvu great you have found matching fold nou how to find after remaining ireland celebrate so they have to be effective in all directions to here you will declare right like this saw all records and often To Have Doing Facebook That's What You Will Be Doing Fair Price Shops Which Will Mark The Celebs Visit Forest And You Will Have To Write In The Matrix Also So Why Don't You Gift That One So I Just Want To Make That Change The Value And Now They Are Going And Reviews And Visiting Don't For Directions In The Defense Right Today The Growth In All Four Directions And Clear To Dushmani Say J - Vriksh Your Hair Tweet Disawar Current Servi - Vriksh Your Hair Tweet Disawar Current Servi - Vriksh Your Hair Tweet Disawar Current Servi Tried To Go For All For Research On To Yaar Do It Share It Till Only In The Loop And Finally Vansh Will Get Out And Way Come Here Three Wickets That Power Set Contents For Its Value Gifts Where Is Not Dare Mist Powder White Tight Beach Only Panty Set Hui Ascending And They Are Getting Anti Shatter High Means The Editor Then Iodine Ther School Increment Account Clear Kar Acts Will Go Into This For Lower Rates Will Find All The Island Website Wherever I Find One In Great To You Will Keep Doing A Sandwich Activities Surplus Of Wildlife And Or Not And The New year going to return to 10 of violence at so this is the weather of implementation is and will take your first to you will take care of this first test case rights and issued to give 3 and you will take doctor testis i to yaar getting correct Answer Rajat Innovative and Creative Is The Answer Sun Will Love You Know Who Will Check The Taste Case Ke Saudagar Discuss The Example Two Days Have Given Us To Induct Case You Always Have Output Correct Software Cutting Gents Hair Cutting Correct Caring Whose Pregnancy Festivals Hai 116 Fashion Gold Accepted By It's Good For This Is The Way Can Solve Account White Problem Subscribe Facebook Google Assistant Practice Problem Also Give You Have Violated My Play List Of List To Decode Solutions Please Visit His Lord Of Life And More Than Hundred Solved Problems Explained With Examples and They Should Also Not Consist of Different Varieties of Problems That Verification Code in Interview for B Tech Companies Like Amazon Apple Google Facebook Microsoft and Many Others Believe Variety of Questions Asked His Dynamic Programming Directly Related Problems Related Interview Questions Difficult You Know Graph Tree Questions Here are some frequently asked interview questions for a limited company please go through it if you find this video health food if you like this solution Please hit like and subscribe your subscription this is really important for that because is the video can reach to more people the can also watch with solutions and get help during the interview preparation and java interview preparation for Please subscribe to the Channel thanks for watching video
Count Sub Islands
design-authentication-manager
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in `grid2` is considered a **sub-island** if there is an island in `grid1` that contains **all** the cells that make up **this** island in `grid2`. Return the _**number** of islands in_ `grid2` _that are considered **sub-islands**_. **Example 1:** **Input:** grid1 = \[\[1,1,1,0,0\],\[0,1,1,1,1\],\[0,0,0,0,0\],\[1,0,0,0,0\],\[1,1,0,1,1\]\], grid2 = \[\[1,1,1,0,0\],\[0,0,1,1,1\],\[0,1,0,0,0\],\[1,0,1,1,0\],\[0,1,0,1,0\]\] **Output:** 3 **Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. **Example 2:** **Input:** grid1 = \[\[1,0,1,0,1\],\[1,1,1,1,1\],\[0,0,0,0,0\],\[1,1,1,1,1\],\[1,0,1,0,1\]\], grid2 = \[\[0,0,0,0,0\],\[1,1,1,1,1\],\[0,1,0,1,0\],\[0,1,0,1,0\],\[1,0,0,0,1\]\] **Output:** 2 **Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands. **Constraints:** * `m == grid1.length == grid2.length` * `n == grid1[i].length == grid2[i].length` * `1 <= m, n <= 500` * `grid1[i][j]` and `grid2[i][j]` are either `0` or `1`.
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
Hash Table,Design
Medium
null
1,447
in this video we will look at lead code problem number one four seven and it's called simplified fractions and you can see a glimpse of the problem here if we are given a number four then what we have to do we have to find all the fractions between 0 and 1 but not including 0 and 1. so you can see that i write 1 by 2 1 by 3 1 by 4 2 by 3 by 4. so in all these cases denominator will be more than numerator because it has to lie between 0 and 1 and if i have written 4 these values should be less than or equal to 4 so denominator is obviously larger so we have to check for denominator so you see that none of the denominators are more than 4 and these has to be unique so let's see a larger problem let's see if we want to write it for 5 so these are the unique possibilities so clearly you can see that we are starting with numerator 1 so write down all the possibilities with 1 so with 1 what can i write i cannot write 1 by 1 since it will be 1 and we have to write it between 0 and 1 so the value will be here value should be less than 1 greater than 0 so this is not valid next is 1 by 2 this denominator should be less than 5 so 1 by 2 is valid 1 by 3 is valid 1 by 4 is valid even 1 by 5 is valid so denominator can be equal to this only the value should not be equal to 0 or 1 it should be between them so we are done with 1 and you can see these are the 4 possibilities then we start with 2 so can we write 2 by 2 or 2 by 1 if we write 2 by 1 it's more than 1 if we write 2 by 1 not possible 2 by 2 not possible since it will be 1 it will be more than 1 next is 2 by 3 it's valid next is 2 by 4 but you see that 2 by 4 is same as 1 by 2 which we have already covered so these should be unique so we will discard it so how can we check if it has already occurred uh either you take the gcd of numerator and denominator and you divide them so you get one by two or you store the decimal part like in this case it will be 0.5 in this case it will be 0.5 in this case it will be 0.5 and this is also 0.5 so you keep a set and this is also 0.5 so you keep a set and this is also 0.5 so you keep a set and whenever you create a value insert there so 0.5 is there so 0.5 is there so 0.5 is there 0.3334 is there 0.3334 is there 0.3334 is there 0.25 is there and so on so next time 2 0.25 is there and so on so next time 2 0.25 is there and so on so next time 2 by 4 comes it's valid it's less than 1 it's more than 0 but we see that we have already stored 0.5 so we will not store it 0.5 so we will not store it 0.5 so we will not store it next is 2 by 5 and next is 2 by 6 but that will be more than 5 so we stop then we come to 3 so we are done with 2 so for three by one is not possible three by two is not possible three by three is not possible so first will be three by four then next is three by five so we are done with three last one is four by five so how can we do that you see that in numerator we have one two three four we will never have five so we can have a loop for i equal to one 2 if this is n 1 to n minus 1 so it will never be n this is the outer loop and inner loop we can have j equal to i plus 1 to n so denominator will be till 5 numerator will be till 4. so you see here n minus 1 n and our denominator will be strictly one larger than numerator at least so it starts from i plus 1 and then we create a fraction i divided by j if it's not insert it in the result we have to print all these strings so create string out of that so we can have i plus then this fraction sign in the string and then append j so this will be the string that we want to insert in the result and either you take the gcd and cancel out the common terms or you can store the fractional part in the set so let's take the eg root of storing the fractional part in the set so let's first write it in c process then we will modify it for java and python so this is the result which we will populate then we have an unordered set not zero otherwise it will be zero it has to be more than zero so one i less than n plus i j equal to i plus 1 j less than equal to n and plus j then float if i don't cast it to float it will we division will be done as integer then converted to float so since it's between 0 and 1 this will always hold the value 0.0 always hold the value 0.0 always hold the value 0.0 so we will convert one of these beforehand to float is set dot find fraction equal to set not and that is it's not found in the set so we insert it in both result as well as set and let's try it out and this works for this simple case let's add a few more cases let's add one let's add three four five and this is that accepted that is output is same as expected so let's go ahead and submit and the solution is accepted in c plus now let's write this exact same thing in java so let's copy and here the result return type is string list string and we can create an array list and then here we will have list sorry set float set okay let's try and this works for all the cases so let's submit and the solution is accepted in java as well finally we will do it for c plus python 3 sorry for ie in range 1 to n for j in range i plus 1 to n plus 1. and these two loops go away result dot append set not add and let's try so the solution works in python as well so let's submit and it's accepted in python as well
Simplified Fractions
jump-game-iv
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction with a denominator less-than-or-equal-to 2. **Example 2:** **Input:** n = 3 **Output:** \[ "1/2 ", "1/3 ", "2/3 "\] **Example 3:** **Input:** n = 4 **Output:** \[ "1/2 ", "1/3 ", "1/4 ", "2/3 ", "3/4 "\] **Explanation:** "2/4 " is not a simplified fraction because it can be simplified to "1/2 ". **Constraints:** * `1 <= n <= 100`
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Array,Hash Table,Breadth-First Search
Hard
2001
70
welcome to another one of my lead code videos in this one we will be doing lead code number 70 which is climbing stairs so the problem is you're climbing a staircase it takes there's a total of n steps to reach all the way to the top of the staircase and then there's two ways you can climb if you're at a given spot you can either take one step or two steps and so it's asking how many ways are there that you can get to the top so for example if there is a total of two steps you can either take one step and then another step or you can just take two steps so there's two ways that you can climb to the top similarly if there are three steps one way you can go is just do all three steps another way is one and two or two and one right so in this case there are three ways where we can climb to the top so this is kind of like a recursive slash dynamic programming um kind of problem and the way I approach this is I first come up with a method mathematical model right so let's say if the number of ways I can climb a staircase of n is basically equal to the number of ways I can climb to n minus 1 because from there I can just take one step and get to the top plus the number of ways I can climb to n minus two so you know the number of ways I can climb to the third step is number of ways I can get to the second step plus the number of ways I can get to the first step right and if I add them together then I'll get to the third step we know our base cases right so let's say weighs at zero or sorry ways at one if there's only one step we will have one way to climb that only one step right and if there are two steps we will have two ways of climbing it because you can either take one step and then another step or you can take two steps at once so there's two ways so if we know one and two we can compute n by just you know keep we can compute three four so on up to n and then we have our ways at n right so let's see how this goes so uh for n i is equal to so we'll check our base cases first right so if n is equal to 1 or n is equal to two we just return n right and then for in I is equal to three so we go up to I less than equal to n i plus so we go all the way to ways uh of n so here we can store ways n minus 2 to be equal to 1 because that would be ways of one and then ways of n minus 1 which is this one will be equal to 2 because n is 3 minus 1 2 so ways of 2 is 2. so here we've stored ways -1 and ways minus two -1 and ways minus two -1 and ways minus two and then we'll compute ways n and as we compute n we'll kind of shift it so ways n then becomes n minus 1 and then n minus 1 becomes n minus 2. so let's see ways n will be equal to weighs n minus 1 plus raise n minus 2 and then we'll have ways n minus 2 is now equal to ways n minus 1. and weighs n minus 1 will be equal to ways n for the next iteration right so we compute base n and then we shift it to the right so at the end of this the and the ways for n will be stored in N minus 1. so that's what we return and yeah that's it so let's try to run the code accept it submit it yes accept it 100 solution so thank you so much for watching and I'll see you in the next one
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236