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
149
hello guys welcome to God enzyme and in this video we are going to discuss problem 149 of lead code and the problem name is Max points in a line problem difficulty is hard let's read the problem statement given an array of points where points I is equal to X1 comma y1 represents a point in X Y plane return the maximum points in a line on the same straight line okay so this is a geometry problem let's see some examples first so here is an example this is the first example so we have one comma 1 2 comma 2 and 3 comma 3 and we can see all the three points lie in around line and when we count the number of points in this line uh it is the maximum number of points so our output is three let's see example number two so here is example number two we have several number of points and we can see if we try to join every point to every Point uh so basically we will be brute forcing it so we will join every point to every point and we will count number of uh all the points that fall on every line and we will when we will see this is the maximum points we will get so these are the four points and these lie on the same line so our answer is 4 in this case now let's also see the constraints we have points DOT length is equal to 300 and the points sorry and points I represent consists of only two characters so the length is two and X1 comma y one ranges from minus 10 raised to power 4 to 10 s by 4 and all the pairs are unique so we don't have to take care of this uh last point but uh let's try to analyze what kind of complexity we will need and since points DOT length is approx is 300 so if we Cube it we will get an approximately uh six and two times per 6 which is almost less than 10 square 7. so we can say that uh maximum algorithm of Big O of n Cube will work in this case and in the and today I am going to discuss a solution of big of n Square so let's see the approach but before that we should know what kind of data structure to use but so we want to use our data structure where we will are going to store lines and for every line we are going to have some set of points right so we will need something like a hash map to where we are the where we will map every line to a set which will consist of unique points and a line on that line right so we are going to use hashmap for this case now the question comes what uh what describes the line so since we are going to sense our indexes of the hash map are going to be line but what exactly is a line and uh to answer this we need some knowledge of mathematics and let's see how we can actually represent the line and I am going to show you two forms and I'm going to show you two types of forms of line one is the uh to represent a straight line in mathematics one is the slope form and it is given by Y is equal to MX plus C here m is the slope and C is the intercept and another is a point form so y minus y 1 upon x minus x 1 this is also a slope which is equal to Y 2 minus y 1 upon x 2 minus x 1 and here you can also use Y and X in this case also it follows give you the same result but the important thing is this is equal to slope so since slope is common one thing is for sure that we have to calculate the slope of the line and in the second point or second form we can use this point form to calculate the value of C and that's C is going to be equal to slope into x minus X1 plus y1 right and if we put y x is equal to 0 in this point form we will get C is equal to slope into minus X1 plus y1 right so I will write that for you so C is equal to slope into minus X1 plus y1 and in the hash map we can store pairs like uh first we are going to have a pair of slope and C slope and The Intercept which will map to a set of points right but uh here comes a problem what if this m the slope is equal to Infinity what are we going to what will be our Intercept in that case so for that if the slope is infinite we can see that uh our lines will be vertical and if the two points remain on the same line then we can see the X component of that line will be same so in that case we are going to store this x value in the in place of this C okay if that's if the if our slope is infinity otherwise we are going to use this formula only so that is that was all the explanation and now let's see the code for this so this is the python code first I am checking the first time handling the edge cases so if our length of points is one I'm simply returning one and if it is two and it will simulated on into and this is our map uh the dictionary and now I'm collect I'm saying that the okay for every Point uh this is an ol Square Loop right because um for every Iron Ridge line point I'm also traveling from to the other points and later my first point will be X1 y1 okay and this X2 Y2 will be my second point if these two are equal if the X values is equal since we see so in this formula we have to uh divide by X2 minus X1 since uh we so we have to handle it explicitly otherwise it will give us a divided by zero error so if X1 is equal to X2 my slope will be infinite and that means if we will reach this case and in Python we can specify slope is equal to infinite using this float of INF so this will make my slope infinite and otherwise I'm simply going to use this formula now if my slope was infinite what I am doing if my slope is infinite I am storing my X values in place of The Intercept so in my so my intercept will be in X1 otherwise I am storing the I am storing my intercept using this above formula slope is equal to C is equal to slope into minus X1 Plus y1 and now uh in the dictionary I am putting these so if there's a tuple of slope comma intercept is already present in my dictionary then I am adding to the set of points x 2 comma Y2 otherwise I am making a new set for that for this Tuple and adding my these two points in that and At Last I can Traverse in the dictionary and find the maximum amount of length of set of points in the dictionary and next I am going to return answer so that completes the code so I hope you were able to understand this so if you were able to understand this currently subscribe to my channel like this video I will see you guys next time happy learning thank you
Max Points on a Line
max-points-on-a-line
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\] **Output:** 4 **Constraints:** * `1 <= points.length <= 300` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the `points` are **unique**.
null
Array,Hash Table,Math,Geometry
Hard
356,2287
986
hello everyone welcome to the channel today's question is interlaced intersections if you are new to the channel please consider subscribing we sold a lot of interview question on this channel and that can definitely help you with your interview a questions is given to lists of close intervals each list of intervals his pay was destroyed and in a sorted order written the intersection of these two interval lists and we again with the example and if we look at example we are given with a and P and we need Britain the intersection and we can clearly see the intersection between a and B so these are the points of intersections so let's move to pen and paper let's see how we can solve this question after that we will see the code I have taken the example given in the question and this question is similar to the question we have done before on this channel and you can find the link of the quotient in the description below and this question is asking that we need to return the intersection of these two intervals and the intervals are a and B and if we look at bar chart two on the send how the intersection of interval is working then this represents a and this represents B and this represents our output and we can clearly see that intersection of a and B for the first elements are this part and we can clearly see how we are getting there so intersection of these two point will be equal to 1 and 2 and how we are getting 1 into 1 is the maximum of starting point you can see 1 we are starting with here and 1 we have starting point here and the starting point is maximum of starting off a and B and if we took over the ending point this is minimum of ending of a and B you can clearly see a and say B and C so you can say the ending of R in the word is minimum of ending of a and B so now we go to our first interval and to get all the intervals I need to spam both of the list a and B and for that I need to increase the point ring a and B but if you see that a starting here before B ends that means we also consider it as a interval and which also means I just can't increase the pointer in both of the array at the same time because what if I was first here at 0 and 0 after getting my first interval but if I am moved to 1 and one that I would have missed this part and my answer have been 8 and then and I missed this part which is 5 and 5 so how to check which one to move whether I have to move in a or we have to move in B so for that I will compare the ending part of each element and if ending element of a is greater than ending element of P these are green with every single element and looking over in this case I will increase the point of P else if the ending part of a is less than ending part of P in that case I will increase pointer off and let's see this thing in the second interval so if I come here I am done with my first interval now I will compare ending element of a and ending element of P and I found that ending element of B is greater than ending element of a that means I will going to increase the pointer in a and I will come here but I will not going to increase the pointer in P so I will still remain here now again I will implement this part that the starting point of the interval will be the maximum of starting point of a and B so our is this which is maximum of five and one so Maxima is five okay so we got five and the ending point of the interval will be minimum of ending point of a and ending point of B and the minimum of ending point of a and ending point of B is five and so in this way we will get our second interval which is five and five which represent this part okay now again we have the quotient in which part we have to increase the point of again we will compare the ending point of a and B so we have a here and we have be here so I will compare the ending part of a which is 10 and the ending part of B which is 5 and if ending part of a is greater than ending part of B I will increase the pointing B so now I will come here and I will remain here in a so now again I will use this part to get my interval so the starting point of the interval will be maximum of a and B is 8 and the ending point of the interval will be minimum of a and B which is 10 and this is our third interval now again to increase the pointer I will compare the ending point of a and B and ending point of a is 10 and ending point of base 12 and ending point of a is not greater than ending point of B that means I will increase the pointer of a so now my a will come here now again to get the interval oil implement this thing so the starting point of the interval will be the maximum of starting point of a and P maximum of a and B is 13 and the ending point will be the minimum of ending of a and B and the minimum is 12 and now we are facing a weird thing that how can our starting point can be greater than the ending point if this is the case this is not an interval so if starting point is not less than equal to the ending point I will not going to append it my interval so let me write it down here if starting is less than equal to ending then only we are going to append it in intervals so we will not going to append it in the endeavor but again to increase the pointer we will use ending point of a and ending point of B ending point of H 23 and ending point of peace ending point of a is good with an ending point of B so I will increase the point O in B so again the starting point the interval will be the maximum of a and B which is 15 and the ending point of interval will be minimum of a and P which is 23 now again I will append it to my intervals 1523 which is here so now again to check which pointer to increase I will compare the ending point of a and ending point of B and if the ending point of a is less than ending point of P that means I will going to increase the pointer in a and ending point of age 23 and ending point of is 24 so I will increase the pointer in a so now again the starting part of interval will be the maximum of starting of a and B is 24 and the ending will be the minimum of ending of a and B now the minimum is also 24 so again we go to our fifth interval which is 24 and 24 which is our this part so again to check the pointer I will compare the ending point of a and B and now ending point of a is geared to the ending point of P that means we will increase the pointer in B so my pointer will come here now again to get the interval so now the starting point of the interval will be the maximum of starting point of a and B and the maxim between 24 and 25 is 25 so the starting point of my interval will be 25 and ending will be minimum of ending of a and B and ending of in base 25 and 26 and minimum of them is 25 so I will take 25 and this will serve as the last interval which represent this part so what are the key things we have to pick from here first to get the interval I will use this part that the starting point will be the maximum starting bit of a and B and the ending part will be minimum of ending of a and B and we will only willing to append in the interval if the starting point is less than the ending point and to check the pointer I will use this part that if the ending point of a is greater than ending point of P in that case I will increase the pointing B else I will going to increase the pointer in a or you can say if the ending point of a is less than the ending point of P in that case I will going to increase the pointer in a else I will going to increase the pointer in me or you can say whosoever have the smaller ending point I will increase the pointer in that so let's move to the coding part and let's see what is the code for this problem so let's see the code at line number 3 and at line number 4 I have pointer a and B which is equal to 0 and I have taken interval which is empty list in which I will store my intervals and I am taking a while loop while I is less than length of a and B is less than the length of given list B and I am defining my interval of starting and interval of ending and the starting part will be equal to maximum of starting of a and B and the ending of interval will be equal to minimum of ending of a and B and we will going to append the starting and ending point in the interval only if the standing point of the interval is less than equal to ending point of in the world and to increase the pointer we will check the ending point of a and P and if the ending point of a is less than the ending point of P in that case I will increase the pointer in a else I will going to increase the pointer in P and at the end I will simply written the interval so this is the code let's see whether it works or not so here I sum in my code and it got septic so this was the solution for this problem if this video was helpful to you please give it a thumbs up thank you so much guys for watching the video please don't forget to subscribe
Interval List Intersections
largest-time-for-given-digits
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
String,Enumeration
Medium
null
225
hello everyone we are solving problem number 225 to implement stack using queues so in this problem we need to implement functionalities of Stack which are push pop top and empty using only Q data structure so we will first take what is the difference between these two structures so for Q it implements first in first out methodology while stack implements lasting for start methodology so this is the major difference between uh these two on this structures while other functionalities like top pop empty are nearly similar so I will just first Implement one queue or declare one queue let's call it q and we will initialize it here in the Constructor we are going to implement using it using linked list so we will first complete this uh simple questions or the simpler functions so in this case we will just say Q dot Pole then in this case we will just say Q dot P these are the similar functionalities so we don't need to think for this U dot is empty okay but for push so when we push any item in a queue so the item which is pushed earlier gets removed from the first while use in queue sequence but while in the stack uh when you push an item and you if you perform pop operation so the element which is most recently uh pushed get popped so this is the uh one uh tricky implementation so for that what we can do is let's take one example let's say we have one two three four in the queue and we need to add 5 but as Stacks logic if we need to perform power operation our file should get popped but uh by Q's implementation if we perform pop operation then our one will get pop as one is added earlier than others so here what we can do is we will add this Phi and we will re-add these elements and we will re-add these elements and we will re-add these elements again from the back so what we will do is we will just simply do this process so we will uh so by this process we will uh maintain the track of which element is getting pushed most recently and which is getting pushed with the uh which is pushed earlier than other elements so we will just do this what we're going to do is we will just push this element that's it add and then what we will do is we will run a for Loop while I is less than Q dot size but you will perform till -1 only -1 only -1 only as we don't need to pop this element as we need to keep it and then we need to react the elements which are in front of on that element from the back so we will just remove first uh length minus one elements and you will we will react them so I plus and what we will do is we will just say Cube that Q dot add Q dot pull so by this process by this function we are removing element from the beginning and then adding it in the end so I think everything is okay let's try to run this code okay it's running yeah 100 faster so I will just explain uh this tip once again so what we are doing is let's say we have one two three in this stack and we are uh pushing let's say a new element X so by this tax logic if we pop in a pop uh if you go from pop operation then X should get popped but by the queues implementation as uh it has original functionality the one will get pop as it is pushed earlier than x so what we will do is we will push X in this queue and then we will push the elements which are main front of X sorry uh again from the back so I will do stepwise okay so what we will do is we will pop this one and we will add it again from the end okay so then again we will pop this two and then we will add it from the end then we will pop this three and then we will add it from the end okay so by this way our most recent elements will get placed uh in the front of queue and if we perform then uh then if we perform uh pop operation for this implementation of Stack then we will get the most recent element so for that we have done this Loop till size minus 1 and we have added the element which are which we are poking popping from the front okay so thank you
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack. * `int pop()` Removes the element on the top of the stack and returns it. * `int top()` Returns the element on the top of the stack. * `boolean empty()` Returns `true` if the stack is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. **Example 1:** **Input** \[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 2, 2, false\] **Explanation** MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `top`, and `empty`. * All the calls to `pop` and `top` are valid. **Follow-up:** Can you implement the stack using only one queue?
null
Stack,Design,Queue
Easy
232
689
hey hello there so today I want to talk about this question 689 marks in the sum of three non-overlapping sub-arrays we of three non-overlapping sub-arrays we of three non-overlapping sub-arrays we have an input array of positive integers and we want to find the three non-overlapping sub arrays within this non-overlapping sub arrays within this non-overlapping sub arrays within this input array and if you add all the numbers from those three sub arrays they should be the maximum possible and there is one thing that this resub er is in common they all have size k consecutive K elements in this sub arrays the K is also input to the problem we want to return the list of indices for their starting positions if there are multiple answers we should return the lexicographically smallest one so the we want them to be as left as possible if we have tied total sum for the elements we wanted the one that towards the left and as much as possible so example we have 1 2 6 7 5 1 the sub array are of size 2 so if we look at the starting index at zero that window that sub array is long and 2 so the total suite if you look at the index 3 the sub array are 6 &amp; 2 the total is 8 3 the sub array are 6 &amp; 2 the total is 8 3 the sub array are 6 &amp; 2 the total is 8 if we look at the index 5 the sub array contains 7 &amp; 5 the total is 12 so 12 contains 7 &amp; 5 the total is 12 so 12 contains 7 &amp; 5 the total is 12 so 12 plus 8 plus 3 we get at 20 23 so that's the maximum and they are multiple there are another possibility is just 1 3 &amp; 5 3 &amp; 5 3 &amp; 5 basically just shifting the first two separate was right 1 2 1 they sum to be the same thing but for this one the lexicographically order it is larger because one is it's larger than zero so visually it will be the if we have physical arrays there visually will be more that's right so that's why we wanted a nursery fire here so some current tea here the lens is gonna be within this range the numbers here are I think it's eight I don't remember eight bits integer and in here the K will be between one and four noms lens divided by three that's just saying that we have to have at least one possibility for four K sub arrays in this array if K is larger than this number then there is no way we can put K consecutive non-overlapping arrays in consecutive non-overlapping arrays in consecutive non-overlapping arrays in the array so that's some guarantee so we will read through this question there is really nothing special about this reading here there's nothing about three that really changes how you just think about this question and actually you can you should expect that this three will be may be upgraded for to four to be a more complex question or downgraded to be one or two to begin with but the end goal is to have a more generic a solution that supports an arbitrary number of non-overlapping sub arbitrary number of non-overlapping sub arbitrary number of non-overlapping sub arrays so if you have a solution that's really doing a lot of special handling of three cases then you will be a lot difficult for you to solve the follow-ups if the generic one is coming follow-ups if the generic one is coming follow-ups if the generic one is coming afterwards so you staff directly thinking about three non-overlapping sub thinking about three non-overlapping sub thinking about three non-overlapping sub arrays we just got to be thinking about this as m and the simplest case for this question will be one none of the lapping sub arrays so how do we solve that so we basically run the window well the window is basically the sub-arrays of window is basically the sub-arrays of window is basically the sub-arrays of size two from the left most locations starting position and just run it slide it towards right we're gonna shift it by want what's right each time the initial one that it has the sum of three and the initial location index to be zero in the next iteration will move it towards right by one the new total is still three so because it's not it's the tie so we just keep track of the first appearance because that we results to be lexically lexicographically smaller another iteration doesn't change anything one more iteration the sub-array now sum one more iteration the sub-array now sum one more iteration the sub-array now sum up to eight is larger than 3 so we update this maximum and also update an index that's that becomes three another iteration we get 13 we change eight to 13 and update the index to for another iteration will get twelve since that 12 is not smaller than the previous maximum we don't do any updates one last iteration so we reach the end of the input array we tried all the possible size two sub arrays of course it's non overlapping with zero sub arrays and we by doing running through the window we get the maximum four for the one none of loving sub arrays of size to the some would be searching and its index will be four so we run one window we can solve the one none of Allah great question so can we just run two windows together to solve the two non-overlapping separate question yes non-overlapping separate question yes non-overlapping separate question yes that's what we're gonna do so initially we're gonna have because they are none of lopping the best case we can do in the very beginning we could just gonna have them side by side we're gonna change this two variables to be index of one index of two which maximum of one a maximum of two this second lie here is gonna be the maximum of two none of the laughing sub arrays it's not the maximum of the second but that posed together so initially this is in the initial case it's 3 and 0 this will be 3 plus 3 and the index will be at a pole of 0 &amp; 2 so that's the initial State and of 0 &amp; 2 so that's the initial State and of 0 &amp; 2 so that's the initial State and in the next year very same we're just going to move this towards right stimuli endlessly by one position the first window will become 3 this first a sub array will become sorry so then we only like then we'll look after the maximum of 1 all we can do is compare this owed 3 with this new sub array so it would be similar to the one window case we couldn't update that in this case for the second sub array you've become interesting the total now the total for our sub array is now 8 and what would compare that with is the 8 plus the current a maximum of 1 because the there's this non-overlapping guarantee there's this non-overlapping guarantee there's this non-overlapping guarantee we can always just add 8 tor for the maximum of 1 there in the same iteration which could be recently updated can be updated to four if we have two here and eight plus three will be 11 and because 11 is larger than the previous maximum six we can update the maximum of two to be maximum of two long overlapping sub arrays this given time to be 11 and the location will be updated to zero and Suite 3 is the starting location for this sub array sum up to eight the second sub array the sum up to 8 3 so that's the picture here in the next iteration we could have shifted the two window towards right by one two sub arrays I use window and summarised interchangeably because they are pretty much the same in this context the first sub array is still sorry we don't week still can't update the first slide but the second line the this submarine comes 13 + 13 + 3 is larger than searching 13 + 13 + 3 is larger than searching 13 + 13 + 3 is larger than searching plus 3 is larger than the previous box and 11 and so that we can actually do the update change the in starting index for the second window a second subarray 204 so the 0 and for those 2 sub arrays the total would become the new total would be become 16 I'm just going to run this through one more time one last time actually the first sub array becomes 8 total there so we update there's to be 8 and the index will be 3 and the second sub array here the sulphur that running sub array here would be second the running sub array will be 12 and when we consider how we whether we should update in this box love to we are 12 where's this 8 with no new maxim of want because then no non-overlapping guarantee this we can non-overlapping guarantee this we can non-overlapping guarantee this we can always if we process this box of one box of 2 in the sequence we can always use this 12 to add the you know max this we don't care about what's actually in here all we care is the maximum of 1 and because none of a lapping we can always use that to try to construct our bigger song so 12 plus 8 which is 20 that's the new maximum it's greater than 16 and to update the indices it's just now 3 &amp; 5 yes that's pretty much it so now 3 &amp; 5 yes that's pretty much it so now 3 &amp; 5 yes that's pretty much it so the tool and overlapping sub-array the tool and overlapping sub-array the tool and overlapping sub-array solution is basically just maintaining two lines here and you can imagine if we are actually working on this three non-overlapping case we just have three non-overlapping case we just have three non-overlapping case we just have three windows here will be three eight and twelve the starting indices for them is one for the current sub array running sliding running sub array it's 1 3 &amp; 5 sliding running sub array it's 1 3 &amp; 5 sliding running sub array it's 1 3 &amp; 5 their distance there their gap is the size 2 here the maximum for the first would be 3 the index would be 0 but that's this one here the maximum of 2 will be 11 which is 3 plus 8 and the index is 3 is 0 &amp; 3 for the 8 a maximum index is 3 is 0 &amp; 3 for the 8 a maximum index is 3 is 0 &amp; 3 for the 8 a maximum 3 and the location in indices of the story would be 11 plus 12 2003 and 5 and that is exactly this simple example sample example 0 certify so just by looking at this if we have M windows we're just going to have M line here each line is memorizing the maximum sum of the first and windows and there are indices for the end windows so we're just going to update that the update rule is basically is going to be the maximum between the previous maximum of 5 and the maximum of I minus 1 we use a bracket to indicate this as indices plus the current window current parent of submarine current to sub array I so that's the update rule and for the indices we just grabbed the indices associated with the max and the max of I minus 1 and just append the starting location for the current a sub array I and we can update the indices so that's pretty much as a strategy it's gonna be sliding and different windows altogether and they are side by side the update is happening by updating the sum of the first our first one some of the first two sweet max in the sum of the first three and so on and so forth so we can do this updating a for loop instead of different our different logic hand-coded our different logic hand-coded our different logic hand-coded hard-coded logics we can just use a hard-coded logics we can just use a hard-coded logics we can just use a looping construct to do that so that's pretty much the analysis then is the actual coding now sorry my voice sounds bad because I'm copying a little bit today early on and but I guess you don't care so we're gonna populate something like the window song which before that the first thing to do is to make the question to be the full opera version M which is the number of windows that we want number for the overlapping windows so what do we do is first we you start up a cockade calculating this sum of k elements and all the time you know whenever we shift the one we need to calculate a new some of the sub arrays we basically do one pass and generate all this in one go and later on we can just grab those instead of doing some extra calculation redundant calculation we're going to call this windows sounds and the I we just grab the sum by the first position for the sub array as the index so in the beginning it's some of the numbers of apollon T of the first decade and then I'm just going to do one loop this is make sure that we have one last window that of size K so it's a instead of you know the last index for that would be lens of nuns plus 1 exclusive decrement by one so that's why we need a plus one and we decrement by K we minus K because the window size is okay so that's the range here we will pen is to grab the previous window a previous solarium and just disregard the discard the previous leftmost element and add in the new element so that the nones I minus one plus I plus K minus one so that's the updates throughout the leftmost the previous leftmost and are the new rightmost and so that we can just whenever we wanted this three eight twelve thing we can just call the windows song with the index number so we don't have to recalculate every time yeah we initializing data structure to store this al-anbar lying thing it's store this al-anbar lying thing it's store this al-anbar lying thing it's gonna be a we can access that by the number of sub arrays we're considering so it's a hashmap with keys being the index being the number of sub arrays we're considering the value is going to be two things a typo or an array of two things which is the maximum sum of the candidate list of indices so we're gonna have that way what are we gonna call it max sums it's gonna be defaulted the default value for those is going to be zero and empty list after that which is going to slide the M windows in simultaneously so we got out the iterator which is going to be the starting location for the very first window so I'm just gonna call it s meaning the starting location for the first suburb of sliding sub array so the range is gonna be from 0 which is the first allocation here towards it would be similar here it's just that the K would be multiplied by M m windows just gonna copy and multiply this by n the number of windows my conserving then we just got to loop through this thing one by one we will grab the Sudbury song you know what I'm already calling this window so you just gonna call this window windows on the go you say index so the first index is going to be as the first windows a starting location will be ass that's why we call this ass but for the eyes window it will be for the second window it will be this S Plus the window size K so since that we're working with arbitrary number the we can just use a variable to do that to keep track of that so it's a s plus I minus 1 multiplied by the window size K so that's the starting position for the eyes sub-array position for the eyes sub-array position for the eyes sub-array running sub-array and we grab the sum running sub-array and we grab the sum running sub-array and we grab the sum instead of actually calculating on-the-fly actually calculate on the on-the-fly actually calculate on the on-the-fly actually calculate on the fryers also fly as also okay but I think this use a little bit extra space to speed up the things but potentially speed up things this pattern danya's just using this formula to do the updates grab the so this windows son here will be the correspondent to the current a sub-array I this same here and we want sub-array I this same here and we want sub-array I this same here and we want to grab the maximum of I minus one so it's I minus 1 and the max is the first item in that so it's 0 if it's greater than the max of I which is using this key now the first element then we just override this maximum with the new maximum and we update the candidate in the say list which will be the indices of n minus 1 the maximum of the maximum for a candidate for the N minus 1 I'm sorry concatenating the this L location that's the updates for the windows so in the end which is going to return the very last ally and return the candidate in the silliest so this n + 1 candidate in the silliest so this n + 1 candidate in the silliest so this n + 1 so yeah so this is the code let me try runs for some examples missing one required position argument and okay let me set a default here which is 3 what the question originally is and say submit so yeah it's working so let's look at the code and do a little bit analysis about the time and space so this Sudbury Sam's is pre calculated the size is a it's obvious the lens minus k plus 1 so it's a and if we have n numbers so that's space and 404 for generating this portion then looking at this data structure here the hash map the keys are the M number M windows the space requirement here is it's dominated by the appended list so the first window yo has you will have for the first two sub array they were it would just have one index number but for the very last one the M it will be M element here and index are there so it's one plus two plus and go all the way up to M windows am summaries I'm sorry they're interchangeable yes you should be okay understanding so it's a M squared that's the space for this data structure for this hash mark it's predominated by the number of index that we want to keep track of so that's what hash map here for this looping condition here it's a outer loop and you know we're looking through all the delenn's - some cost of smaller the delenn's - some cost of smaller the delenn's - some cost of smaller things if they K and M are relatively small the array has this big this is pretty much just out of hand the second loop in the inner loop is all of em so that the time for this is a multi-part the end is the resize m is multi-part the end is the resize m is multi-part the end is the resize m is the number of windows number of race for space there's nothing here so this space is the M squared plus egg and if we want to optimize for space a little bit we can choose to not do this but instead we can put one element in the hashmap to be the window zone to be the running sub-array zone and instead of running sub-array zone and instead of running sub-array zone and instead of doing this calculation just in a one-off doing this calculation just in a one-off doing this calculation just in a one-off fashion here for each of those windows we can instead of grabbing that from the pre calculate result we can just do the subtract and addition here with this index to be some kind of multiple of K and offset it by the S so that can remove the requirement for populating this so dropping the time on our end and the space order so the space will be strictly M Squared but I think that will be little bit more tricky to writing interview time and you have to deal with this s and you know this would be complicated the number of multiple of another loop another thing here the da here another Sam if you decide to do that here it will be S Plus I don't even want to I don't want to talk about that formula but it's easy to get it anyway this is the question it's a generic version solution so we supports arbitrary M and if I look at the analysis is really not about anything different from one or two yeah all the things the area's just did this relationship and that's pretty much it alright so that's the question for today bye for now
Maximum Sum of 3 Non-Overlapping Subarrays
maximum-sum-of-3-non-overlapping-subarrays
Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one. **Example 1:** **Input:** nums = \[1,2,1,2,6,7,5,1\], k = 2 **Output:** \[0,3,5\] **Explanation:** Subarrays \[1, 2\], \[2, 6\], \[7, 5\] correspond to the starting indices \[0, 3, 5\]. We could have also taken \[2, 1\], but an answer of \[1, 3, 5\] would be lexicographically larger. **Example 2:** **Input:** nums = \[1,2,1,2,1,2,1,2,1\], k = 2 **Output:** \[0,2,4\] **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] < 216` * `1 <= k <= floor(nums.length / 3)`
null
Array,Dynamic Programming
Hard
123
1,365
That IPL 2000 Problems In Life In North And Look For Simple Right But Just In The Mid Day To Copy No Optimal Solution 2019 Tricks For Big Problems Sometimes In Talking About Very Similar Problem Only Give Me The Number Of Elements Which Element Hello Friends Welcome To My Channel Please Subscribe Limitations Subscribe To Let You Understand All The Best Worked In Your Mind A Letter To Make Short Were Doing Problems Worth Treating Not Just These Tears And Cheers Elements You Need To Find Out How Many Elements Of Modern Art and happiness is look at and test case number one Vihar second right and benefit amazing to deposit for each element unit of length is long then element number 8 how many elements of moral and even smaller to this model tourism and entry small do not give total Of Elements Right to Unit Two Right Down for Engineers and Robbers next9news Element of Money Please Hello Cooking Hate You Too How Many Elements in the Year-2013 Year-2013 Year-2013 Toll Free Number to Do Subscribe Button and a Remedy Latest Writer Locator Take Care Number Two You Have the Element 65.88 The Element Six How Many Elements 65.88 The Element Six How Many Elements 65.88 The Element Six How Many Elements Confined to a Small Detail 514 Correct Surya Don Too Many Elements of Modern 540 on the right side take a similar diff is number three this for all elements of 7 light to turn off elements of smaller in this case Cancer 20000 not find any problems you for the question a solution subscribe element temple in front of you This Day This Staff Element Twist Comparing Between Element One Spinner Yes Tourism And Yes To Small Royce This Marvelous Gift Total Of Elements Like You Ca n't Stop Writing In This One Moving Forward Element Number One And Welcome Page 89 Tomato Two Is Not Modeler Does not feel left down 0 ki ko ine tube start element number 218 is note maurya vansh smaller two is equal dhund not maurya ko mute only five one element right the twilight wave similar you will get one can you will get over with oo some intoxication and 10 minutes work correctly and will give correct answer every time but problem with a very large for example of no element of light 15909 post office second element and again compete with a pinch of elements to what is happening taking a lot of time to complete all Elements And You Will Not Be Able To Write To Improve The This Lipstick You Sample Are Once Again And Whenever Your Thinking About And Optimize Solution Just Ruler Of Things With Your Intuition How Can You Approach Problem Number Of Account Deficit In The Middle Of The Elements For all elements in early intervention to give you can create a new account of switch of the element in there is not sorted in addition to attract the current account of this element Vivo phone that Tamilnadu Effigy start editing tools are such element Number 8 Right For Themselves Will Increase Discount By One To Have Next Such Element Number One Quarter Me To Family Increment Discount Again By One To That They Will Increase Discount By One To Index Number 2 And Intimate Discount Spoon Way Increment Vikram One Neck Elements Two August 116 Go To Index Number 2 And Instruments Account Increment Discount Welcome To Similarly Phone Number Three Level Increment The Account Index Number 3 A Moving Ahead Like This With Salary Will Welcome Something Like This A Right And What Is Not Telling If You Have 2103 Dos 3251 chhath festival now think what does one you have three to love you have one two three love you have two five say this one fix and you have 182 right now go one step ahead just look at element number two e look to laptop How many element to elements right and right the elements three 500 600 to Tubelight it's all elements and elements in this question you need to find the number of elements of kal su qualified dhul tips hum off switch off button to notification steadims page will give me Two will give two three will give oo the five plus one will give fix 60 will give 6162 e will give 8080 will give oo that 90 tune in airtel a suite 20 number three and what are the telling you mercy simply shading dat this rebellion elements data Model One You Have Two Elements And Smaller Than Two And Than One Right Next You Have Five Elements Latest Model Country Where Two Too Two One Right You Have Fixed Animators Manvendra Hair Oil Officer Ban Sake This Fixed Element 2015 Light Move Ahead With No Limits For All Elements That Pranav One Week Come Up With The Answer What The Tools You Can Start Looking At All Of The Independence And A Value On Thursday Turn On The Question Number Of Elements In To-Do List To-Do List To-Do List Play That And Help Others Will B's answer is a new latest figures how they can write you do this ok hair vihar left side of the screen you can go to intimidation and write sample 15th the water does in the beginning create worked for counting point dry display create but there and Mrs too Frequency of Chief Minister for to get day of the day that Pranav second is telling media have best I have to app 13018 right to connect with they are now what do you know me to the number of moral number element subscribe this Video give 123 K day plus one day i will give you for ur reply flag can forgive and forget and ultimately which power grid now the is tele me data it for events at this month of three elements to smaller than one element smaller than 2 and have elements involved in this Piece of information you can point out that there are no one can run for look at the moon on that similarly phone number to have a look at index stud and will get the volume 181 hair 10101 hair and ultimately or three idiots Please return at a time Complexity of devotion of one provident fund 1020 not mean that fits well into space so I hope life is the problem and solution for new item final moments thank you took advantage of accounting for them and tried to solution important question For Alleged That Can Help You Avoid Subscribe Problem Work Has Not Only Of Elements From Nehru Problem Very Much You Can Apply For Building And This Apni For Bigger Problem Water Measure Pay And Water Tank Withdrawal What Prompted To This Every Thing This Comment Section 2D Attack this channel subscribe my channel friends this video problem and come here
How Many Numbers Are Smaller Than the Current Number
how-many-numbers-are-smaller-than-the-current-number
Given the array `nums`, for each `nums[i]` find out how many numbers in the array are smaller than it. That is, for each `nums[i]` you have to count the number of valid `j's` such that `j != i` **and** `nums[j] < nums[i]`. Return the answer in an array. **Example 1:** **Input:** nums = \[8,1,2,2,3\] **Output:** \[4,0,1,1,3\] **Explanation:** For nums\[0\]=8 there exist four smaller numbers than it (1, 2, 2 and 3). For nums\[1\]=1 does not exist any smaller number than it. For nums\[2\]=2 there exist one smaller number than it (1). For nums\[3\]=2 there exist one smaller number than it (1). For nums\[4\]=3 there exist three smaller numbers than it (1, 2 and 2). **Example 2:** **Input:** nums = \[6,5,4,8\] **Output:** \[2,1,0,3\] **Example 3:** **Input:** nums = \[7,7,7,7\] **Output:** \[0,0,0,0\] **Constraints:** * `2 <= nums.length <= 500` * `0 <= nums[i] <= 100`
null
null
Easy
null
80
Hello friends welcome back and watch this video. Simply Want Justice For This Element 's Daughter Suri Cruise Patient Element From One 's Daughter Suri Cruise Patient Element From One 's Daughter Suri Cruise Patient Element From One Point In This Universe In This Year Now Electric Reached To Of This Day Will Appear In The List Of Elements For Example 123 Subscribe Will Start From Subscribe To With Mayor We Exempted Goods Please Pet Point To Play List Check The Last Not Only Check Subscribe Now To Receive New Updates Time Play List Play One Phone The Last Second Position Verified So What Is Simply Dresses For Class Second Position Started Search This Note To The Police Please My Bhavan Hair Okay Baby I Love You Two Plus Two 9 2009 2013 Finally Bigg Boss Reading and Writing Video Subscribe One Place A Speech At Everything In This Way Can't Have Equal To Zero Track Hussain Saver Of The Number Please Subscribe My Apps Elements President of Ayyappan and Two Elements Means How Plus Debit So Now Simply Set Up Absolutely Free May Next Okay Bad Skin Element Which Is This Band's Play List Number One Position But Last But Not Least Number Two to lucknow wire i want to which is not good luck sid please my to be verified festival looking for land last element please subscribe and subscribe how to fix deposit 1059 liquid course pretty simple is the only thing which assures a peon circle rate On My School Class Select Class Element In Placing Limits And Placid It's A Platform Elements Not Equal To The Last Second Element Severe Good Places Sequence Placid At Its Principles In Good Elements Which Can Simply Chari Net Acid Classification Share I Will Have The Channel and tap on the simply don't see the like subscribe and problem subscribe with oo
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int\[\] expectedNums = \[...\]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\] **Output:** 5, nums = \[1,1,2,2,3,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,0,1,1,1,1,2,3,3\] **Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\] **Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order.
null
Array,Two Pointers
Medium
26
724
hey everyone today we'll be doing another lead code problem to uh seven to four point pivot Index this is an easy one given an array of nums calculate the pivot index of this array is where the sum of all the numbers tricky left of the index equal to the sum of the all the numbers at the very right and if the index is on the left edge of the array then the sum is going to be 0 to the left the sum left sum is going to be 0 because there are no elements on the left this also applies to the right return the leftmost pivot index if no such then returns minus return minus 1 so we have an array like this in which we are going to return the pivot index of pivot index at this point is going to be this 6 because the sum at the very left of the index is this is going to be returning 11 and this is going to be returning 11 not including the pivot itself so what we can do is just make a left uh some variable and a write some variable so the left sum obviously starting from the very first they said like it is 0 and we are not going to include the pivot in our index uh pivot the index itself which we are considering a pivot and not in our sum so one will not be added in neither of the right or left so right will be just the sum of the whole array but minus 1 because we are at uh zero index and one is at the zero index 28 is going to be the sum of this whole list and if you minus 1 we are getting 27. then we will we are this is our pivot and now we will just move our pivot and add before moving our period we are going to add that add the first index to the left one you can say and now when we go in the next iteration we will remove it from the right one so we will check left and right are not equal to 0 we will move our pointer to or our pivot to the next and then 7 is going to be added here so it will be like 8. and now 3 will be decremented from here and the private will move to 6 and 3 will be uh it was decremented from here and it will be incremented here so it will become like 11 and now 6 is going to be decremented from here because we are at six we are not going to include 6 and we are at 11 and 11 so at this point at this 6 we are going to have 11 left sum is equal to the right one so we are going to return 3 in that case because the index of 6 was 3. um Okay so left is equal to 0 and the right is equal to the sum of nums okay so for index and element in numerate in nums okay so first of all we have to decrement our right with the element okay now if the right is equal to left we are going to return the index in text okay and after that we can just decrement or not decrement just increment our left by the element and that's it if you are going to find it then we are going to return the index otherwise we are going to return minus 1 so that was it that's it if you have any kind of questions you can ask them in the comments
Find Pivot Index
find-pivot-index
Given an array of integers `nums`, calculate the **pivot index** of this array. The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right. If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array. Return _the **leftmost pivot index**_. If no such index exists, return `-1`. **Example 1:** **Input:** nums = \[1,7,3,6,5,6\] **Output:** 3 **Explanation:** The pivot index is 3. Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11 Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11 **Example 2:** **Input:** nums = \[1,2,3\] **Output:** -1 **Explanation:** There is no index that satisfies the conditions in the problem statement. **Example 3:** **Input:** nums = \[2,1,-1\] **Output:** 0 **Explanation:** The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0 **Constraints:** * `1 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1]. Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
Array,Prefix Sum
Easy
560,2102,2369
200
well it's another death first search problem you know you want it you know you came for it you can't live without it here we have number 200 number of islands so this says given an m by n 2d grid map of one's land and zero's water return the number of islands an island is surrounded by water and is formed by connected connecting adjacent lens horizontally and vertically you may assume all four edges of the grid are surrounded by water okay um well this is as if you just stepped in the mediterranean and they say hey uh identify uh naxos samos kefalonia rhodes lesbos yes that's where lesbian comes from let's go there and of course the biggest greek island crete okay so you have these ones and zeros and whenever you see a bunch of ones connected horizontally and vertically that's kind of one island so this is kind of one big island here which is what they give one island whereas here you have kind of these four ones in a bunch then this one and then these two so then there's that's three islands so they're asking you to count the islands so this is a depth first search in which we're going to what we're going to do is kind of iterate through the 2d grid and every time we see a 1 we're going to go down as far as we can with the ones either vertically or horizontally and we're going to flip those ones that we're going to turn them into an s character and incidentally i think yeah they should have made this a character symbol instead they made it a string symbol over here kind of the double quotes whatever in any case um every time we see the ones we're going to convert them to s's so that we don't look at them again and but before we start our dfs we're going to increment our count by one and that's it at the end we're just going to return our count so first a little sanity check if grid as per usual if grid is empty then return zero okay then we're going to come up with um an int my count which is zero and this is the new c plus i think they call it universal initialization and at the end we're gonna return my count so let's iterate down this grid so four into i equal zero i smaller than grid dot size i plus and now we're going to have our int j equals zero j smaller than grid zero dot size so these are the rows j plus okay so as we go in so okay so our check what we're going to do is eventually have some kind of magic dfs function which is going to convert them into s's so we don't want to see s's as well so if we see a 1 we're in if we see a 0 or an s we don't go down the dfs so in fact let's just call it dfs so um if grid uh grid i j equals one yeah as a matter of fact that's how we could do the check then we start the then oh first we need to increment my count and then we could go down the dfs so let's send it the grid let's and let's send it our i and j coordinates and actually i think that's it isn't it i think that's it we won't have to do anything else after that okay let's uh let's get down to this so we have this is our dfs function in which we're going to throw in our grid because the count we don't need to pass it in we as soon as we see an island we iterate all the way down and we can increment the count beforehand before getting in the dfs so we're throwing our grid by reference since we're going to modify it and then we're going to throw in i and cons and j okay now in this function here um okay now if we're going too far so all we want to do is just go in and as soon as we see more ones we just flip them to s's so that we don't see them again as we're iterating down the grid so let's see now so if i smaller than zero or let's use this c plus or which we can right now or j smaller than zero or i bigger or equal to what is this grid dot size or j bigger or equal to grid zero dot size or um or so okay so if we got that far that means we could check grid i j not equal to uh what is this not equal to one uh yeah one if it's not equal to one then we just return we came to a bad square so if we're yeah if we hit an s or a zero then we just get out of there otherwise we just set grid we just set the grid i j equals s for scene so if it's not equal to 1 then we don't care about it and then we just uh kind of move along in the dfs so dfs we're going to send it the grid and then we're going to send it i and j every time so okay so there's four different combinations we're doing i plus one i minus one and we're doing j plus one and we're doing j minus one so going up and down left and right and let's see if this miraculously works run code wrong answer expected one when it saw a one here so what's this problem we got into if it saw one it should at least increment my count oh wait okay so this is a one character that's so idiotic that's a one character and let's make sure that we saw that let's run that again okay now it worked let's submit that and we have a winner thanks a lot everyone have yourselves a very good day or night whatever time it is over there
Number of Islands
number-of-islands
Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return _the number of islands_. An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. **Example 1:** **Input:** grid = \[ \[ "1 ", "1 ", "1 ", "1 ", "0 "\], \[ "1 ", "1 ", "0 ", "1 ", "0 "\], \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "0 ", "0 ", "0 ", "0 ", "0 "\] \] **Output:** 1 **Example 2:** **Input:** grid = \[ \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "0 ", "0 ", "1 ", "0 ", "0 "\], \[ "0 ", "0 ", "0 ", "1 ", "1 "\] \] **Output:** 3 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 300` * `grid[i][j]` is `'0'` or `'1'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
130,286,305,323,694,695,2035,2103
701
welcome to october's leeco challenge today's problem is an insert into a binary search tree you are given the root node of a binary search tree and a value to insert into the tree return the root note of the binary search tree after the insertion it is guaranteed that the new value does not exist in the original binary search tree now notice there may be multiple valid ways for the insertion for example if we were to insert five into this binary search tree we could insert it to the left node of seven or we could restructure the tree added to the root and make four go into the bottom here on the right side of the three node i would say ignore this just makes it more confusing just look at this binary search tree insertion and think about how we would write our algorithm now one of the things i realized is i've worked with binary search trees quite a bit but i actually don't know how to do this which surprised me but if you simplify this idea as simple as possible like let's just say we have the number five we know how to traverse the tree right we could say if five is greater than fourth and go to the right if seven is uh or five is less than seven go to the left and so on and so forth that's only when we find that there's no more nodes that we should do the insertion we should insert five here but say that we have the number 2.5 for but say that we have the number 2.5 for but say that we have the number 2.5 for example i know these are all integers but just for example say we have the number 2.5 example say we have the number 2.5 example say we have the number 2.5 we go left and then we would see that 2.5 is between 2 and 3 right 2.5 is between 2 and 3 right 2.5 is between 2 and 3 right so one of the first thoughts you might have is oh then we should you know restructure this to have 2.5 here and restructure this to have 2.5 here and restructure this to have 2.5 here and then 3 to the right but we don't need to do that actually because of the way the binary search trees are structured there always will be one level at the end where we can insert our value especially because we know that it's unique there should be some child at the very end some sort of leaf that we should be able to insert it at the very end whether it's to its left or right and still keep the structure of the binary search tree so because of that this really is not that complicated what we're going to do is write a function and we'll just call it insert and we'll pass in the root or we'll call it node as well as the value now usually with these sort of binary search tree problems we have like a base condition but you'll notice that we'll actually don't need that here um and i'll show you why so if the value is greater than the node's value then what do we want to go to the right side right so we'll just do the insert and go to the right otherwise we know that it's less so we're going to go to the left side all right so where do we do the insertion well here's the problem we actually need to insert it when we're at the node right we can't insert when we're at a null value so it's not this base condition that we want to put we just want to check here if node.right is if node.right is if node.right is null so if not node.right this is where null so if not node.right this is where null so if not node.right this is where we just insert it into the node so we say node.right is just going to equal node.right is just going to equal node.right is just going to equal tree node of this value and then we just end right there so we can just make this an else and continue on forward like this same thing here if not node dot left and make the no dot left equal to tree node value otherwise we keep traversing and do the insert here so this is recursive but notice that the base condition comes in the code here rather than up here so that i thought was interesting but that makes total sense right so all we need to do then is run our code insert the root and value and then just return the root after we're finished now one edge case if the root is blank we still need to create a node for the tree so if not root we're just going to return the tree node of this value because that is now going to be the root all right so let's see if this works and it looks like it's doing what we want uh this is the example we've been given and you can see five has been put to the uh left side of seven here i think well um i guess we can just take a look see how it looks and yeah so five is at the left side of seven this correct let's go and submit that and there we go accepted so when i first saw this problem it kind of worried me because i wasn't sure i've never seen this before it might be complicated but as soon as i realized you know we can always insert this value into some sort of leaf at the very bottom it becomes very simple so great thanks for watching my channel and remember do not trust me i know nothing
Insert into a Binary Search Tree
insert-into-a-binary-search-tree
You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST. **Notice** that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return **any of them**. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[4,2,7,1,3,5\] **Explanation:** Another accepted tree is: **Example 2:** **Input:** root = \[40,20,60,10,30,50,70\], val = 25 **Output:** \[40,20,60,10,30,50,70,null,null,25\] **Example 3:** **Input:** root = \[4,2,7,1,3,null,null,null,null,null,null\], val = 5 **Output:** \[4,2,7,1,3,5\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-108 <= Node.val <= 108` * All the values `Node.val` are **unique**. * `-108 <= val <= 108` * It's **guaranteed** that `val` does not exist in the original BST.
null
null
Medium
null
1,547
everyone welcome back and let's write some more neat code today's today let's solve the problem minimum cost to cut a stick and to be honest somebody at leak code really needs to put down the crack pipe because we are given a wooden stick of length n so far so good the stick is labeled from zero up until n so just like you know a meter stick or something like that and we're also given an array of cuts which tell us where we are going to perform the cut so for example we could cut here we could cut there we could cut here but then they tell us we should perform the cuts in order and also you can change the order of the cuts as you wish and at that point I just stop reading the description because it's probably not going to help you understand the problem so let's actually look at the example so let's say we're given n equals seven and these are the cuts now they tell us here that if we try to just perform the cuts in the order that they're given we do not end up with the optimal result and by the way every time we perform a cut so for example one we're going to be cutting right here every time we perform a cut we take the length of the stick that we just cut which in this case is seven zero up until seven and we add it to like the cost we're trying to calculate the cost of cutting the stick with all these cuts and where not only that we're trying to minimize that cost so in this case no matter which one of these Cuts we do first I mean the length is of length seven so we're always going to have a plus seven here next let's try to perform the three cut so these are our two sticks remaining suppose we do the cut here what's the length of this portion of the stick it's length six so then we add a plus six to our total cost next try to do the four we cut here the length of this portion looks to me like it's also four so then we say plus four and lastly we do the five on this portion which is of length three and then we end up with these sticks we don't care about the sticks we care about the cost so we add the plus three here total we get 20 was the cost now there's different orderings that we could have done the cuts in and this happens to be the optimal ordering first cutting three which again would give us a cost of seven then cut five rather than cutting four because it kind of divides the stick into evenly sized portions rather than cutting it here which would leave us with a one but then also leave us with a three over here so cutting here first gives us a cost of four not bad then do one over here the length of this portion is three so we get a plus three and then lastly we do the four cut the length of this portion is two so we ended up I think with a cost of 16. so clearly doing it in this order is minimal but if we try to Brute Force this we'll have to pretty much try every permutation of cuts I think that's roughly n factorial and that's not going to be super efficient so let's see how we can try to optimize this problem and first let's just kind of understand how we can even think about this problem at all like how could we even Solve IT recursively even with a Brute Force approach well let's consider the choices that we have we know we have a choice for every single cut we could cut three first we could cut at five first we could cut at one first or we could cut at four first I redo it just to make it a bit more clearer that these are like the cuts that are happening but what kind of value are we going to be maintaining let's suppose we did the cut on three we knew originally the length of our stick was seven now that we cut three obviously we're gonna have two different sticks at this point it looks like we're gonna have a stick of length three and we're gonna have a stick of length four and we need to then recursively go in both directions so basically every time we perform a cut we're actually not creating one branch for that we're creating two branches um maybe I'm not drawing it super clearly but that's because it's kind of hard to visualize but notice how like saying okay now the length of the stick here is three the length of the stick on this side is four that's not really enough information because now if we try additional Cuts like we try to perform a five cut here a one cut a four cut we don't know does that cut actually apply because if we're cutting at the five Mark we can't cut like this stick at the five Mark and this stick of length four we can't just cut it at some arbitrary spot we have to cut it at this particular spot we have to know that's where we're cutting it and it's going to be split into two sticks of length two so rather than keeping track of the length of our portion let's keep track of the range of it so initially we're at a range from left equals zero to right equals seven so that gives us a more clear definition of the sub problem that we are currently at now the other thing is let's suppose we did cut at three it's pretty easy for us to know what the cost of that cut at 3 three was because we just take the length of our range we could take right minus left that gives us the length so that's easy enough but now that we already used the three now from here we're probably going to make some more choices right probably these choices we still have to do the five cut we still have to do the one cut and we still have to do the four cut so should we be keeping track of that cuts array and like dynamically removing from it as we already perform a cut you could try it that way it'd be kind of complicated to do it but notice that it's actually not really necessary in the context of this problem if we perform a three cut and now here we try to perform four more Cuts again including the three cut if I try to do the three the five the one and the four the three cut is not really gonna do anything anymore because we know after we did the cut here we actually ended up with two sticks from zero to three and then another stick from three to seven so you can try cutting this stick at the three Mark like this stick over here you can try cutting it here it's not really doing anything you can try cutting this stick at the three Mark it's not really doing anything so basically there's an easier way for us to know that this cut is unnecessary and that's basically every time we try a cut let's at least make sure that cut in this case three let's at least make sure that cut is greater than the left boundary and less than the right boundary in this case three is not greater than the three and less than the seven this does not apply therefore this cut does not apply to this segment and also the one cut over here also wouldn't apply to this segment of the stick so therefore there's an easier way for us to know that this branch is not going to do anything for us and also the one branch is not gonna on this portion of the stick and the five we're would not do anything on this portion and the four would not do anything on this portion of the stick so that is an easy way to simplify this problem and believe it or not those are really the two points that you need to keep track of to solve this problem even though this is a hard problem it's actually surprisingly not super insane I guess the hard part was trying to understand what the hell they're asking for again the two points are that we're keeping track of the range of our stick and that we're just going to be looping through all the possible Cuts determining if a cut actually is valid for that portion of the stick or not and that will be enough to solve this problem especially when we apply caching to it because you notice that the sub problem itself is very simple we don't even need to keep track of this as part of the sub problem we simplified that part we only need to keep track of the range and there's going to be two values left and right the possible combinations of these two values are going to be n possibilities for left because it could be any of these values same thing for right so the number possibilities is going to be N squared now we are going to be looping through the cuts array each time so I believe the overall time complexity is going to be the length of the cuts array let's call that M multiplied by N squared where n is given to us as a parameter so now let's code this up so remember we're going to have a recursive function I'm going to call it DFS the range of our sub problem is going to be defined from left to right and immediately let me show you how I'm going to call this I'm going to call DFS starting from 0 going up until n which is the parameter given to us and I guess this is one thing I didn't talk about what's going to be the base case for this problem possibly where the length of the stick is equal to zero possibly where left is equal to right well is that technically possible is it possible for us to cut this stick in such a way that we get a length segment that's of equal to zero not really so we're probably never going to call DFS where the two left and right boundaries are equal it wouldn't really make sense the base case would basically be if none of the cuts apply to this segment and we don't necessarily know that until we iterate through the list of cuts but there is one case where we do immediately know that and that's when the length of our segment is equal to one so basically R minus left is equal to one and in that case we would just go ahead and return zero let me add the If part to that here so that's the main base case we're going to have another base case for the caching case but for now I'm just gonna code this up the Brute Force way so remember we're trying to minimize the cost so let's initialize the cost to be a really big value like infinity and then let's start going through every possible cut in the cuts or right now how do we know if this cut applies remember if the cut is greater than left and less than right and in Python you can do that with like a single equality like this but maybe in other languages you can't now how do we calculate the cost well the cost to cut this stick was right minus left plus now let's run DFS on the left portion of the stick which we can get by taking the left pointer and the cut position because that kind of tells us now where the end of that stick is going to be and let's also call DFS on the right portion which is going to be from the cut mark up until the right pointer and remember we're trying to minimize the result so let's set result equal to minimum of itself and this portion which is the recursive case of course so after this our result will be minimized now technically there is an edge case what if none of the cuts actually apply like we never even executed the recursive case result would still be infinity and that's probably not what we want to return so maybe we can set result equal to zero if it's still equal to Infinity that basically tells us that we could not cut the stick just like in this case otherwise we leave it as the result and then here we return the result so that's pretty much the entire code and believe it or not it actually does pass on leak code and you can see the time complexity is not going to be super efficient actually this won't pass on lead code I forgot to do the caching so let's make sure we do that which is usually pretty easy just a few lines I'm going to create our DP cache in this case I'm going to use a hash map but you could probably use a two-dimensional array I'm probably use a two-dimensional array I'm probably use a two-dimensional array I'm going to check has this key already been computed and if it has go ahead and return it like this if it hasn't let's go ahead and compute it which basically means we're Computing the result so before we return the result let's also make sure we add that same value into the cache which I'm just doing in a single line sorry if this is confusing because there's multiple assignments being made this is being assigned to result and result is being assigned to that and then we're returning the same value so now let's run this to make sure that it works and as you can see yes it does and it's somewhat efficient I think there's a slight optimization that leak code made in the editorial but I think the overall time complexity actually can't really be improved no matter what you are going to need a loop inside of the recursive function if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has a ton of check out neatcode.io it has a ton of check out neatcode.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon
Minimum Cost to Cut a Stick
destination-city
Given a wooden stick of length `n` units. The stick is labelled from `0` to `n`. For example, a stick of length **6** is labelled as follows: Given an integer array `cuts` where `cuts[i]` denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Please refer to the first example for a better explanation. Return _the minimum total cost_ of the cuts. **Example 1:** **Input:** n = 7, cuts = \[1,3,4,5\] **Output:** 16 **Explanation:** Using cuts order = \[1, 3, 4, 5\] as in the input leads to the following scenario: The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20. Rearranging the cuts to be \[3, 5, 1, 4\] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16). **Example 2:** **Input:** n = 9, cuts = \[5,6,1,4,2\] **Output:** 22 **Explanation:** If you try the given cuts ordering the cost will be 25. There are much ordering with total cost <= 25, for example, the order \[4, 6, 5, 2, 1\] has total cost = 22 which is the minimum possible. **Constraints:** * `2 <= n <= 106` * `1 <= cuts.length <= min(n - 1, 100)` * `1 <= cuts[i] <= n - 1` * All the integers in `cuts` array are **distinct**.
Start in any city and use the path to move to the next city. Eventually, you will reach a city with no path outgoing, this is the destination city.
Hash Table,String
Easy
null
539
hello today we are going to take a look at question 539 minimum time difference in this problem we are given a list of 24-hour clock time points in our minutes 24-hour clock time points in our minutes 24-hour clock time points in our minutes format and we need to find the minimum minutes difference between any two time points in the list let's take a look at example one so the time 23 hours 59 minutes and 0 hours 0 minutes is one set one minute note the number of time points in the given list is at least 2 and I won't exit to 20,000 the input and I won't exit to 20,000 the input and I won't exit to 20,000 the input time is legal and the range is from 0 hours 0 minutes to 23 over 59 minutes ok so how are we going to solve this problem first let's take a look to solve this problem there is no algorithm to apply just the procedures so first we will need to so we're given a list right so we will need to put all convert all the time in two minutes so and put it in to our new list then we sort them so first minutes time lists so second we sort of a list sort of a minutes time list so third we get a Jensen adjacent difference in our sorted list and then we find the minimum difference so this is how we are going to get our answer okay so it's step by step then let's take a look at how to do each steps so first step to create our minimum time to create our minute time list okay to do that first we have to know how many minutes in a day so this formula tells us it's 1440 minutes in a day okay so we first create a magic number called ten minutes one go further okay why we need to do this because sometimes we need to use this value to get the difference because the difference is not just simply miners sometimes okay so the second step is after we get this there is there are two exceptions we have to consider so let's say the first exception is that the list we are given as all the numbers all the time points we in a day so if that is the case and there must be two to duplicated time points in that list therefore we will just return 0 Thanks there are two time points they are exactly the same so there is no difference so the minimum difference is zero and there's another problem is that if the time the length of the time point is 1 so that what will happen is that so there's only one time points therefore we return 10 minutes since there is no other time points after that one so there is no that is not a good case but now I look at this sentence it says the number of time points in the given list is at least the two therefore I don't think we need this exception okay that's moving on so now we are going to create our list new list with time and we need to create a variable which is our answer eventually it's the minimum difference so the minimum difference we first the curator the biggest number as possible so we give it this now it's time to put our time points convert them and put it in all times so we iterate through the time points so first we have to deal with one exception which is the time is equals to zero at that time we should not give zero to append zero to our new list instead we have to depend the ten minutes the reason why is because we needed so we need the minimum difference therefore when it's when it comes to zero we use that we can if we use their own which sorry the result we get will not be the minimum therefore we need to choose the so another expression of this time which is the ten minutes so cycle it's like how to say it like 12 p.m. is exactly the same as zero a.m. so after this we just continue things or process so this time has been processed so if the time is not this we need to do we need to and extract the over and the minutes out from over time which we split it by step of this so we get our hour and minute number then how are we going to convert it to minute so we are now 1 over consisted of 16 minutes and at the minute so we get we converted that we get the converted form now we add this into our new list ok our new list have the converted time okay now it is time for us to sort it after we sorted it we have to iterate it one more time things because so we have already finished step 1 and step 2 and now we need to do step 3 which is we have to get a chance and difference so the way we get it is we just iterate through it and keep getting the pageant's and difference and then we compare this adjacent difference with the minimum difference if it's smaller than the minimum difference will be replaced by this different stuff in that case so the minimum difference will get lower smaller and smaller then eventually we'll get the smallest difference okay now after this can we just the return minimum difference the reason is so the answer is we can't why because the minimum difference we get so we sorted the new list but there's one more saying we have to check which could be the minimum so the smallest time for them boots let's say one the biggest let's see 10 so we had 2 3 4 5 6 9 so there will be a case the number the difference between this is not soft so it's the smallest I don't know how to give you an example but sometimes that will be the case when you convert those time into time minutes lists so sometimes this will be the case therefore that's one thing we need to do is we need to get the difference between the first number and the last number of our new list and of course sometimes the time is sometimes the number is not so if we get the number simply sometimes it is not the case therefore we need to add the 10 minutes since it's already I don't know because we need to get the minimum minutes difference therefore we need to check this so after this then we can start return if this T is bigger than zero usually it will bigger than zero bit well but usually it won't smaller than minimum difference else we will just return minimum difference of course yes so the tricky thing is a lot of people they forget to check this depth so I'll think of an example of why you have to check this example so it's we have already sorted the minimum list and it's from the smallest to the biggest but if we - it and its last ten minutes but if we - it and its last ten minutes but if we - it and its last ten minutes yes because sometimes for damp Oh hmm so ten minutes is one four zero so for example the first number is one and the last number is one four zero so we know so one four three no just one four zero so we know this is very small so their difference is very small so don't make I'll make it clear for them po the first the smallest number in our list is one the biggest is one four zero so we know the difference between this two is one right so it could be the smallest difference but if we just attract the adjacent difference we will miss it the further orders this the second number we carried back three four or five you name it then we will get the minimum numbers too but the truth is this the difference between the smallest number and the biggest number is our minimum difference therefore we have to consider this
Minimum Time Difference
minimum-time-difference
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Array,Math,String,Sorting
Medium
2266
283
we will have pointer J to go through each index and check for non-zero each index and check for non-zero each index and check for non-zero numbers and we will have pointer I to replace all the zeros with nonzero numbers identified by pointer J and to set Zer at the end of array here value at J pointer is zero therefore we will move on now J pointer is at a non zero value therefore we will assign this value to the I pointer and then increment the I pointer again J pointer is at a zero value so we will move on now 3 is non zero therefore we will assign it to the ey pointer and increment ey pointer 12 is also non zero therefore we will assign it to the I pointer and increment the I pointer now we can assign all the elements being visited by I pointer to Z this is the final result now let's code the solution we will set pointer I and J to zero initially we will use J pointer to iterate through all the elements in the array whenever we find a nonzero value we will assign it to I pointer and increment I pointer after that we will assign rest of the elements to zero let's run the solution it's working see you in the next video
Move Zeroes
move-zeroes
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3,12,0,0\] **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you minimize the total number of operations done?
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
Array,Two Pointers
Easy
27
404
welcome to august liko challenge today's problem is some of left leaves find the sum of all left leaves in a given binary tree you can see we have a binary tree here and a left leaf is while a leaf on the left side so it's got no children and it's coming from the left we want to sum them all up so here 9 and 15 are the only ones and we'll turn 24. so to solve this problem i'm going to use a deferred search and what i'm going to do is traverse the entire tree and only start checking to see if we are on a left leave at the very end so just a normal dfs what we'll do is pass in the node and we'll say if not node return and otherwise we will call the node.left and the node.left and the node.left and the node dot right now here we need to have some sort of checker to see if that this is a leaf or not so we could just say if not no dot left and not no dot right we will increase our total by the no doubt value so we're only going to add up to children here we'll have some sort of self variable on top and we'll start with zero but one thing to note we need to know if we're on the left side or the right side and we're not gonna be able to tell that from the note itself we're gonna have to keep track of where we've been passed from so to do that i can just pass another variable here i'll call it the left and when we're coming from the left i will make that equal to true and if we're not we'll make that equal to false and that is going to be an extra check here and left that's going to make sure that we only add up the left leaves finally we just need to call this the root and we will pass in false because we're not coming in from the left technically so we're just coming from the root so that's going to be a false finally at the very end we just return the self.total and that's it's a pretty straightforward problem let's go and submit that and accept it so main trick here is to realize that since at the node we're at we're not going to be able to know if we're coming from the left or the right we have to pass that along and once we realize that everything else is pretty straightforward so that's it thanks for watching my channel and remember do not trust me i know nothing
Sum of Left Leaves
sum-of-left-leaves
Given the `root` of a binary tree, return _the sum of all left leaves._ A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 24 **Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively. **Example 2:** **Input:** root = \[1\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
1,027
hey guys how's everything going let's continue our journey to lead code yay I'm Jay sir who is not good at algorithm today we will look at 102 7 longest arithmetic sequence given an array a of integers return the length of the longest arithmetic subsequence in a ok so 4 3 6 9 12 out of them are arithmetic sequence right so the longest will be in the whole array four nine four seven to 10 a long case would be 4 7 10 yeah an example 3 like this will be longest will be 20 15 10 5 well let's analyze some basic examples if the elements the input will be longer than 2 so if there is only 2 elements like 3 6 of course the longest will be the whole array and if there is 3 6 9 of course 3 6 9 let's define what is this arithmetic sequence well the sequence will have a characteristic that the increment is the same right so 3 plus 3 is 6 plus 3 is 9 plus 3 is 12 so actually the element is start annamund plus the increment but actually define the whole Earthman arithmetic set sequence right and the increment is defined by the top two element right if we have the top two elements like this and we can just edit check if nine is in the fall in the rest elements and we find a line we can check if 12 is the nment thus for each two top two elements we can use extra linear time to detect the longest arithmetic sequence and how many top numbers are there well into the end to the square n right so totally we can achieve we can tackle this problem by and to the cube of time complexity right we just start with any top two elements and just to do the iteration to check the next possible animate well sure let's just try to start so the idea is start with all possible top two elements and they use a linear time to check the longest sequence Wow let for the yeah for the start if the input is only two elements we can just return to right or we can just mmm I think we can just ignore it mmm no because yeah I think we're just a filter out the special case if a tenth is two we turn to right so now at least there will be three elements okay now for the now we next loop through the array with a two round to determine the top two elements so the first a loop ends at the sediment right so smarter than one now we can get to the top elements with AI with hij so the increment will be AJ minus AI so now we can look through the rest numbers J plus 1j smaller than 8 up then k plus K and how will we check we will find the next impossible and next target right we have the enemy increment we have the second element and we can calculate the next element and just do the search right yeah after we get it we can update to the next target and continue our search with one patch just to be just in this for loop so I'll say the next target would be AJ plus increment for this K if a K is next target add weaned and do we need to set the net current longest then our with I'll just use these nests because we already have to write so current is 2 and if we find a target what we do plus a current and update it oh we forgot to define that the max okay and we need to update to the next target increment and finally we return the max so actually this is this should work cool let's submit yes we are accepted and the faster than 60% of the input and the faster than 60% of the input and the faster than 60% of the input let's analyze the time and space complexity a time we use of two for loop here and another for loop to check the possibilities so obviously it's in to the cube space we haven't used any extra space so it's constant so this is our solution but could we improve it we have done this a lot of times if we want to improve it we need to analyze our input analyze our naive solutions like this one is and to the cube right like we have assists to analyze this example - first we are analyze this example - first we are analyze this example - first we are we get to start with two six and then we run into nine and update the max and then run into twelve right and then we got to nine there's nothing matted and then two and a six nine okay here's a problem first three six nine twelve we've already Travis two six nine right and now we have because it's actually part of the longest arithmetic sequence we now will with Travis six nine twelve again well this is a necessary check right so what if we have when we travels first time when we go to Twitter three and six and we can cache the result of the check from six nine twelve which means in next time when we go to Six know of what if we get when we start three and a six we all reach however the six in an up in a traversal for it and cache the results say we have a longest string have a longest I have a longest arithmetic sequence I'll finance three with the increment of three if we have that information when we are checking them this number three we will just because the stiff the difference between three and six is three so we can get the result immediately without extra this for check so thinking backward is a little confusing let's just try to understand our previous solution in without rather than calculating the start point it's basically a symmetric so we can think of the problem as ending right so if we treat think this for loop as we choose the two ending what ending positions for the longest arithmetic sequence like the first we will get to six wow it's too sick itself and then two nine three nine well is 3/9 and then two nine three nine well is 3/9 and then two nine three nine well is 3/9 off and the six nine okay we're gain is six nine because we've already traverse three six it's two with three and three plus six plus three is nine self so we can get the results right away so now we can have we have the chance to catch the intermediate result right so the problem becomes what is the longest automatic sequence ending at each position the longest one absolutely will be deducted with this math max so that's a side effect we don't need to care so we don't we need to catch the result for each point so the data will be like cut the data we want to cache is actually a combination of one the increment and that is to the longest currently a current longest length right cool now let's do that so the idea is cache the result for off of this increment and the current longest then ending which ends at index right let's say if that is F so the increment my increment might there were been a lot of these kind of combinations right so actually this will be a map if I will be a map of what type of increment longest death right so fi plus one will be what now let's say we have all the this fi for a through two three six nine now we have a new one fi plus one what do you what it is it will be suppose the supposed 9 is in the array right so suppose line is together with this 12 there are two possibilities one there is nothing ending at no prayer no previous longest arithmetic sequence ending at nine if that's the case we can just say there is a new possibility at the start at nine right so it would be living criminals - and no you increment B a criminals - and no you increment B a criminals - and no you increment B a minus a plus one - we just say new map a I - right if what if a I passed no previous sequence of AI plus 1 - increment - increment - increment with a I mean so the increment with these two numbers are fixed to three so we just need to check if nine has previous arithmetic sequence with the increment of three right so if there is we just said we just there we just add twelve in it if there isn't we just add I'll add it add a to a right so if there is it would be a I minus a I and previous one so this will be for AJ F J get AI minus plus one minus a I mean this is the increment mmm okay I'll say this is in cream looks rebels but you know what I mean get this I plus one right well this is not as simple as it is it should be four this is not I a I am sorry it should be j okay because each of the previous element would be possible so for J and 0 - I also the cut so the relation is - I also the cut so the relation is - I also the cut so the relation is unclear let's start writing our code okay let's first though that the cache will be of course array of maps so I'll create a cache I'll say current longest currents on the gate longest sequence map at okay use this cache and now we're gonna loop through each element you start would be four for the first one there's nothing there so we first we push the first element first cache will start with a six so one equals so there's only one possibility right so new map the increment would be a 1 minus a 0 then this would be too cool so the though so the loop will start with I from to write the 1 is already set it here so I'll remove this one so according to our methodology here we will do what we will for let we will start with J from 0 and J will be J was more than that I and J plus and free which means for each this right and then we will check the increment right the increment will be a I minus AJ now the first one okay for I forgot sorry the first one would be the first one will be empty ray yeah new map so we just to check if there is previous record so it means cast previous equals previous ight previous map @j okay I use previous ight previous map @j okay I use previous ight previous map @j okay I use this first map equals this with J now if this has increment which means just a pen has add the new element as one possibility right if you already have the increment so okay I'll create a new set for current so car and map car map is here god sure so current map I'll say set increment with previous map increment of course it's get house one right okay for all the art cases if there's nothing there maybe we could just add a new one right and a new top two elements for sequence so it would be two and don't forget to update the max let max equals two here max equals math max this oh I'll say I'll cash it let's run the code hmm oh it's not working let's debug for three six nine twelve okay we increment the first one is empty oh sure the second one is this too right we start with nine and net nine self I'll here is mistake we should end at the last one right this is different from previous for loop so I made a mistake sorry mmm-hmm Irish my house undefined ah I'll I forgot to push sorry quote I submit well I think we are little we have improved a little yeah and cool now let's analyze the time and space complexity as you can see we use a for-loop eat24 loop and the see we use a for-loop eat24 loop and the see we use a for-loop eat24 loop and the process here is actually a bunch of set of map direct access right a skier said so the time complexity would be improved to and to the square space it's basically too complicated first we have n and affordab no n elements so the map array will at length n and for each one what's the worst case I think for the worst case would be that we every time we add a new news a new wait a minute when you a new entry right so the rest case is all the elements are different and so for I for index I their worst case is and I minus one entry to map I so the space would be actually and space would be a sigma some okay so actually 0 plus 1 plus 2 plus the data so it's au and square so we've actually trait have a trade-off here we actually trait have a trade-off here we actually trait have a trade-off here we use extra end Squarespace for the improvement from and cube to the N square so that's a that is our solution to solutions hope it helps see you next time bye
Longest Arithmetic Subsequence
sum-of-even-numbers-after-queries
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`. **Note** that: * A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. * A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`). **Example 1:** **Input:** nums = \[3,6,9,12\] **Output:** 4 **Explanation: ** The whole array is an arithmetic sequence with steps of length = 3. **Example 2:** **Input:** nums = \[9,4,7,2,10\] **Output:** 3 **Explanation: ** The longest arithmetic subsequence is \[4,7,10\]. **Example 3:** **Input:** nums = \[20,1,15,3,10,5,8\] **Output:** 4 **Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\]. **Constraints:** * `2 <= nums.length <= 1000` * `0 <= nums[i] <= 500`
null
Array,Simulation
Medium
null
322
welcome to march's leeco challenge today's problem is coin change you are given coins of different denominations and the total amount write a function to compute the fewest number of coins that you need to make up that amount if that amount cannot be made up return negative one you may assume you have an infinite number of each kind of coin so if we had coins one two five we would return three because two five coins and one coin would be the least amount of coins to get eleven now on the surface this looks like a very simple problem um in the beginning we might think like we could just sort our coin denominations and then do a while loop subtracting the largest denomination first and then trying to see if we can get the amount here so here we'd get one five coin two five coins so now we have one left and we move here and we have one coin so that'd be three coins right but that wouldn't work because of certain situations like this where we have let's say one four five if we had eight coins if that algorithm would be the same we would take five here and then we take three one coins which would equal four but we know that we can do four twos and that would be two coins that should be the minimum so we need to keep track of um the number of coins that we can make at each point so really that solution won't work we'd have to go with something um either recursive or dp and i'm going to go with a dp solution what we'll do is create this into sub problems and have some sort of dp array that contains the numbers all the way up to 8. what we'll do is just have some infinite max number here i'm just going to call that let's say negative one but assume that this is infinite and what we'll do is um see we keep track of the index points so this is uh zero amount one two three four five six seven eight something like that and basically we'll check for each coin denomination oh we need one more here how many coins would it take to fulfill that amount so here we'll start with uh one coin or i'm sorry we'll start with the amount zero we know that there's no amount of coins that we can make to make you know um zero amount so this would just be zero immediately now we have the amount one right so out of these three coins we run a for loop if we use one then we could create it with one coin right what about four we can't deal with five either so this would all be the same up to like two three four something like this but once we reach four uh we know that we could have four ones but we should also check one four and we know that's gonna be the minimums so that can be changed to like one four coin five wouldn't be work now what about at five here we'll check to first see five ones that don't work okay so five ones we'll update that now what about four well we obviously can't make five with four but we could make um we know that we could add one four here and then go back four spaces to one see how many coins that it took to make one that's going to be the minimum here and add that so we know at five we can have one four coin and use one coin here and that would equal two right so that gets updated to two and that's uh the algorithm how that algorithm works we like look backwards to see the minimum amount that we can make minus that coin amount and see if that's minimum if we if it is we're going to update it so hopefully that sort of made sense what we'll do is create a dp array here i'm going to start with making these all infinite values because we want to get the max value and we'll say 4i or whatever four blank in range of length of amount we'll also need to add one here okay so we have a steep array we need to make the very first value zero so we'll do that here now for let's see for i in range of length of dp we are going to run through all our coins so for c in coins if this i minus c is greater or equal to zero that means we're in bounds so we could subtract the coin amount from our value here we're going to update our i to be the minimum between ppi or dp i minus c and then add one which is the coin value right now that we're at so if this is less then we're going to update it otherwise uh we'll keep the old one so at the very end we should have our dp amount for this number that we're trying to get the amount which would be the very last index in our dp already now one thing to note we want to return negative one if it's an infinite right because that means that we weren't able to form that amount uh if i made this negative one here it wouldn't work with this algorithm so what i have to do is say if dp i minus 1 is equal to float infinite then we'll return negative one else we'll just return the amount right there all right so let's see if this works objects has no length here oh okay i don't need length here i just get the range of amounts plus one i think all right so that looks like it's working let's go ahead and submit that and accept it so time complexity wise it's going to be of n which is um the number amount here times the number of coins so let's say that's c times n now i did see that there were some recursive solutions that did the exact same thing but were way faster when we run an elite code i'm not entirely sure why that is because time complexity wise should be the same it could be that forming this array here takes a while especially if the amount is large i'm not entirely sure so feel free to put that in the comments if you know why but otherwise this is the um sort of accepted solution for this problem it's a very classic one all right thanks for watching my channel and remember do not trust me i know nothing
Coin Change
coin-change
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`. You may assume that you have an infinite number of each kind of coin. **Example 1:** **Input:** coins = \[1,2,5\], amount = 11 **Output:** 3 **Explanation:** 11 = 5 + 5 + 1 **Example 2:** **Input:** coins = \[2\], amount = 3 **Output:** -1 **Example 3:** **Input:** coins = \[1\], amount = 0 **Output:** 0 **Constraints:** * `1 <= coins.length <= 12` * `1 <= coins[i] <= 231 - 1` * `0 <= amount <= 104`
null
Array,Dynamic Programming,Breadth-First Search
Medium
1025,1393,2345
735
hello hi guys good morning welcome back to the new video and for sure if you have salt or if you have watched our live contest stream which we do every week if you have watched it for the past one month then for sure try this question but I also because you should be able to do it because I have told you this exact same question like kind of same question in the live stream for sure do it try it by yourself but now unless I will pronounce it with her asteroid Collision it's a very standard problems like Collision kind of problems are kind of standard they just have three four variants two variants we have already told in our live streams it is same one such one of the one of those two variants which you are seeing right now cool um we are having an array of asteroids of integers representing uh asteroids in a row uh for each asteroids the absolute value represents its size and the sign so basically we have an array of asteroids right so every asteroid has some value let's say minus 40 or 40 um or let's say 15. so 15 will represent the size 40 will represent the size and minus will represent the direction minus will say left and plus we'll say right cool now uh find out the stays of the assets which means asteroids are just moving it is just the moving States now we have to tell after all the collisions are done and see the position will happen between two asteroids so two F2 asteroids meet and for sure when these two will meet then only the Collision will happen so when the two asteroids will meet force or the smaller one will be explode and if both of are of same size then both will explode cool now just that okay we have to know the state after all the collisions which means after my all asteroids meet with each other so for short I know is ultimately if the asteroids will collide then for sure they have to meet if they have to meet then for sure some condition will be there so I'll just see okay what all asteroids will not meet and whatever asteroids will meet cool uh so if two asteroids meet what I will do is I will make all the cases of when the two asteroids can meet for sure the examples can help you but yeah we quickly jump onto the logic because we know we have to just make the two asteroids meet and ultimately if some asteroids it remains ultimately after even after meeting then for sure it will be in my final answer after collisions and if it just gets finished then for sure it won't be in our answer after Collision now what I can do is I can start off very easily so in the starting itself I have let's say any asteroids moving right or moving left if some asteroid is moving left then for sure it will keep on moving left and no way it will gonna be Collide and ever with anyone because for sure it's moving left right so in the starting of and for sure now you will see okay Arena starting when I know that I have to take this so in what data structure shall I take I know I have to return a vector but should I take a vector or for doing the operations so one thing you know for sure that as you are pushing an element every time you encounter an element so basically you will be pushing this element in a data structure for the for example this element when you will get the you know okay it's never gonna have a collusion so for sure you will push this element in some data structure what that title structure can be we have to see and also when we know when someone who is coming left and for sure in between let's say someone was coming right so we know one thing also for sure that we need to pop one of these because it is right it is left so one will pop out so for sure we know that a few elements we will push in a few elements will pop out so maybe at the run time itself I should be able to push and pop the elements who are remaining let's say for example right if this is if this was bigger and this was small so for sure it will collide and for sure it will remain so for sure uh one needs to pop so by this itself I can know maybe I can use a stack or something like that okay from the end I can remove an element I can push an element from the end it can be the stack either it can be a DQ it can be a vector or any data structure you want let's take it as a stack itself and for sure if it was the first time of you solving it that season I told you about the intuition of stock but going forward please have at the back of your mind saying that the Collision problems can either be straightforward or via stock start is 90 of the times used in cooling out of problems cool now coming back to the first case if it is at the very starting and if it is moving left it will keep on moving left so for sure we don't need to do anything if it is empty and if it is negative then just push that in the move start and push that element and when this is it is the asteroid of I push that in your stack but if it is positive and for sure if it is moving in the starting now you will say again if it is positive then for sure it can have a collision yeah it can have but provided if later point of time someone is coming left right now it can't have collision by just a straightforward scene it can't have Collision so for sure I will assume that whosoever is moving right will not have Collision but whosoever will move left later on will actually can impact Collision so for these moving right I'll just say okay uh it won't cause Collision so for sure if it is empty so now we saw if it is empty either if it is a positive or negative just push that in your stack okay one case done now other case for us was to know okay if it was moving just right now for sure if it is moving right we know it won't cause Collision because it is moving right so for sure if it is positive then please itself it wasn't starting when it is empty so we know we can push both of them either possible negative but yeah we also saw okay if it is positive even and we know the positive ones won't cause Collision because we ultimately thought the negative ones on positive will cause solution so we just assumed okay because one will cause a question on the other so here we assume the positive ones will not Constitution and the negative ones coming forward will cause Collision you can also do vice versa and make your cases a bit more efficient by that but they are simple now ultimately what will happen is maybe the negative one come now you know one thing we took one case starting case we took okay it is positive we do okay now it is negative if it is a negative it can cause correlation but let's say if it is negative which was coming in Left Right it has some value if the values which is the one which is coming in left is Big the one which was actually in the left so the one which is coming left it is this element it is Big the one which we have already in the left it is small then for sure big one will collide with a smaller one and the smaller one will get removed and you know everything which means everything which is in the left is actually in the stack itself already so for sure as the big one is coming in it he knows that he will collide with the smaller one and smaller is going to finish so what will happen is I will just say okay if my stack the top which means anything which is in the stack itself if it is positive which means it is moving right and also if it is less which is smaller in size then for sure it's gonna be removed so I just simply remove it but this process will keep on going until I have smaller elements and also the elements moving right in the stack itself so I will just simply apply a while loop on this okay smaller elements moving right keep on removing it until you have the condition that okay they are smaller in size with the one which is coming in left for you it is coming in left and for sure you know one thing the values of this particular is actually negative so please make sure that you take the absolute value off here so you will write absolute of asteroid of I because ultimately I am concerned I know okay it is a negative one which is coming in by the direction but now I'm concerned about the sizes so please take the absolute value now coming okay and now we saw okay if both of them had if the one coming in left had the bigger size and the one which was uh in the start which means it was coming in the right has a smaller size but what if they both have same size now if they both have same size based on the question both will get collided so the while loop will not come in picture if they both have same size because if both have same size for sure both will get collided so no one will be there to actually make Collision for the remaining part of the start right so if both have the same size if both and again here it will be absolute if both are the same size please simply pop it and simply stop it so it will not be a while loop it will just simply be if Loop now what if this coming left has a smaller size if you're a smaller size and if it is bigger size and if you already know that it is already in the stack if it is a bigger size it's a smaller size then simply you just remove this which means it was incoming in it was the asteroid of I you just removed it and it is already it was already in the stack it will still remain in the stack cool no worries so nothing you have to do as such or you can simply pop it and push it again but still no worries no effect as such on this particular element of the stack but lastly let's say if it was going in going and going in the first case as you going in and what if it completely exhausted all the elements of Stack which means ultimately what if the stack becomes empty again it came back to the first case that okay if the stack becomes empty and if the element is coming in as left simply push that element so for sure if it is coming in s as if and the stack is empty simply push that element but what if the next element although we saw here the element which was the next to him which means it if asteroid was I was the incoming element and the element in the top of the stack was actually a element moving right so we just did the Collision but if the element at the top of the stack was actually element moving left itself so for sure it will keep on going left so ultimately no Collision so please again push this asteroid of I if the elements in top of the stack are actually moving left so if the stack top is actually negative which means stack top is actually moving left so please simply push this element because it's also a negative element which is it's also a element moving left simply push that element and by this you can simply make out the cases of when the Collision will happen and when it will not and how the Collision will affect the existing stack top and that's only simply the case you have to solve in general in this kind of problems quickly see the code uh firstly we'll simply go on to entire Vector from left to right uh simply as we go on we will simply say as we saw if it is empty even if it is moving left or right simply push it or if it is moving right then simply push it so if it is empty or if it is simply moving left or right oh sorry if it is empty or if it is actually positive element simply push that in the stack now comes the part where actually this element is coming in as F which means the asteroid of I is actually a negative element for sure we know I will keep on removing from the stack provided the element at the top of Stack is actually moving right and also its value is smaller than actually the incoming element it's moving left so if it is the case I will simply remove Elements by while loop but if they both have same size so if they both have same size then I'll simply do a if conditions and remove the stack like I simply remove the element of the above the stack which means standard pop but if I still have the element which is negative coming in and stack is empty simply I'll just simply push it or if the stack top is already a negative which means moving left then also simply push it because I can't simply pop anything out so in this case I simply pushed it down now we have all the elements at the top of the stack right because here we are moving from left to right we are moving and we have portion the top of the stack now as we will pop it out which means as you will get the final elements after Collision remaining so what we will get is in the vector as from right to left right because it is the first last and first out so I'll just simply push in the elements like this but simply I again want in the same order from left to right so I'll simply have to reverse it down or maybe what I can do is I can simply push these elements which means the stack top I can push it at the last and then it is the second lesson so on and so forth anyways you can do so here we just have all these stack elements posted in this kind of order last element at the last location this element at the last location by this moving at the from the last index onwards and by this simply getting the elements which are actually meaning after collision and simply return that in the better and the form of result you can simply use the vector also a DQ also and stack for sure but stack is more intuitive to actually solve it pop a top uh push that kind of concept right time and space both o of n because for sure you are using a stack space stack time simple linear stuff going on that is all uh the code is see that's actually very standard so please remember that this that kind of thing is used and we have gone through Wireless stuff you actually started doing things
Asteroid Collision
asteroid-collision
We are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. **Example 1:** **Input:** asteroids = \[5,10,-5\] **Output:** \[5,10\] **Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide. **Example 2:** **Input:** asteroids = \[8,-8\] **Output:** \[\] **Explanation:** The 8 and -8 collide exploding each other. **Example 3:** **Input:** asteroids = \[10,2,-5\] **Output:** \[10\] **Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. **Constraints:** * `2 <= asteroids.length <= 104` * `-1000 <= asteroids[i] <= 1000` * `asteroids[i] != 0`
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
Array,Stack
Medium
605,2245,2317
41
what's up guys this is my two first video we gonna solve the famous problem the first missing positive it's usually asked by the top tech company like amazon okay so let's move to the description okay so given an inserted integer array nums uh find the smallest missing positive integer so let's take some examples the first example we have this array of one two and zero and the first missing positive integer is three move on to a second example in this case the uh the first missing positive integer is one okay so let's think how can we solve this problem okay one important thing to notice is like we have at most n elements it's the length of the array so the result will be between one and n plus one as the n is the length of the array so uh for this first example uh the first missing positive integer is one and one is between one and n plus one in this case we have uh four elements so n is equal to four uh n plus one is equal to five so the result 5 is between 1 and n plus 1 5 in this case okay move on now to a brute force solution would be like if we use two nested loops and try to figure out the first missing positive integer to the array so like it's important to remember that the result is between one and plus one so we will use two nested loops the first loop will uh loop between one and n plus one and for each possible result we will check if this possible result exists in the array or not so if this elements is equal to the possible result so we will return it else we will return n plus 1. and this solution is a big o of n square of time complexity but let's think about a better solution on how can we reduce the time complexity to big o of n of time complexity but this better solution it will be a big o of n of space complexity okay the idea is to use data structure to save the different elements so like instead of like looping through the different elements and in each case test it like we are going to save the different elements that exist in the array into a data structure and test on them so the idea is to use a set okay so if we have this array one three the set will be one three and the first missing uh number is two okay this is uh the pseudo code of this solution so we will loop through the different elements of the array and add them to the set and the second we're going to loop through the different possible results and tests if this results exists in the set or not if yes we may need to return it if not we will return n plus one since the result is between n and n plus one but let's optimize try to optimize our solution okay i came up with this solution how can we achieve this the idea is to mimic the set functionality okay but how we are using the array and an important thing to remember another time is that the result is between one and plus one so and uh it's important to remember also that we can access any element of the array within a constant time so how can we use the these two points to solve our problem to achieve a big o of one of space complexity the idea is to use the positions within the array since the result is at most between one and n plus one and like if we have like any possible number we will like tag the position of the value of the elements the array and to the negative value so for this first example we have one and three we will go through the different elements we have one so we will go to the element of index one and we'll we will assign the negative version of it okay so one second we will go we will move forward this is the second element so we will assign again the negative version of this position so it's also minus one and finally uh we can move forward so three so we will assign the negative version of the element at the third position of the array minus three and finally we just need to loop through this array and to return the first the position of the first positive element in the array is at the position two so that's the result in this case but we have some pre-processing parts we have some pre-processing parts we have some pre-processing parts that we need to verify so we may need to like be sure that the elements or the elements are between like one and the length of the array else we may need to solve this problem using some other solution okay so we may need to like test if one exists or not if yes so we will pass else will return one since it's the two first positive integer and we will loop through the different elements if the element is equal or less to zero we will assign the value of one instead and if the element is bigger than n also we may need to assign the value 1 to it okay so this result we will find that 50 is bigger than 3 the length of the array we will assign 1 and -5 is less than 0 and -5 is less than 0 and -5 is less than 0 so we will assign one to and finally if we will execute the same algorithm to this array we will find that 2 is the first missing integer and exactly that's the case okay let's move to the implementation so we may need this to solve it okay this is an online python compiler okay so let's create our solution class let's create a our function the famous first missing positive function that needs an array let's parameter okay the first thing that we may need to do is to get the length of the array to a separate variable on the test and to test if one exists or not and to test if we have an empty array okay so if not nouns we will return one okay the second thing to do is like to like change or elements uh less or equal to zero or bigger than n to 1 okay so we may need to loop through the different elements okay and to test if the element is equal to zero or the elements we can so less or equal the element is bigger than n so we may need to assign one to this element and then after doing this we will move to the main part so we need to loop through the different elements again okay so let's get the absolute value of this the element so if so absolute value okay like one or two and then we need to assign the negative version of the value at the position one so because like of the shift of the indexes i might need to assign the negative version of the elements and finally we just need to find the first positive element and to return its position okay so finally we may need to loop a third time through the array and test if the element is greater than zero so we may need to return its position we may need to add one because of this shift else if like uh we didn't find the possession we may need to return n plus one sense the result as equal to at most n plus one okay let's execute this by creating a new instance of the solution okay and try to use some relevant examples if like okay let's test another example an empty array using some negative members okay all right with capital s okay great so for the first example the two first missing positive number is two like we have one so the first element is two for an empty array so uh the two first element as one for this example with the negative elements or elements bigger than the length of the array for in this case we will have three on the first element that's correct so thank you for watching and i hope you liked this video
First Missing Positive
first-missing-positive
Given an unsorted integer array `nums`, return the smallest missing positive integer. You must implement an algorithm that runs in `O(n)` time and uses constant extra space. **Example 1:** **Input:** nums = \[1,2,0\] **Output:** 3 **Explanation:** The numbers in the range \[1,2\] are all in the array. **Example 2:** **Input:** nums = \[3,4,-1,1\] **Output:** 2 **Explanation:** 1 is in the array but 2 is missing. **Example 3:** **Input:** nums = \[7,8,9,11,12\] **Output:** 1 **Explanation:** The smallest positive integer 1 is missing. **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
Array,Hash Table
Hard
268,287,448,770
1,267
hello everyone so in this video we'll go over one more problem from lead code the problem is count servers that communicate so let us go over the problem statement directly the problem statement goes like this that you are given a map of a server center represented as an m cross n integer matrix that is named as grid now where one means that the cell there is a server and zero means that there is a no server as you can see in the diagram so there is a grid that is given to you in this first example it's a one two by two grid and uh one means that there's a server add here in the first row so this is the first row second row okay and the first row in the first column it is one server and the second row second column there is one more server fine now it is mean that two servers are set to communicate if they are like if they are on the same row or on the same column so two servers can only communicate that in that way return the number of servers that can communicate with any other server cool so just find out any server that is in a communicating state that can communicate to any other server it doesn't matter which server but it can communicate to any other server and if a server is that is isolated cannot communicate to any no other servers then you have to neglect that now in this example as you can see this server cannot communicate to any other server like there is no one more computer on the same row or in the same column like same for this uh now if you come down to this computer can communicate to this as well as this company could communicate to this and this communicate computer can communicate to this similarly for this server can communicate to this and vice versa this will communicate to this vice versa but this cannot communicate to anyone and thus it is left out so total number is the number you have to print out is how many servers can communicate okay so as you can see that is four now what you can do here is that in this grid that is m cross n grid you have to output that how many servers can communicate you can pause of this video try to think over of your own how you can do about for this problem it's not too much difficult you can directly see that the main intuition for this problem is that you have to see whether there are more than some computer on the same row so you have to find out for like how many computers are there in the same row and save column can you think over that in that direction first you have to easily find out how many computers are there in the same row and same column fine and then what you can do next is for every computer you just have to check that if this computer is in a community state or not communicating stakeholder state or not how you can check that for a particular computer to be in a communicating state there should be at least one more computer in the same row in the same column then only you can take that as in a communicating state or it's not so that's a very simple observation if i can just draw it out for one example if let's take you have a grid like this and just randomly draw out some computers okay so let's say that one computer is here and one computer is here uh that's it okay now these computers can communicate with each other uh this computer will not so what you will do here is that you have to first make a map like two vectors that is one for the column wise and one for the row wise then what you can do is you have to fill that how many computers are there in the particular row okay so uh for this as you can see i'm talking about this so there are four points four these are the four uh as you can see uh columns first column there are two computers or servers whatever you can say there only one there is actually here in this line there is one there is zero and the first line also there is zero similarly for uh as you can see for this line there is zero for this line there is one for this line it is two for this line it is one okay now you can iterate over every so you can actually cut it like generate this how you can generate this like you can do this is o of n square you can iterate over every point and update it in the same like in the uh what you can say column as well as in the row okay for like you can iterate over this whole matrix and whenever you find out the server you can update that there is a particular server and update the particular row as the as well as column fine after doing that what you'll do in the end you'll again do an o of n square or of not n square exactly of n into m because it can be different you have to read over the matrix again and what you will do you have to check that whether i want to take this server whether it is in a communicating state or an isolated server if it is a isolated server or not if it is communicating state they should be at least like two like more than two computers because this is already taken i have to find out that there is at least one more computer in the same row okay in the same row or in the same column now that can be said here because we can just check that whether there's one more computer so there is one which means that there is no computer in the same row but there is one more component in the same column so i can take that similarly i'll iterate over everything and when i come to this it will tell that there is only one computer in the in this particular row and only one component in this particular column so i cannot take that similarly just count all of them and then print it out that's the whole logic for this problem nothing much more let us move down to the actual uh code port part of this video we'll first find out the dimensions of the grid okay make a row and column that is row for coro and column for column and then what you'll do is over the whole matrix of the whole matrix using two for loops nested for loops and just check that whether a particular grid is giving a server if it is giving a server what you'll do you'll update the particular row as well as column increase by one because everything is initialized with zero and then you'll increase by one just thus finding out the column frequency and the row frequency how many servers are there and then total is the total amount of servers that are communicating state again it right over the whole grid okay so another condition is if the particular grid is one which means that there is a server down there also and either of them is true either there is up in this particular row is greater than or equal to two which means that there are more than two computers in the particular row or there are more than two computers in the particular column and it is in a or state but it is and with this condition i hope you get the point so this is like a condition you have to satisfy if this condition is satisfied the total will increment by one that is there is a server that we are on that is in the communicating state take that and in the end print that answer so i hope you get the point how we have write down the code for this problem as well as the logical part so thank you for watching this video till the end i will see you next one till then keep coding and bye
Count Servers that Communicate
remove-zero-sum-consecutive-nodes-from-linked-list
You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers that communicate with any other server. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** 0 **Explanation:** No servers can communicate with others. **Example 2:** **Input:** grid = \[\[1,0\],\[1,1\]\] **Output:** 3 **Explanation:** All three servers can communicate with at least one other server. **Example 3:** **Input:** grid = \[\[1,1,0,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,1\]\] **Output:** 4 **Explanation:** The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m <= 250` * `1 <= n <= 250` * `grid[i][j] == 0 or 1`
Convert the linked list into an array. While you can find a non-empty subarray with sum = 0, erase it. Convert the array into a linked list.
Hash Table,Linked List
Medium
1618
1
hello everyone welcome to another one of my lead code videos and this one we'll do lead code one two sum and I'll try to make this a little bit more beginner friendly because it is likely that a good percentage of you watching this video are just starting out on lead code so yeah let me help you start out your journey and provide you a good explanation for how to solve this problem so the question is basically we are given an array of integers numbers right so as an example we have 2 7 11 15. and we're also given a number Target right so in this case like Target is nine and we are going to return the indices of two numbers that add up to Target so indices are basically the indexes of the array so the first element is index zero the second element is index one and so on right so we have to return the indexes in a form of array of the two elements that sum up to Target right so in this case we return 0 and 1 because if you notice 2 plus 7 so sum up to 9 and what are the indices of 2 and 7 it's 0 and 1. right so that's why we return 9 and they say we can return the answer in any order so it could either be 0 1 or 1 0. and just one more example for completeness sake if we have this every three to four and our Target is six in this case 2 plus 4 is equal to 6 and the indices of that are 1 and 2 respectively so that's why we return one two and obviously we can assume that we have exactly one solution so we don't really need to handle the case where we can't find this or there are more than one answers right so how do we go about solving this problem so I've written the array again here just for example sake now one way to solve this problem is you know we take each element of the array and compare it to every other element until we find the sum that is equal to our Target right so for example first we take two and then we try two plus seven and then we try two plus eleven and then we try 2 plus 15 and you know if we still don't find the sum then we move on to the next one and then we try 7 plus 11. 7 plus 15. right and if we still don't find it then we move on to the next one and then we try 11 plus 15. right so we don't need to try the ones previously because they would have been tried when we were running through those so overall what will be the how many operations will we do in the worst case if we were to use this algorithm right so the first one will be compared to n minus 1 other elements right so it will be n minus 1 elements you know to be compared for the first one the second one will be compared to n minus two elements right so we'll try n minus two pairs right and so on until the last one is only compared to one element right so until one so this is the summation of 1 to n minus 1 which is um just equal to n times n minus 1 over 2. and this basically is going to be like N squared over 2 minus one half so this these this is the number of operations we'll end up doing in the worst case right so it's N squared over 2 minus one half and in terms of order it's a N squared algorithm right so it's a big O of N squared algorithm because as our n increases the number of operations will you know increase as a square proportion to the N right so this is a kind of you know good initial solution that will get us the correct answer because we'll keep comparing all the possible Pairs and once as soon as we get a target of like our whatever Target T's we'll just return those indices right but the question is can we do better like how can we optimize this solution so to optimize the solution like you know let's say when we're taking the first element let's say number two we know that we already know the Target right so we know that we're looking for some number X which will equal to the Target so let's say the target is T right so there's only really one number here where because if you solve for x that would be T minus two right so there's only really one number that will satisfy the value of x that we should look for in the entire array right so which is going to be T minus 2 or T minus the whatever element we're comparing right so really our only the question we need to ask is you know is there an X in the array right so is X present in the array and if yes what is the index of X right so what kind of data structure allows us to do this in efficiently right so if we have a data structure where we have a map a hash map right so if we have a hash map of the number n to the index right then we can create a hash map of this array so we can see like two you is the key and the index is the value is going to be zero seven is the key the value is one 11 is the key the value is 2. and 15 is the key the value is 3. so now once we have this hash map this is just going to be Crea we can create this hash map in on time right because we just need to iterate through the array once to be able to create this hash map right and once we have this hash web then we'll iterate through the array again okay now for number two do I have already uh T minus 2 in the array and then we'll find for example if T was 9 we find oh yes we have seven index one so we just returned that right and looking up something in the hash map is o1 because it's a you know it's a hashed data structure so it allows us to efficiently look up each element so now we'll be doing n operations to populate the hash map and then another n operations going through each of these and finding T minus that X whatever that X is at each index in the hash map right which is another n operation so it's going to be two n operations and that is or just an order of n algorithm which is much better than our previous N squared algorithm because this algorithm just grows linearly as n increases versus the other one would go grow by like a square proportion as n increases so now let's go ahead and just code this solution so we'll start out with our map of integer to integer which will be our element to Index right this is the map we said we'd create first and we'll just go through each element in the nums array so we'll say well I equals 0 I less than lumps dot length I plus so this will create a loop from 0 to the last index of nums and here we'll just say LM to index dot put the element so the key will be our element which will be num it's at I and this should be nums so the it will be num set I the element and then the index which is just I right so this would populate our hash map for all of the element and then what we need to do is just again go through the nums so we'll just again iterate through the nums and now you know our X which is basically what we need to look for is going to be Target minus n right so whatever n we're at we should look for Target minus n and then you know if our LM to index dot contains X so that means if we have X in the hash map then we should get the index of X so we'll just re so we'll say index of X is equal to LM to index dot get X and our current index will be the index of n so we actually need to uh create a index based Loop here so we have an index based Loop here and our X will be Target minus nums at I right because that's our number at this element and then here the index of I is going to be just I so we'll just return here new and I comma index of X that means we have found our pair right and at the end if we aren't able to find anything we'll just return an empty array but we are pretty much guaranteed here that we won't reach this case because they guarantee exactly one solution so hopefully we'll be able to return something we won't run into the case where we end up here so let's run the solution see if it works and then we'll do one more optimization before we close the video so we actually have a error here because you know in this case we have three is in our map and then we saw six as the target but then you know three and three add up to six but you can't actually use the same element twice so yeah this was actually the optimization I was going to do but turns out that we need to do that optimization so what we'll do is we'll keep populating our map and instead of doing this logic over here we'll just move this into the upper Loop right so before we insert it into the map we'll put this logic here so basically we'll say okay this is our X which we're looking for have we seen this before right so have we seen Target minus nums at I before right so if we have seen it before we get the index and return it otherwise if we haven't seen it before we insert it in the map so that something in the future can use it so this will guarantee that you know we don't use the same number twice because we aren't putting it in the map until then unless we have checked if a previous one is matching right and we would we don't return and only then do we return if a previous one is matching so the current one won't be considered twice so now let's run the code hopefully this works all right this passes all the test cases and let's submit perfect so this is an accepted solution thank you so much for watching I'll see you in the next video cheers
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
142
hey everybody this is larry this is day 19 of the lead code daily challenge hit the like button hit the subscribe button join my discord let me know what you think about today's forum this problem is link list psycho 2. so the second one is that the one with the pointer uh yes we're learning the note right okay yeah so what is negative one nick what is it just return none yeah i think it just returned none right oh do not modify wait no we're not modifying it given that we turn the node okay we turn none okay fine it's actually the first line i just read it backwards okay yeah so this is the one way you have to actually do a return um first of all i think the first thing is um you know you don't know how to do this uh or at least how to do the first step of detecting a cycle definitely go i think there is a previous problem with is just detecting a psycho um we'll go over it really quickly but you know you get two problems at the same time as opposed uh if you haven't done it yet but the idea is that the idea is that you have two pointers uh there's a couple of names that go by this but basically you have a first point and a slower pointer and then if there's a cycle so the only two cases right there's a cycle and there's no cycle if there's a cycle then you venture they'll catch up uh let me actually pull up paint real quick let's see oh that was already up huh that's awkward but uh anyway yeah let's say you have uh you know some node and you know there are only two cases right one is no cycle no psycho is kind of obvious if you have two pointers uh eventually you know this goes to none right uh eventually you just go outside and then you'll reach a nun and then you're happy you're good you're living your life and there's no cycles however if there is a cycle if there's a cycle right then eventually um because of i guess do i want to say induction but the idea is that you have one point that moves twice and then one that goes one then here let's say you start with here um yeah let's say you start here and then after one step you have one pointer here and one pointer here right after two steps you would have one pointer here and then the other one would have gone two more here right so then the idea is that the fast pointer um the fast pointer will gain one will basically gain one once um uh it enters the loop right what i mean by that is that every iteration every step that uh the slower one takes the fast one takes two so that eventually will catch up to it because of i guess is it induction i don't know but like let's say the distance between them is x after one iteration will be x minus one and so forth right so that's basically the idea behind that and that's um to be honest it's one of those trivia things i don't know if you could come up with if you haven't heard of it before but i just feel like it's one of those things that um yeah it just becomes like people just know about it right and when people know about it that it's so common uh i don't even know if it's a interview question anymore because it's too common to be an individual question but that's the idea right and then now uh the idea is then okay let's say there is a cycle right there's a cycle um you have to try to figure out where the starting point is um there are a couple of ways to kind of represent this as a system of equations is how i want to think about it um i actually don't remember this particular part with respect to like the formula or the code so we'll try and see if we can prove it from scratch so this part may be a little bit murky and if so then you know feel free to uh feel free to watch my card um uh fast forward watch on uh faster speed or so forth so okay let's say there's a cycle right what does that mean that means that's the slow pointer uh let's say hmm how do i want to represent this uh yeah let's say the slope let's say there's two parts right a uh let me bring up paintbrush again hang on maybe that's a little bit easier for a quick visualization uh but yeah let's say you have this and then let's say the part before the cycle is let's use another color let's say the part before this is a and then this part um and then the part where they meet will be b right let's say they meet here i don't know this is just an example let's say they meet here right then that's b um what does that mean right um then here we can kind of try to figure out the formulas is what i was going to say and let's see if we can do that right so the slow pointer would move a plus b just by definition um so in this case i think one observation to know here is that um the slow pointer will not make one full cycle through because like i said no matter where the fast pointer is let's say the fast point let's say the length of the cycle is equal to c um and the fast point there is one space ahead right or c minus one space behind if you want to put it that way that means that it will take c minus one um iteration to go right and of course in that case the slow point it would have only might move c minus one case so it would never make one full cycle just an observation right um i don't know if it's a useful observation but it is an observation because like i said i'm trying to um try to prove this by uh from scratch and figure it out right so yeah so then the faster pointer of course it goes 2a or 2a plus 2b um and then there's another way of phrasing it right so this is just two times the slower pointer just by definition um and now the question is can i you see in this right in either one um let's see well we where do they meet right uh this is the part that i'm always a little bit sketchy about and it's such trivia hmm excuse me um oh yeah and i think it goes without saying we're trying to do it with all of one memory because obviously if we have of n memory this is even more you know we just have a hash table or a lookup table or something like that and that would be uh you know like a four loop and silly so yeah um so let's incorporate cycles into this right so the idea behind this is let's see let me see if i could have my visualization up real quick um so this means that there is some head so the slower point that moved from a and then will be part of the cycle okay how far did the faster pointer move right well the faster pointer when it moves to b what does that mean right and there's this formula as well but that means that it moves a plus because the a is the head c is the length of the cycle right do you say let me think about this for a second ah so bad at this linked list stuff is so useless if you ask me but that's besides the point you i know people could say that about anything but it just doesn't really come up in competitive either not even um yeah but okay what am i saying okay let's see i'm just tired today okay let's see right so a is the part that means that it has move so b is the length that is traveled inside the loop so that means that the faster point of a meet pointer at b plus the cycle right um because the cycle is one cycle um we assume that the faster go one foo and then plus and then um and then catches up at b does that make sense hopefully that makes sense um let me draw it up really quick again actually um i think this is right though but let's talk about this again um if we meet here okay let's say this is a let's say they meet uh let's say they meet here right so then this is b and then of course the cycle length for c this is c um right so that means that because in order for the fast pointer to reach all the way back to here to this point it would have to go and then one cycle later right so of course if you draw it this way then it's clear that this is a um b is this part um already and then c is the cycle right the length of the cycle just to kind of visually show the formula that we kind of uh that i have here which i was trying to do it in my head which is i think fine in theory but you know i'm trying to show you a little bit right so okay so in this case then that means that well i mean obviously these two are the same which means that the um this is the number of steps this should you go to do and of course this if you subtract a and b plus both sides that a plus b is equal to c is that right that is huh maybe some people just memorized this then i guess it's very easy to remember i just never i don't think i ever remember this but uh but that's actually if that's true then that's good i am not super confident at this particular point not gonna lie uh i'm a little bit rusty and yeah and you could kind of see me actually solve a problem that i don't really you know like this is almost like ad hockey weird problem right so okay in this case okay so what does this mean this means this is the length of the cycle right that means that the slow pointer has moved the length of the cycle by the time it meets man that sounds really awkward but is that true let's see i mean one thing that i like to do is uh to verify myself before i kind of invest more time in it is take a you know take to take a case and then see where it goes like for example one what happens here right and you kind of like just draw it manually so the so move one each and then two and then three huh i guess that is the i guess that i mean it works for this one so okay wow that is uh i guess that's how people remember that because i do know people like did this really quickly and i'm like yeah i don't know because i don't like memorizing these trivias but i guess this one's actually not that bad to remember but i don't know i still don't like it so that's why i don't remember it but as you can see you can put uh kind of figure this out where i don't know about very quickly but pretty okay right okay so then that means that okay we know the cycle length so then how do we uh how do we get the starting pointer right um and the point there is of course just a that's basically effectively the answer that we're trying to get which is a so then we already s so then here um what is a right a is equal to of course c minus b um but can i represent this in terms of motion um okay so we have a okay so the length that it goes is the length of the cycle right so what does that mean so that means that we're in the cycle um and this is the length of the cycle minus b that means that if we have a pointer that moves b would that give us a no but what we want so a is equal to this stuff hmm man i am not knowing this at all uh so we want to find a which is c equals to b but we're trying i'm trying to think about how to do pointer arithmetic because we don't we actually in theory know c or b um but if we move hmm is that a good way about it let's see right uh we also do have all these other things so basically if we move another a plus b we get another cycle so is that helpful um don't know how do we find a or b then given these things okay so we have a fast pointer this part i'm not i'm a little sketched about uh let's see okay so let's say we have another point there right so what happens if we have another fast pointer i'm just like throwing up random ideas if we're not a fast pointer and we are at um at c then effectively what we're doing is adding a plus b on the slower one and then on the fast one we add a plus b plus three plus c right which i guess is just adding two cycles on both sides does that help at all where do they meet man just what i'm really bad today um okay so let's say we have this thing and we want to add or maybe this thing right so we're at actually let's step back for a second right so hmm so we know that this is the length of the cycle and that means that we know that um so that means that if we add another a then this is the cycle and this will be c and then we will get a okay i think that's how i do uh i think sorry about the red herring um yeah okay i think that's how you do it right is that okay you have a and b you're on a slow pointer if we do if yeah let me say it in a way that i think i understand now that the thing is up uh okay so now we have a plus b on a slow pointer um and so in order so we add another a to this then we know that this is equal to c which is equal to um because if a plus c is of course equal to c sorry a plus c in this uh linked list of arithmetic is equal to a because c just cancels out right like it just loops around so that means that in the beginning we would have a so that means that from here um from where we are now we have to move another a right um and we move and other a maybe that well okay maybe i'm maybe that doesn't make sense actually now that i think about it or like it makes sense but how do i get this again i think i had some idea in my head but now i'm a little bit lost again whoops i mean what i'm saying is right but how do i get that again uh okay so we have a plus b and let's say we move how do i move another a i mean if we know how to move another a then we just know the a right so that's actually maybe uh a circular logic thing man i'm really bad today on this one uh let's see maybe that wasn't the right way to go i was gonna do something like okay maybe if we add another when would okay i guess my question is when would this like if we start another fast pointer from the get go from the beginning right um okay maybe i'll write it here um let's say we reset this to zero after finding this thing um let's say we want another um until they meet again what does that mean right does that mean anything because now what happens is that one psycho is going to be one cycle is going to be c i guess though it could go many cycles right so because a could be large and the first point it would catch up one at a time does that even wow i really have no idea how to do this hmm today anyway because i feel like i've done this before but i'm missing um okay so we have this thing where's the faster pointer again the faster pointer is a plus b plus c oh yeah we knew that because they're both at the same place that's how they meet um okay um how do i just get a then let's see how is there a way i can move just b steps or a steps i guess if we just add a steps and this would be not a trivial in a way as we already said well oh i see um is that true no i guess not i was going to say maybe we could uh like we could calculate this by sending another uh another pointer moving c but that doesn't really change anything because now we know the length of c but we do not know a or b what if we no that doesn't make sense i was going to say well we sent a second slow pointer but it's also there's a chance that they just never meet right so that's just silly um if we have a second fast pointer where do they meet i guess i was a little bit lazy not lazy i just don't know how to do that one right then that means that the fast pointer is going to be a plus b behind hmm um what happens if we have a second slow pointer okay i think now i remember the idea that i kind of lost a little bit because i confused myself which is actually ridiculous now that i think about it i mean i actually alluded to the same ideas but uh but sometimes math is just ridiculous and it's also one of those things where if you knew the answer you could prove it easily but i don't know how people come up with stuff like this but the idea is the same right is this plus a is equal to c plus a so this is of course now we have um now we have c but the idea is that um and we kind of touched upon this before we add eight a steps on each side but the key thing to know here is that um this means that the two pointers meet at that means that the two pointers meet at the same time and the second slow pointer i think that's basically the idea here um because okay let me bring back the paintbrush thingy again um so basically let's say we have here right um and this actually may not be true because i might have missing some notes but actually no this is actually right but i don't know uh by accident really but yeah but let's see what they mean here right that means that because this is a plus b here um and we know that another additional a this completes the cycle because that's also the definition of a plus b but that means that because of that if we have another slow pointer starting in the beginning they will meet at exactly here because this a is equal to this a i think i had the math right but i missed the visualization in which they meet at the same point and if they meet at the same point then you can just return that answer this is also honestly a ridiculous problem if you haven't done it or seen it before i've seen it before and why i refuse to remember it or memorize it because it's not really it's just one of those things either you remember you don't you and i don't put any effort into memorizing this because it's whatever um but that said that's uh that's actually amazing so that allows us that's it right the tail um if you send a second slow point that they intersect at the starting point okay so this is already a long video but hopefully you kind of see my thought process including a couple of times where i was way close like i saw this idea i knew i just saw the mathematical thing but i think i confused myself with the math uh the math with the visualization and also what it means physically right in terms of the linked list um and i think once we um kind of put that all together everything is good again okay let's uh let's get it to um yeah let's get started on this then um and this hopefully uh even though it's really long and i hope you watched it on a faster speed until at least the end uh hope this is a very good understanding problem because this is hard if you uh you haven't done it before so yeah um okay so then now we move and this is what i'm doing now is just the array this part i say is standard with voids algorithm and it actually comes into play with different other problems as well um which is why i know it because in this case there's a linked list right of course so and like i said i don't care for linked list per seg it doesn't come up that much but you can actually use this on other things that are not linked list but it has a linked list e uh thing right like one thing that is used is if you have a function like if you have for example f of x um and you want to see is there a cycle um let's say you have x to f d uh dot right is there a cycle um and of course in this case freud's algorithm would be uh the slow and the fast pointer um could used to be used to solve this in constant space if that's your need right so there are a lot of like stuff like this and then you could kind of even do another loop to get the entry point again um which is kind of like i said kind of miraculous but in either case uh yeah maybe i could use that because i think actually interestingly a couple of days ago i did a code first form where i was running out memory um though this is a little bit slower so i don't know but yeah so maybe that could have been helpful anyway so yeah wow how do i want to write this um yeah uh well fast is not none fast is equal to fast.next if s is equal to fast.next if s is equal to fast.next if s dot next is not none uh but fast it's not none as fast as you go to fast down next slow as you're gonna slow down next there's this part i'm a little bit sketchy about in that i always forget how to write uh the loop in that there's a there's not enough by one um but if this is a little bit off i'll have to just modify it but uh but yeah they're the same then we break and of course they're the same so you could just take either one um doesn't really matter right like so we'll just start slow as you go ahead again and then now while slow is not you go to head slow next and then just return slow again uh again it doesn't matter which one you return because they're the same right that's the variant let's give it a spin maybe i'm off by one maybe not hopefully not okay uh let's see oops add a few more cases uh oh i um i uh watched my card i didn't do the case where um yeah i didn't do the case where um you know this is true yeah the non link the non-psycho yeah the non link the non-psycho yeah the non link the non-psycho case is what i forgot um and that looks okay let's give it a submit done it apparently is it a year and a half ago okay cool um yeah that's all i have for this one i know this is a longer video um but i hope that i mean because you know to be frank this is a problem that a lot of people have videos on so i don't really you know like i don't feel like you know if you only want the answer then i apologize uh the video is a little bit long but if you want to see how someone whom um have some idea but wanted to kind of uh do the thought process about how to solve this problem from scratch not really scratching i'm not gonna lie but like to salvage live um hopefully this was a good uh attempt to kind of uh visualize that uh let me know what you think let me know how you did let me know if you did it in constant space uh that's all i have stay good stay healthy good morning to good mental health uh have a great rest of the week and i'll see you later bye
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. 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 (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **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
Medium
141,287
438
hello welcome to my channel today if you have leeco 438 find all anagrams in a string so given a string s and a non-empty so given a string s and a non-empty so given a string s and a non-empty string p find all the star indices of piece anagram in s so later you will see the condition here and also another condition in non-empty also another condition in non-empty also another condition in non-empty string p so as we know that and take a look at example right here we have s x input a string another string p right here so uh the indices of zero which is in here you can find the anagram of p so this mean abcs in here that have all the character in p abc here and also in this uh right here six it also contain the anagram here so i have bac also have the same character of abc here so now we have that two indices and output for the outcome and another example here so you have a b that have a b two character also b a's also have a and b in here another index of a and b and that's also contained that two same character so the output will be this three index and this one is really classic because it's using the sliding window and i think it's really good to demonstrate this question to you and for the beginning with the sliding window problem how we uh take care of this problem is first we just take a look at example two now we have a table of 26 character and you see a ends here b is here and so on to z and we accumulate that we have one a we also have one b so this is called table oh hold on o y is not writing okay finally sorry so tables right here so in here we know we need to balance it so we need this through two from here to balance this out so now we have a window start lab here and also have a window right here so the left side windows in here right side window here so we need to expand that so as we expanded the right side to here then we have character a and we see character a and go back to this table and you see oh a we cancel this out then since we cancel it out and here become zero so think this is zero how many do we need to balance it become one so the two deducted by one things is zero right now so and we always keep the windows uh become two keep the two window and now we have right in here and later because this is only have window one only you need to expand the window become two range then right side will expand it to here and now you see the window currently is a b right now and you see b is right here and come to the table again can the cancel this deducted by one and now we have a balance of zero so since balance is zero then we found it and then what we do is output this left side which is zero into the array output and since this window is already fit for the size and we need to move the left pointer to b right here and right pointers right here so after you move this one you have to add this back at the a back in here so after it add a back here increase the balance again and then this is one loop and you come back to here to see if the rain windows is size of two so now window is a size of one expand the right side pointing to here so you have b and a process a then uh you cancel this out becomes zero and there's another balance of zero again so that's how you keep looping to indeed to the end of the string and you find all the possible solution and put it to the array and this is the idea of the sliding window problem let's take a look at the code now first we have a list of integer output so equal to new array this is just a template since p is a non-empty one p is a non-empty one p is a non-empty one so we uh have a simple hk check for s so s is equal to no or stop lane equal to zero then what we do is we turn output so just as cases and first thing we need to do is have a table here so the table will have 26 space and then we loop through the p all the characters c and p two character array so every category in here then we need to put table c minus a in here accumulated for example if is the character is a minus a so it's zero so that will have a zero as index they put it to the right place so b will be one for sure b minus a character is one so now accumulate that to the table now and we'll initialize that equal to zero initialize rise equal to zero we also initialize a balance so now we know um we're looking for how many because p is always two i mean p is slings always the balance so we're looking for how many characters we need to cancel out so now we have the balance starting at p dot lane so now we have the right it's always less than stop link th so we have right look through the entire s to the end of the s string what we can do is move the right side we start moving the right side so after we move the right side we need to have so let's have a um ins current equal to s dot character right psi minus a so this is the right side character and minus a is the index of that character so we will first table we will minus that character for example you have one and one here because a and b if we see a then we minus from here we deduct it from here because you're adding this to the table so you minus this from the balance so if table curve the current index is bigger or equal to zero that mean is already deducted from this table um that's something that they're looking for so a is belong to p so at that case and balance minus so mean balance will deduct by one two so you're looking for one less so you define you're looking for two and you have one is in here then you have less one less character you're looking at looking for then balance deducted one and right also increased by one because you're moving the right windows to the right side this is how you move the right window so now we have a check if check balance so we check where balance is if balance equals zero that means we only looking finish looking all the balance from p then um we have output at left so left will be the current uh windows left side and that's the in this indices index that we're looking for so add it to the output and if we check the windows if the window is smaller than 2 in here then you need to expand the right side but when you expand it to the right 2 size of 2 that means the fulfilling p size already then you start moving the left pointer so mean right minus left equal to p dot size uh p dot link at that time the window need to change by moving the left side so we also do the same as moving the right side so we can keep the current as stop chart at left and looking for the index of that character and put it to current so we put the current back to the table because you're deducting 1 from the window then we have to add this back to the table to see how many uh character in that window and after we add it back we have a check if table current um have bigger or equal than one and the balance will add it back so after you add one if the table have one or more that character that mean the balance should be adding by one because you're looking for more if you give up one of the things that belong to this um table or beyond to p then you definitely need to add back one more target in the balance so after that left increment by one two so this is how we move the left pointer windows so i think this is it for the moving window and now return output it looks good let's submit it cool um and i think that's it for this questions is sometimes it took me a while to think about the lab windows and it's normal and i think you should try to draw it out and nothing's easier to understand so other than that if you have more questions and please feel free to comment below and i will see you in the next video 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
12
Roman number to integer so basically we have given a Roman number in the question and we have to find the integer for the same so here I have written the program for that if you can see the solution the map I have formed in the map I have just kept the Roman number with respective number and here I'm just taking a for loop with this for loop I will be just returning the sum and then you can see this is like complete video and the explanation is already available on the channel and you can check that as well and do subscribe to code for placement guys for more such videos you can see the beat time is 55 which is not so good but still the uh this is one of the best approach to do so do check out the complete video you can pause this video and get the code as well thank you guys
Integer to Roman
integer-to-roman
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given an integer, convert it to a roman numeral. **Example 1:** **Input:** num = 3 **Output:** "III " **Explanation:** 3 is represented as 3 ones. **Example 2:** **Input:** num = 58 **Output:** "LVIII " **Explanation:** L = 50, V = 5, III = 3. **Example 3:** **Input:** num = 1994 **Output:** "MCMXCIV " **Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. **Constraints:** * `1 <= num <= 3999`
null
Hash Table,Math,String
Medium
13,273
50
hello guys welcome back to take those and in this video we will see how to find X raised to the power of n we will see the most optimal binary exponentiation technique in this problem and this is from lead code number 50 and it is a very important math algorithm problem which you should never skip before looking at the problem statement I would like to announce about our DSA live training program which will guarantee understanding of every programming concept it makes you interview ready in just three months and it will maximize your offers so that you get the best possible pay and in the best possible company you can all the sessions will be live interactive sessions so you will get the feel of a live class and you can ask all your doubts throughout the class in order to get more details please WhatsApp us on this given number let us now look at the problem statement so let's see the problem statement the problem is very simple like we are given a to the power of B and we just want to find the final answer for this so let's take an example like uh 2 to the power 8 and if you want to calculate 2 to the power 8 the simplest way would be to take the base exponent number of times that means take two eight number of times and you just keep on multiplying the two eight times and if you do that then you will finally get the result but the number of operations which you are doing is order of B hence the time complexity for this approach will be order of B so this is the simplest possible approach now there exist another idea which you can use to actually solve this problem so if you can look at 2 to the power of 8. the way we can write 2 to the power 8 is 4 to the power 4 as well and you can see 2 to the power 16 it can also be represented as 4 to the Power 8 2 to the power 32 can also be represented as 4 to the power 16. now what is happening here if you see let's say I write 2 4 times right if I write 2 4 times it is equivalent to 2 to the power 4. now 2 to the power 4 I am saying that it can also be written as 4 to the power 2 and how is this happening let's say we Club these two twos together now you can write them as 4 and this will become another 4. now if you multiply them then it will turn out to be 4 to the power 2. so with this logic we can say that 2 to the power 8 can also be written as 4 to the power 4. this is nothing but squaring the base and taking half of the exponent and this is pretty logical this is a very simple example for the same logic Now using the same logic we can also say that 2 to the power 8 can be written as just Square the base and half the exponent and you can write it as 4 to the power 4 and simply 4 to the power 4 can be written as just Square the base and half of the exponent so 4 Square will be 16 and half of this 4 will be 2 so 16 to the power 2 right even again if you start extending it will be 16 square which is I think 256 to the power 1 so you will see that 2 to the power 8 final answer is 256. instead of following this technique if you had followed the previous technique of the simple approach of like multiplying two eight times then that would have given you 256 but in eight number of steps in this case you see that there are only three steps one two and three right so this is heavily reducing the number of steps so let's solve an example with this idea now if you look at the idea it is just squaring the base and dividing the exponent by two so let's uh Take 2 to the power 8. so if we take 2 to the power 8 then we can write it as 2 to the power 4 into 2 to the power 4 which is like dividing it into two parts and simply this can be written as 4 to the power of 4 okay now if we take again 4 to the power 4 we can write it as 16 to the power of 2 with the same logic and again if we take 16 to the power 2 we can write it as 256 to the power 1 and whenever you reach to power 1 that is where you stop so 256 is your final answer for 2 to the power 8. now if you try solving a similar problem 2 to the power 9 where the power is odd you will definitely fall into a problem like if you divide this 9 by 2 it will be 4 right so you have to write it as 2 to the power 4 into 2 to the power 1 so you will see that this 2 to the power 1 is not matching this 2 to the power force and this is just an extra value which is equal to the base so this has to be saved somewhere so let's save to 2 to the power 1 somewhere right and let's call it result now once we get 2 to the power 4 like this can be written as 4 to the power of 4 isn't it now this 4 to the power 4 can be again written as 16 to the power 2 and again 16 to the power 2 will become 256 to the power 1 so you will see that 256 is the final answer here and there was something which was lost due to dividing an odd number by 2 and hence it was saved in results so finally this 256 will be multiplied by this result and it will become 512 so you will see that there is only one thing you need to take care of in case of the odd powers for even Powers uh dividing by 2 actually doesn't make you lose any power like any of the base value and when the odd number comes like when the power is odd then you will definitely lose one of the values okay so that has to be saved somewhere and that is where uh the result actually comes into picture so let's take one of the problem and do a dry run of the entire logic and then you will easily understand so the right hand side is actually the entire code of the logic which we discussed which is binary exponentiation and on the left hand side let's take an example 2 to the power 13 and by the way this technique is known as binary exponentiation binary because we are dividing by 2 and exponentiation because the base is exponentially increasing and the steps are reduced to logarithmic order right so let's just do a dry run on this entire code so let's take the example of solving 2 to the power 13. so if you take 2 to the power 13 and let's also take all the variables so the variables are result which is equals to 1 and then you have a and b so a is equals to 2 and B is equals to 13 right which is a to the power B format now in the first step you will see if B is greater than 0 so 2 to the power 13 again it can be written as 2 to the power 6 into 2 to the power 1 now this has to be saved somewhere so definitely if B mod of 2 where B is 13 in this case right so if B mod of 2 that means if B is a odd number then definitely this 2 to the power 1 has to be saved in the result so this result will be multiplying to the power 1 and this will become 2. and in The Next Step you square the base so the base will become 4 and the exponent will be halved so now the next problem to be solved is 4 to the power 6. now is this 6 an odd number you will see that no it is not an odd number so definitely you can write here 16 to the power 3 for this so what we are basically doing is just squaring the base and making the exponent go to half so now you have a problem 16 to the power 3. so we can write 16 to the power 3 as 16 to the power 1 into 16 to the power 1 now these two can be clubbed together and it can be written as 256 to the power 1 okay and this is an extra value because the power was an odd number now this has to be saved somewhere and that will be saved in the result so you will be multiplying 16 to the power 1 here and this will make it 32 right and now you have 256 to the power 1 you will see that again B greater than 0 is true and you will see that the power 1 is odd so this 256 has to be multiplied here and this will be present at this place and you will get the final result as 8192 and again in The Next Step this 256 will be squared up and this one will be halved so 1 by 2 will become 0 and so the while loop will be breaking so whatever is saved in your result will be returned and that will be 8192 and this will be your final answer so you can now calculate how many steps did you take you will see that how a was growing so A's value became a square and then it became e to the power 4 and again it was squared right so every time you will see that the base was getting squared up and the exponent was getting hard so from B it turned out to be B by 2 and again B by 4 and so on it went on until we reached to 1. you know that if we keep dividing a number by 2 the number of steps will be log of B base 2 exactly these many steps right so you now know what will be the total number of steps to solve a to the power B that will be order of log B right and since we are always dividing by 2 hence the name binary came and uh this is logarithmic order or you can say base is exponentially increasing and that's why the name binary exponentiation so even if you go ahead and solve the problem power of X comma n in this case the x is given as double but still the code would exactly be the same so you can just go ahead and try solving this problem it is a very important math algorithm problem if you like this video then please hit the like button and subscribe to our channel in order to watch more of this programming video see you guys in the next video thank you
Pow(x, n)
powx-n
Implement [pow(x, n)](http://www.cplusplus.com/reference/valarray/pow/), which calculates `x` raised to the power `n` (i.e., `xn`). **Example 1:** **Input:** x = 2.00000, n = 10 **Output:** 1024.00000 **Example 2:** **Input:** x = 2.10000, n = 3 **Output:** 9.26100 **Example 3:** **Input:** x = 2.00000, n = -2 **Output:** 0.25000 **Explanation:** 2\-2 = 1/22 = 1/4 = 0.25 **Constraints:** * `-100.0 < x < 100.0` * `-231 <= n <= 231-1` * `n` is an integer. * `-104 <= xn <= 104`
null
Math,Recursion
Medium
69,372
318
hello everyone welcome to quartus camp we are a 27th day of mail it goes challenge and the problem we are going to cover in this video is maximum product of word length the input given here is a string array which consists of words and we have to return the maximum product of any two words and the words should not have the same characters so let's understand this problem with an example so here is a given example if you observe the words they do not share the same characters are a b c w n foo is one pair so if you see the length of a b c w is four and the length of four is three that multiplies to twelve and next a b c w and x t f n is also not having same characters and again the product of the lengths of these two words are going to be 16 and the other words are ba z and x t f n and again the product is going to be 12. so out of all these combinations 16 is going to be the maximum value or the product of these two words a b c w and x t f when they both have different characters and the length equal to four each and if you multiply they both then it is going to be 16 and that is going to be an output so if you want to approach this problem in a brute force way then you are going to have two for loops which is nested and they are going to compare each word with every other word in the input and we are going to compare those two words that whether they have common characters or not and if they have common characters then skip it if not then multiply its value and have it in a variable which compares every time and update it with the maximum value and finally return the result and that is actually going to take cubic time that obviously going to do a time limit exceeded result so how do we approach this in an optimal way so there comes the help of bitwise so instead of comparing each word with every other word and iterate we are going to assign a integer value to each word in the given input after assigning we are going to compare those values and come up with a result so as i said we are going to put an integer value to each word in the given input so how do we arrive at the integer number so first we are going to represent the given word in form of binary and then convert that binary number to an integer number so consider our alphabet starting from a to z are going to point at each integer value starting from 0 to 26 that is nothing but a represent 0 b represent 1 and so on and is it represent 26 so we are going to have a 32-bit integer so we are going to have a 32-bit integer so we are going to have a 32-bit integer number where we are going to fill the bits with ones or zeros according to the character present so let's start with the first word abc w so we are going to fill in once at the character so a b c and w will be having once and all other positions will be having zeros so once we fill with ones and zeros it is representing a binary number so if you convert this to an integer you will get an integer value for example if you convert this particular binary number to a decimal value then for a b c w it will be converted to 4 1 9 4 3 double 1 some integer value which is 32 bit integer same way we are going to create these kind of integer values to all other strings in the input for example for a second string we will be having one set only b a and z all others are going to be zeros and the same way we are going to assign an integer value to each number so the second step is once we have our integer values ready we are going to compare each integer value to arrive at our solution so the condition given here in the problem statement is no two words should have common characters so as we are representing the words in binary format we are going to perform an under operation between those binary numbers and if any number comes all 0 that means the words are not having common characters then we are going to perform the product operation so just for a work around let us consider we are having only four characters and we are representing that in a four bits binary number so let's say our words are a b and c d so in that case the first word is gonna represent it as one zero and the second word is gonna represent it as zero one so if you perform an and operation to these two strings then it is gonna become all zeros because in and if there is one zero then it is going to be zero in the solution so as these are having zeros at all four positions they are going to become all zeros so in that case we can identify these two strings are not having common characters if suppose the words are a b and b c then in that case we will be representing the numbers as 1 0 and 0 1 0 so if you perform and operation to 1 0 and 0 1 0 then in that case it is going to have 0 1 0 which actually means we have b in common between both the strings so yes by doing these and operation we are going to identify whether we are having common characters or not so if there is all zeros after performing and in that case these two words are not having common characters then we are going to perform multiplication operation of the words length and we are going to have a variable max which is going to hold the maximum product so far and return that as a result so hope you are understanding this approach and we are going to iterate each string and construct an integer value and then perform an end operation so that is gonna take big o of n cross n time and overall it is going to work and we go of n square time complexity so let's go to code now so first let me declare integer array to store the integer values of each word let me name it as check and then variable max which is actually going to be a result and let us iterate each word and each character in each word so here x is nothing but we are converting that character to an integer so that we will convert it to a binary number so here we are going to have an integer value num which is going to be initialized for every character as new variable for every string as a new variable and for that string we are going to convert it to a number so it is nothing but we have converted that character to a number so we are doing a one sh left shift x which we have already covered in the previous problem so if suppose we are converting b as our character then b's value must be two so if we are doing one shift then the binary number of one is going to be zero one then we are doing a left shift of two times then it is going to be represented as zero one 0 so this is nothing but representing a character which is b so yes we converted that to a character and we are assigning that value to our array so yes this is done once our array is ready we are going to iterate through the numbers and compare its result you so yes we are comparing the values and if it is 0 then we are computing our max value so this is it let's run and try you
Maximum Product of Word Lengths
maximum-product-of-word-lengths
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two words can be "abcw ", "xtfn ". **Example 2:** **Input:** words = \[ "a ", "ab ", "abc ", "d ", "cd ", "bcd ", "abcd "\] **Output:** 4 **Explanation:** The two words can be "ab ", "cd ". **Example 3:** **Input:** words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** 0 **Explanation:** No such pair of words. **Constraints:** * `2 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * `words[i]` consists only of lowercase English letters.
null
Array,String,Bit Manipulation
Medium
null
735
hi everyone we'll see about the today asteroid Collision problem that is ask in many company okay let's start with the problem and the question is given you are given an asid of integer representing the asid in a row and for each estro the absolute value represent size and the sign represented Direction and it is will be like posi Direction and The each asteroid move in the same speed find out the state of the asteroid all the collision and if the two esto made the smaller one will explode if both are same size both will explode and the two asid moving in the same direction will never so this is the proper condition which we have to be keep in mind while creating the condition while creating the code for that first of all what they are given they have a SES it will be positive or maybe negative okay then they are giving they are moving in the same there a condition like uh what is the condition which we have to maintain if there's a condition like they are given uh if two estro meet the smaller one will explode it means if we have a two plus one and minus one like plus a minus B if some reason one of the number is like anyhow one of the reason is one of the number is bigger so the smaller number will uh get slow over there I can say and second condition they are given if both are the same size both will and third condition like two asid moving in the same direction will never obviously if both have plus sign then they will never Collide if one of them plus and one of them minus like one is coming and one is going then they will explode otherwise not so coming to the input what they given basis on that we can map the condition or check the condition here asid equal to 5 comma 10 commus 5 so first we will check both are which how much element we have which we can say it never Collide because of the same charges or same direction so you can see we are When comparing 5 comma 10 it both number holding the positive number positive direction so it will never meet second come to the 10 minus 5 then they are given if both of the number have one of the plus one of the minus and one of them get explode and that is which number get explode I can say which is a smaller one so if you can say 10 and minus 5 colide resulting in 10 because it already mentioned like if toid me the smaller one will explode like coming from the 10 and minus one is like less one that's why it will collide and when we are comparing five and 10 then they are never get Collide so that's why the our output will be a 5 comma 10 the from the 10 and five we are getting the 10 and from the five and 10 we are they never Collide that's why we are uh taking the five from there okay similarly for the second condition 8A 8 minus8 they are having a both number same and both number having charges so they will exclude thir we have input like 10A 2us 5 in this also we can compare as a previous one 2 and minus 5 when we are comparing it will be giving the result in minus 5 because as already mentioned you both are holding the sorry one of the like different direction one is positive and one is negative so get smaller will be get discl explod I can say and when coming to the like 10 andus 5 when we comp 2 five 10 and five so in the 10 and five again it will be getting the 10 because minus 5 is a smaller number so it will get slowed so output will be a 10 and the constant here given this asteroid length between the 2 to 10 power 4 10 to this 1,00 to 1,00 positive power 4 10 to this 1,00 to 1,00 positive power 4 10 to this 1,00 to 1,00 positive then it not be equal to Zer yeah obviously if it will be zero then why we will check the charges and explore the conditions okay so this is the uh problem which we have to be uh solve okay so I have the code I just have to be write and apply the same thing here what we discuss here as a okay so coming to the coding part uh first of all what we have asroy input error so we are taking one of that in the list okay then we are checking like how much time or how many time we can iterate or we can check that values which is containing in Theo input it is positive negative same direction different Direction when they meet when they not meet like that so yeah I just created the one of the list for keeping all the asteroids and getting the one of the I variable for checking like the count which we have from this resulted input from resulted estro so you can see I applied the uh loop until the our count will be lie between less than count like this asteroid count till that count we can iterate okay first condition we can see asteroid of sorry result of I greater than zero because it is given in the condition it will not equal to zero so always it will be greater than it will be like obviously uh zero Val not containing but yeah we have this minus to+ one range so we have this minus to+ one range so we have this minus to+ one range so we have to check like greater than Z or less than Z so first of all Weck from the first greater than positive number purpose so if result of I greater than Z and this count is Li between from Z to like the number what we are iterating from that number to end of that and third condition we can check our next element is also less than zero like it will be like condition checking when we have a condition to collide each other like one is positive and one is negative you can see result of I + 1 is less than you can see result of I + 1 is less than you can see result of I + 1 is less than zero and this number is result. Count minus one will be a less than from so what we can see we can take those number those two number in the this asid one and asid two variable and taking the absolute value from there and then we are comparing which one is a smaller which one is a greater because of that we have to be explode so if you can see we have when asteroid one is greater comparing to asteroid 2 so we have to be remove the asteroid 2 because as already mentioned in the question if one of them uh like one number is greater one number is smaller then the smaller number will get expl so I + one is containing the smaller number I + one is containing the smaller number I + one is containing the smaller number comparing to aoid one so it will be getting explod and it will continue for moving the next element so that's why we are skipping that part and removing that position and then again continue second condition as we mentioned asteroid 1 is always less than asteroid 2 here we are checking it is greater than sometime it like our first value Also may be negative comparing to the second one so who will be a less one we have to remove so if we are conditioning like aoid one is less than asid 2 it means we are getting I + one asid 2 it means we are getting I + one asid 2 it means we are getting I + one value here from this and I value from here I can say so we can remove that position number so that's why we are removing and last one we have if nothing like we are having a same then they are never get Collide so that's why you can see it will be like greater than smaller than and equal to case all the three cases we are handled here and in the last part we are just removing remove um that next position current position also and last we are checking if our number I is greater than zero then we have to be decrement otherwise we have to be maintain the I and continue and after each iteration we are maintaining the I counter for the tracking purpose so it will be A++ plus tracking purpose so it will be A++ plus tracking purpose so it will be A++ plus and again we are returning the end of that result of array so it is containing like how much number we have which is not collide which is preventing from the explod I can say so uh we are using the result uh for storing that so storage will be a big often and for time complexity I can say we are taking the length of input from the destroid so it will be a biger of so let's uh we can uh run this it is getting exploded just checking the condition okay if we can say we have a both number same then it will never collide just I'm taking the input condition okay uh when we have a same number uh what I can 5 five with the same we will run this for yeah so if you are taking the same number with the same charges or same direction uh so they will never explode and both number is same that's why we are returning also the same both number so that's it for this today hope you like this meet you in the next video thank you
Asteroid Collision
asteroid-collision
We are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. **Example 1:** **Input:** asteroids = \[5,10,-5\] **Output:** \[5,10\] **Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide. **Example 2:** **Input:** asteroids = \[8,-8\] **Output:** \[\] **Explanation:** The 8 and -8 collide exploding each other. **Example 3:** **Input:** asteroids = \[10,2,-5\] **Output:** \[10\] **Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. **Constraints:** * `2 <= asteroids.length <= 104` * `-1000 <= asteroids[i] <= 1000` * `asteroids[i] != 0`
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
Array,Stack
Medium
605,2245,2317
131
everyone welcome back and let's write some more neat code today so today let's look at a problem palindrome partitioning so we're given a string s and we want to partition it in such a way that every single sub-string of the partition every single sub-string of the partition every single sub-string of the partition is a palindrome and we want to return all possible ways that we can partition it in like by following this rule and if you don't remember a palindrome is basically a string that if you reverse it's the exact same string so one thing to notice is no matter what string we're given it's possible to partition it in this way why is that the case because in this case we have a b we know that any single character like a is a palindrome right if you reverse a you get a any character including b is a palindrome right reverse it you get b so one way to partition this is take each character and separate it right and that's what the first partition over here is right each character by itself so are there any other ways to partition this other than just this single way well if you take the first two characters you see that is also a palindrome right a reversa is still a and of course b by itself we know any single character is definitely a palindrome so for the second partition we'll have two sub strings right a and b so then this is our result because we cannot have any other sub strings that are phalan drums right a b is not a palindrome if you reverse it we get b a that's not the same string if you take this and you reverse it you get b a that's not a palindrome so the brute force way in this case to solve this problem happens to also be the main way to solve this problem which is backtracking so we are going to use backtracking to solve this problem and what we're going to do is create every single possible way we could partition this and then check if those partitions form palindromes and if they do we are going to add them to our result list right because ultimately we want to re we want a list that has every single way to partition this while maintaining palindromes so for the first partition we have three choices do you see what they are if we want a first partition well the first partition can either be a by itself right so a by itself which is if we just took the first character and said that was one partition another partition is double a right if we just took the first two characters as our first partition or the last one obviously if we just took the entire string as our first partition now we will check is this a palindrome how are we going to check well we can start comparing the first and last characters right and we see that well they're not even equal right so this is not a palindrome so we are not going to continue on this branch or on this path for our depth for search tree but we know that this by itself is a palindrome right so this is going to be our first partition now we're going to take the remaining characters a and b and try to partition them right so for one partition of those remaining characters we could get a single a if we took this first one another partition we could get is a b if we took both of these characters but we look at the first character and last character this is not a palindrome this is a palindrome but this is not a palindrome so we don't have to continue on this path and from here we know we already took the first two characters as our first partition so we only have one choice for our second partition and that's just the character b and we know a single character by itself does form a partition and we also know that we have no more remaining characters right we already took the first three characters so what this tells us is this is one possible way to partition to make sure that all the substrings are palindromes right both of these substrings are palindromes so this is one possible uh solution so now the only path for us to continue we can't do this and we cannot do this anymore we don't have any more characters so we can continue this one how many choices do we have well we took the first two a's right so now we only have one choice and that's going to be the b so we for our third partition in this line is going to be b so this one had two uh partitions right two strings this one has three and all of them happen to be palindrome so this is also a possible solution so that's how you basically solve this problem with backtracking it's not super efficient right it's going to be at least 2 to the power of n because we're brute forcing it but now let me show you the code so let's have our result this is what's going to store all of the partitions that we create all the possible partitions let's also have a variable called part this is this basically stands for partitions this is our current partition right so if our current partition happens to be this is just going to be the single partition the result is going to be what stores the partitions right so this will possibly have you know multiple partitions in it and now i'm going to create a nested function depth first search for our br our backtracking the only thing i'm going to pass into it is i the index of the character we're currently at and so since this function is nested inside this function these two variables as well as s the string are going to be accessible in this even if we don't pass them into it so since this is a recursive function first thing we check is the base case so if i happens to be out of bound so if it's greater than or equal to the length of the input string s what are we going to do well in that case the same thing that we did over here right we knew that we had our a valid partition and we had no more characters to add so in that case we know that this is a possible solution so what i'm going to do here is basically to our result i'm going to append the current partition that we have formed but not only that i'm going to clone it because we know or rather i'm gonna copy it because we know if we end up in a different recursive call making changes to this variable there's only one part partition variable so it's not like there are multiple partitions being created we only have a single one so every time we append to result we have to make a copy of it and after we do that we can return because this is our base case if we haven't reached the last index what can we do well we can iterate through every other character in our string right so we're going to start at i and keep going until we get to the end of the string and for this meaning so this is going to be our sub string right this is every possible substring and we want to know is it a palindrome so the indices are going to tell us if from a string s starting at index i all the way to j we're going to check every possible string i'm going to add one to j to get rid of the off by one error and i want to know is this a string is this a palindrome i'm also going to pass in the indices i and j so we know what our left and right boundaries are and actually since we are passing in these boundaries we don't actually need to create a substring we can just pass s itself so we want to know is s a palindrome if you take it to start at index i and end at index j is this a palindrome and so if it happens to be a palm drum i'll actually write this helper function later we'll just assume we have it now so if this happens to be a palindrome what can we do we can to our partition we can add this string so s from index i to index j get rid of the off by 1 error we can add this so this is our current partition and we want to keep because we know s this substring is a palindrome and so now we can recursively do our depth first search looking for additional palindromes and of course we'll start at j plus one because that's going to be the next character and after we do our recursive function we have to clean up so since we know we only have one single partition variable after we have added this and added the substring and then ran our debt for search looking for all possible additional partitions after that we can take the string that we just added over here and then pop that from our partition list and that's actually our entire depth for search function you notice we have our base case when we go out of bounds and with this loop we are generating every single possible substring right from i to j we're checking if it's a palindrome if it is then we're recursively continuing our depth for search if it's not a palindrome then we're just skipping that substring altogether and going to the next iteration of the loop so that's our entire function and the only thing left for us to do is to actually call it so debt for search will pass in zero because we know that's the start index and then what we're going to do is return result and before i forget we know we have to actually write this helper function that we called before we even wrote it so let's write that really quickly is palindrome it'll accept a string and it'll accept left and right boundaries so we just have to check if it's a palindrome so while left is less than right we'll check if the character at the left position doesn't equal the character at the right position that means it's not a palindrome so we can return false if it if they are equal then we can update our left and right pointer so add one to left and subtract one from the right pointer and if this loop this entire loop executes and all the characters actually were equal then we'll exit the loop and then we can return true because that means it is a palindrome and now let me just run it to prove to you that it works and hopefully it's somewhat efficient yep it runs perfectly and it is pretty efficient so i hope this was helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
Palindrome Partitioning
palindrome-partitioning
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab" **Output:** \[\["a","a","b"\],\["aa","b"\]\] **Example 2:** **Input:** s = "a" **Output:** \[\["a"\]\] **Constraints:** * `1 <= s.length <= 16` * `s` contains only lowercase English letters.
null
String,Dynamic Programming,Backtracking
Medium
132,1871
174
hey what's up guys this is john here so uh today i'd like to talk about this 174 dungeon game i think this is very interesting like problem okay so let's take a look uh the blah there's a dungeon and there's a nat knight and there's a trapped princess okay and the 2d dungeon here so you know at so the knight starts at top left corner and the trapped princess where the imprisoned prince princess is located on the bottom right corner and on each of the cell here there's a like a house where there's like a you know there's a magic orbs or there's a trap okay basically the negative numbers means that so the knight will lose this number of health and the positive numbers that you know the knight will gain like additional this number of health okay and the problem is asking you to and also of course the knight can only move to the right or down below and it asks you to find the what's the minimum initial house the knights must have to be able to for the knight to be able to reach to the uh to the princess and remember so the knight has to keep his health at least one at each of the step here okay so for example this one the knight i mean it gives you an example here so the minimum house the knight needs to have is seven which means that you know at with seven here so the knight uh at the first step the house becomes a five okay and then he cannot go down right because when if he goes down he dies okay so he has to go right so now his house becomes to two and then he keep going right because if he goes down he dies too okay so here he his house uh became to okay becomes to five and then he goes down here the house becomes to six and then finally the house is one okay it has to be one remember it cannot be five here otherwise you know even though he managed to meet the princess but he already died the minute he entered this final cell here okay that's why the final answer is seven okay so i mean at the beginning at the first glance right i mean it's not it's i think it's pretty obvious right this one is like a dv problem basically you just need to find the uh at each of the this the step here right you have to gather from the two directions and then you're trying to get the minimum at the minimum house or the maximum value out from it but the tricky part for this problem is that if you do it from top down okay basically if you start from bottom from the top left corners and then you're trying to follow his like step like this you will not get the correct answer with a one pass of dp so why is that it is because you know it asks you to find the minimum health right starting at this point starting at zero point which we have no ideas okay so which means if we start from this moment here okay and we have minus two here so what are we what's our initial health we don't know right let's say if we don't care if let's say we just have minus two here it means that we're assuming the night uh the knight will have like zero health okay and then we're trying to see okay by the end if when he reached to the end what's that basically what's the maximum health he needs to get okay but that's basically with one set of the with one part of the dp there's no way we can solve that because we don't know what's going to be after that so i mean the best answer for this problem is that we do it from this cell from the bottom right corner and we're going back we're going backwards so why this one works because you know if we do it backwards right i mean we know we have seen so we have seen that the last we have seen all the uh all the cells we need right we just solve it backwards for example here right at this moment at this either target what's the minimum we need at this cell it's the uh it's one minus the dungeon the values in this dungeon right basically one minus five which is six basically we need six to get here uh to be survived to be able to survive here okay and then we're just going backwards so now we have to get to this last place here we have two ways of getting here right the first one is from up there and uh the other one is from left so how many we need how many health we need if we choose from this path here we need five we will need five i think yeah we'll need five here okay yes we need five to be able to get to six right because we have one here right and that's why we need five here how about how many uh house we need to be to from this side only one right to get here of course i mean we have to be the minimum house we need for each cell is one but things we're gonna charge we're going to charge 30 more health here that's why i mean all we just you do need to have one here okay to be able to get to here okay and then how about here how about the minus 10 here um let's see here you know let me go back here let me follow the original step here so we have five here and then how about here how many we need two here and then how about here we need like uh we need five here right we need five to get two through here that's why we have five here and then from here we have seven okay right so how about this one here right i mean as you guys can see we need one or five from this one so we choose this one but here uh we need like uh 11 right to be able to get to here because we need to be we need to survive here first that's why we need 11 here how about this one here we this is also one here okay and how about here we need like uh we need six here right we need six here because you know from one because here we have one here so we have eleven but we need at least six to survive here so among this five and six here we will choose five because we know okay five is it's smaller than six that's why we have seven here okay as you guys can see you if we do it reversely from the bottom right corner backwards to the beginning and then we can certainly find our correct answer because we have already seen what's the last one okay so with that being said let me try to code this one here so we need the amount in here the dungeon and n is the length of the dungeon uh sorry zero okay and then for we need a dp here right the dp is like uh since we're getting the minimum from the two of them so to be able to handle the corner case we need to initialize them to the maximum size okay this is like n plus one because we'll handle this like the corner case right in range m plus one okay here okay so and so for i in range like uh m minus one like since we're starting from the bottom right corner and the same thing for the j for j okay in range n minus one okay so and i think we have to uh we since you know our normal case is like this it's a like dp uh i j uh equals to the what the minimum right the minimum of the uh the minimum of dp are i minus one j and dp i j minus one and then we minus the uh the current dungeon value dungeon like inj okay and then in the end here right i mean basically we need to have at least a one here basically what we are saying here let's say we have six here we have a six uh we have six right and then we have like five here right we have five here and then we have uh one here okay remember so the way we're getting this 11 here is that you know we are we're using the minimum right from the previously one and we uh we minus the uh okay let's see minimum of this oh sorry plus okay this would be a plus one and j plus one okay since we're going backwards here and yeah sorry okay i what i mean here so how do we get one here right so i mean we as you guys can see if we use this one here right i mean the minimum of this one is six right six minus uh 30 right six minus 30 is what is like minus 24 right which means the magic orbs here is too much for us right so which means that we don't need that much basically if dp i and j is small equal smaller than zero then we know that okay we just need like one here because we know that at this cells they're like way too many like uh magic orbs we uh then we need so all we need is we just need one house to be able to get here okay but as you guys can see we do a minimum of this one here right and the base case is the princess right so here we have to do a special check here basically if the i is equal to uh m minus one and j equals to the n minus one otherwise since we initialize everything with the max size value here we're gonna have like maximum size here okay which will be a the wrong answer for the first element here that's why i mean for the last one for this one uh equals to what equals one minus okay because we know we need at uh at least basically this is our base case we need one house to be survived here that's why we need like this one minus that else how's this okay of course we have to do the same thing for this for both cases okay so that we can just reduce this uh unnecessary orbs to just one here and in the end we simply return like dp 0 sorry 0 and 0. yeah i think that's it submit yeah cool so it passed right i mean so i mean the time complexity of course is like uh of m and n right m times n and the space complexity is also o of m time times n uh yeah i mean this one is not i mean for to think it back backwards it's a little bit like tricky but okay so next someone might have asked but it's some for some people it's not that easy to think it backwards right how what if we really try to solve it from top left to bottom right can we solve it i mean the answer is yes but to do that right like i said we don't we didn't know the if we do it from the top left to the bottom right we didn't know the uh the what was the answer so we couldn't solve it in one pass so what can we do we have to do a binary search so what does it mean it means that we try all the possible initial house we try to all the possible initial health and then we do a binary search and then we find the minimum value that satisfies that's the knight can still survive to get to the princess okay um okay let's try to do that okay since it's gonna be fun all right even though it's not the optimal solutions but i think it's worth mentioning here okay so sorry to do that right for the binary search like always we need to find the left and the right boundaries so what's the left boundary is one that's going to be our minimum health but how about the right boundary what's the right boundary here so the right boundary is the uh you know it's the total sum of all the negative numbers that's going to be our right boundaries because you know if we have the length uh have all the uh of all the negative numbers that's going to be our can cover all the negative numbers here it's guaranteeing that i mean the knight can reach the final the princess right basically that's the uh that's gonna be our uh right boundaries here so basically i'm just going to do a simple for loop here okay and that's the for loop to find all the negative numbers okay and if the uh the dungeon right d u n g eo and i j is smaller than zero okay and then right uh plus minus dungeon okay yep i think that's that but is that the answer probably not right i think we have to start it we have to initialize it with one so why is that because we remember even with the right boundaries we after all the summarizing all the negative numbers that's gonna like counterparts all the negative numbers but the knight still needs one house to be survived to be able to survive that's why we need uh starting from one okay and then now the next one is the binary search template okay so like always so we have a middle here right the left plus right minus left divided uh divided by two we do a right minus the left just to be to avoid the overflow okay and then so our next one is going to be our halper functions so basically where in this case is can survive right can survive with this middle health if it can okay so now it's the part for the binary search since we're trying to find the minimum value okay so the minimum so for remember this so every time when you guys need to find the minimum values you always do uh if it satisfy the current conditions you set the right to the mid middle and then the left is the middle plus one so the reason being is that you know uh with the left and right okay with the left and the right since we're getting trying to find the minimum values basically we're trying to shrink the right pointer as to the left as possible and the reason we're doing the equal here is because it's because since the middle satisfy our conditions right i mean the middle could be our answer so that's why we cannot do a middle minus one and we have to do a we have to include the middle and then but we are trying to shrink this right to the left until we cannot shrink it anymore then either the left and right is our answer okay and as for the false for the other branches here since we know okay we cannot it cannot survive then we know the middle is definitely not our answer that's why we have we can safely change the left to middle plus one because we know the middle is not the answer and since we're doing the left equals to middle plus one here we don't need to do a plus one here okay uh i think we have explained this a few times in my videos the reason being is that if you're okay so for example if you are trying to find the maximum value in that case so this hyper functions even it is true we're going to do a left equals to middle and the right equals to middle minus 1. okay we're going to come into reverse but if we're doing the left equals to middle and if we don't do a plus one here right i mean for the case of 3 and 4 the final answer is also 3. so basically we'll end up stacking at this as this if statement forever so that's why if we're assigning the middle to the left we have to do a plus one okay but in this case we don't have to do it because we're where uh we're using left equals to middle plus one okay so then we simply return the left now it's how can we implement this uh can survive right uh i mean this part is a little bit tricky to implement because the way we're implementing this we're inside like i said it's a it's another dp because now we have the initials a house for the night all we need to do is just i we just need to check with this initial uh business initial uh house can the knight find a path to reach the uh basically to rescue the princess okay and okay so to do that i mean we have to initialize the uh our dp here so what's going to be our answer here and since uh to be able to walk through to work through at each of the cells here we're gonna collect basically we're gonna collect the maximum health from two directions so that we can use the max one to be able to get to the current one since we're collecting the maximum values right i mean to handle the other corner case we have we need to initialize all the house to have the negative maximum value here same thing with the m plus one for this one in range and plus one okay and cool so same thing for i in range so in this case we're doing like from top left so we have to do m plus one for j in range one and plus one okay i mean here it's a little bit tricky because you know why is that because we uh some of the path is not valid okay like i said i mean uh so let's say when we add set we have seven here right let's say we have five here i mean we can go either go down or go right okay but if we go down here i mean basically the knight will i mean will be that so which means this cell is not a valid path which means when we are at this minus 10 here this cell should be treated as an invalid path okay but how can we do that right i mean basically we just to be able to keep to mark this cell to be invalid we just need to make it keep it like an active we just need to keep that this value to that cell okay so i mean i'm gonna try to uh write the uh the most common case here right so the most common case is that is this right basically max from dp like i minus 1 j and then dpi j minus one okay and then we do a plus we then we can include the current dungeons value okay i minus one and j minus one that's our like state transit state transition function here okay but the problem is this right the problem is it's like and let's say for this case right for this one let's say if this one uh for some of the cases uh it is smaller or equal than m than empty so it means that okay the knight will be that right at this cell so for that one i mean we cannot keep this one at zero or like a negative value right let's say at this moment let's say that the this dp value is minus one okay so minus one means that okay so the knight is that at this cell but if we leave this minus one to this cell here okay and basically it means that the knight can still use this path to keep going forward right but which is not correct if that's the case it's going to lead us to a wrong answer because later on let's say if the knight is it's fine here let's see the knight can survive even though it's like negative one but it can still use this one but then the next one is 10 then right if the next one is 10 here okay so the knight will become alive again here because here it will be night here and then he can just keep going and go and then in the end he will rescue the uh the princess but which is not right if that's the case right i mean instead of seven i mean the knight can be anything the knight can be like uh can even can be two here right because as long as he can reach the uh like a magic orb to revive him from death right he can reach the end which is not correct so to be able to do to fix that right i mean we only assign this uh set this dp value to a va to a number when it is a positive number okay otherwise we keep it uh we keep it like a negative max negative number to mark it as an invalid path so and of course right we need the base case for this one okay so the base case is this right same thing if the if i equals to 1 and the j is equal to 1 and then the dp of i and j will be what is equal to the y to the middle plus the dungeon right i minus one and j minus one okay cool so and in the end we simply return right if the dp like uh we simply return the dp uh m and n if this one is greater than zero okay so but like i said right since we're like checking if the last one is greater than zero we have to uh mark those invalid paths so to mark that uh we need to do we need to use the time values here basically every time when we do a time values here we do this right else we do this temp okay and if the temp is greater than zero okay then we do this dp dpi okay equals to 10. otherwise we keep this one as an active value so that in the end this one will be an active value so actually here you know we can do an early termination basically if the starting point is an active value here we can simply like break we can simply break the whole loop because we know okay there's no way basically the night that the moment he entered the dungeons he enters the dangers but for before the all the other cases we cannot simply break a stop there because there might be other paths that can lead the knight to the uh to the princess so in the end we check if the if is the middle with the current middle starting house can the knight find a pass meet the princess alive okay so yeah i think that's it let's try to run the code here uh dungeon oh sorry yeah okay can you survive sir survive oh survive sorry um too many typos come on all right so this one submit cool so it passed as you guys can see only b is like only five percent of people why is that so now what's the time complexity okay so the time complexity is
Dungeon Game
dungeon-game
The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step. Return _the knight's minimum initial health so that he can rescue the princess_. **Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. **Example 1:** **Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\] **Output:** 7 **Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN. **Example 2:** **Input:** dungeon = \[\[0\]\] **Output:** 1 **Constraints:** * `m == dungeon.length` * `n == dungeon[i].length` * `1 <= m, n <= 200` * `-1000 <= dungeon[i][j] <= 1000`
null
Array,Dynamic Programming,Matrix
Hard
62,64,741,2354
51
hello everyone it's me abhinaya so today in this video we're going to solve another interesting problem from lead code called n queens it's a half it's a heart problem the problem number is 51. let's see the question the end queen's puzzle is the problem of placing n queens on an n into n chessboard such that no two pins attack each other given an integer but an all distinct solution to the increased process so in here they have given n is equal like you know right the queens can move in all four directions we have to place the end queens uh in a way that it doesn't attack each other so if you keep here like this will not attack this and this cannot attack this so what we have to do is if a queen is placed in a position in all those four directions another queen should not be placed so we have to place a and go into the ending so let's see this problem is actually a pretty popular problem it's good to know this problem so for that uh first we'll have a result the result array and then we have a board okay it's a 2d array so we'll have both so first i'm initializing everything with one no everything is zero for um and then we are going to go into another function called place queen and that's going to have a board and the starting uh row position so first i'm going to start with zero and then we're going to have three sets to check for this diagonal one and this diagonal two and for this position vertical position so we're going to have three sets and then at last field with the result so let's see this function so first like cell board i'm gonna call the row numbers i and then diagonal one two and for that vertical position so in all these kinds of problem you have a base condition right so if i is equal to length of the board that means it has gone through all the rows that means you have done with one possible solution so for that if i is equal to length you're going to pass this ball into another function i'm going to call that function as uh okay we'll call it a screen so now what we're going to do is we're going to loop through the board right you already have idea but we need another it's a 2d array so we need j to change so to check this uh diagonal uh to get this diagonal we should just add i plus g to get this diagonal we should just subtract j minus i okay so if i plus stable it should not be in the set okay it's not if i plus j is not in set and j minus i is also not in fact not in d2 and the j is not in the vertical set v then the place is free we can place the queen there right it's not in d1 and j minus i not in d2 and j not in b if it's not in any of the set there we can place the green so for now i'm going to change it into one and in another function i'm going to change the one into three okay and now we begin now like that now that we passed we now we oh now that we place the queen in that position we can add i plus j and j minus i and j in those sets right so d1 dot i plus j and d2 now we are going to call this function again for i plus 1 for the next rows to go into the next row please mean bold i plus 1 b 1 and 2. now like now we don't want those all those values to go again and again so we are clearing those data here i j 0 game on the side and uh v dot remove g so now like this will uh this will get all the possible solutions where we can see that we can place the queen now like here we have place queen as one but we need a uh skew and uh dot right so that we're going to change here this queen function so it's just looking through the board and changing it so we have help now we're going to loop through the board and it's a string right so we have is one that means uh the queen is placed in that position so we'll add q if not uh the queen is not placed in the position so if you queen has not placed its dot so we'll have we'll add the dot and we'll add this string into this and we'll add this into the result append the heavy and that's it let's run this i hope it passes so this is how we solve this problem so if you guys know every other way to solve this in the comments below i'll see you guys in my next video until then bye
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
52
continue from an ass problem which is 51 in Queens let's take a look at number 52 in Queens number 2 so the problem is same except that we need to return the number of distinct solutions well it's totally the same right so please if you have any questions if I have something I'm familiar with this problem please take a look at my previous video in my channel which is 51 and Queens here I just copy paste my code I'll get to do some tricks so the problem asked us to return the result number of results with not the results so let's say results equals 0 here we will put the final result rather than this we were just update the result plus 1 and it should be issue work yay this actually would be the fastest solutions in my home this will be the fast the shortest video in my channel so here that's all for this problem please take a look at my other videos for example the previous Sudoku problem and these n queen problem they're all backtracking hope it helps you a little bit that's all for this time see you next time bye
N-Queens II
n-queens-ii
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 _the number of distinct solutions to the **n-queens puzzle**_. **Example 1:** **Input:** n = 4 **Output:** 2 **Explanation:** There are two distinct solutions to the 4-queens puzzle as shown. **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 9`
null
Backtracking
Hard
51
1,255
Hello, this is Nagopa from Live Coding. Today, I will solve problem number 1255 of Litcode, Maximum Score World Form by Letters. The pronunciation is a bit bad, but please understand and the difficulty level of the problem is hard. The problem was taken from Litcode, but it is a hard problem. It's not that difficult. It was a very typical backdracking problem. Still, if you look at it, the ratio of likes to dislikes is much higher than you might expect. I don't know if people gave it good scores because the problem was easy, but they gave it very good scores and it was because it hadn't been long since the problem came out. Well, this number doesn't seem to be that many. To put it simply, to put it simply, you create a world using letters and letters according to conditions. When you create a world according to conditions, you create the highest score and return it. With a sampling brush. Now, I will explain in detail what the conditions are. As input, the worlds come in like this, the letters come in, and the score comes in. These three types of information come in, and these worlds can be made using these letters first. Since there is a dog, we can make a in this dead, and there are three d. So, we can make soybeans, and it becomes good, so we can make a national road. And since cat does not have a t here, we cannot make a cat. In the case of dog, like dog. You can create it by using laterals. Once you create a world using laterals, the letters you used cannot be used. Because they have been used, they will be removed. So, if you make this or that in Word, the letters will disappear, so you could make them in the past. By making a word, there are cases where you cannot make the next word. And the scores below are 26, a is 1.c is 9 points, etc. a is 1.c is 9 points, etc. a is 1.c is 9 points, etc. So a is 1.c is 9 points. So a is 1.c is 9 points. So a is 1.c is 9 points. d is 5 points, g is 3 points, 5 is 2 points, so a number is entered in the position of a c d g o like this. As a result, the optimal result is 23. When choosing which one, dead is 11 points and 9:00 20 is dead is 11 points and 9:00 20 is dead is 11 points and 9:00 20 is 12 points. A total of 23 points. This is an explanation of why it is best to choose this way. If you understand the problem, let's solve it right away. First of all, in order to increase efficiency a little, for optimization, it is not that big of a deal, but I will give you a score for this world in advance. I calculated it. Using preprocessing like this, the world's score is 10 points because there is no dog cat t, and dad is 11 points from good to 12 points. Yes, so I use this acd g5 in this letter. So, I calculated the score of the world that can be created in advance. So, rather than calculating these over and over again whenever necessary, once the word is set, the score is set, so I created a table like this in advance and reused it to reduce runtime time. And backtracking is typical backtracking. I don't know if I need to explain it here, but to help you understand, I created a state space tree. I will show you how to update the remaining counters of this letter while creating a state space tree. The first one is 0 because nothing was selected, and initially we expressed the input letters in this way. Then, the light child is the score value of the tool when the tool is selected when selected. was 12, and since poison was used, the values are updated here. Cat cannot have a right child, so of course it cannot have a right child. So it goes straight to the left child. And then, so now the point is also 10.5. so now the point is also 10.5. so now the point is also 10.5. It is the same and the letters are unchanged. Then, when you select dead, the ratter for dead is removed and since dead is worth 11 points, 21 points are expressed. Good cannot be made with the current letter counter, so the light child Since you can't make it and go straight to the left child, the current point is 21 points as the maximum point, and since all 4 points have been turned, the current maximum value is 21. And because it returns to the back, which is called backdragging. When you throw away the good and go back, this letter is renewed again. I thought you were using beads, but you didn't. That's why you renew it again, and since you can't go to the light, it goes up to the back again and updates it here. So, it's updated like this. So, if you do not select dead again, this value is maintained as is and the point is also maintained at 10. Then, you cannot select a bead again here, because you need good, but there is only one o. So it becomes the left child, the letter does not change, and the point does not change. So, we were recording 21 earlier, and this time, since the value was 10, we will ignore it. So far, we want to find the maximum value, so we kept 21 as is. It keeps going and goes up and so on, and in the end, if you don't select the dock, the letter will be maintained and if you do n't select the tool, the point will be 0. And since you can't select the cap either, this part is a bit narrow, so I skipped it. If you select Goyo Dead, it is updated like this and you get 11 points. And in this state, because there are two 5s, you can select g5d. So 23 points, so 21 points was the optimal score earlier, but it is updated to 23 points. Then, Now, if you do n't select the number, it's 11 points, so it won't be updated and 23 points will be returned. Of course, it's natural, but if you don't select something, there's no point in choosing it's less than 23, so it's just It went quickly. Yes, so now, if I put this into coding, the code may seem a bit long. It may look long, but I will explain this part in more detail when I live code it. First, I will explain only the skeleton, starting with the large framework. This part is the word. This is the part where we count first and calculate the score. We calculate the world score in this way, and if we can't make it now, we put 0 in the score and preprocess the calculation in this way, which becomes the backtracking code we need. So, in order to use the return type, which is a global variable, I just put it in like this. If I go to the end, I save the larger of the two between the current highest score and the highest score so far. Otherwise, it ends here. The return of this solve function is this word of the current score. When you create a score, the score is passed on. You have made a choice. You have chosen to create the current world. That is why, if you look at the statement above, the counter value is continuously subtracted. By continuing to subtract the necessary count values ​​from this world, the continuing to subtract the necessary count values ​​from this world, the continuing to subtract the necessary count values ​​from this world, the letter counter is The update occurs, and then this function part is finished, and when it returns to the back, the subtracted part is added again to restore the original. Yes, that's why this name is called backdracking. When selected, it has this type of structure. This rumor What can you choose? I couldn't make a choice in the case of the cat earlier. So in this case, if you get caught, you will definitely not ride the part below. You will all go down. If you get caught in the cat, you have to choose. You can choose between doing it or not doing it. When you get caught in a cat, you are forced to not make a choice. If you are a child who can make a choice, you will go through this type of routine and make a choice. And of course, if you do not make a choice, you will use the force. By passing it in, the current score is maintained and the letter is also maintained. Since the letter is maintained, there is no need for a function to restore it when the function is finished. So, with the Solve function, the starting point and current point are also 0, and if you pass the letter counter, this function will take care of it. It will return the desired result to us, so it is a problem of this type where we just need to print the return as the return value. However, because it was a hard problem today, the explanation was a bit long, but if today's lecture was helpful, please subscribe, like, and set an alarm. Listen to the lecture. Thank you for giving
Maximum Score Words Formed by Letters
reverse-subarray-to-maximize-array-value
Given a list of `words`, list of single `letters` (might be repeating) and `score` of every character. Return the maximum score of **any** valid set of words formed by using the given letters (`words[i]` cannot be used two or more times). It is not necessary to use all characters in `letters` and each letter can only be used once. Score of letters `'a'`, `'b'`, `'c'`, ... ,`'z'` is given by `score[0]`, `score[1]`, ... , `score[25]` respectively. **Example 1:** **Input:** words = \[ "dog ", "cat ", "dad ", "good "\], letters = \[ "a ", "a ", "c ", "d ", "d ", "d ", "g ", "o ", "o "\], score = \[1,0,9,5,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0\] **Output:** 23 **Explanation:** Score a=1, c=9, d=5, g=3, o=2 Given letters, we can form the words "dad " (5+1+5) and "good " (3+2+2+5) with a score of 23. Words "dad " and "dog " only get a score of 21. **Example 2:** **Input:** words = \[ "xxxz ", "ax ", "bx ", "cx "\], letters = \[ "z ", "a ", "b ", "c ", "x ", "x ", "x "\], score = \[4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,10\] **Output:** 27 **Explanation:** Score a=4, b=4, c=4, x=5, z=10 Given letters, we can form the words "ax " (4+5), "bx " (4+5) and "cx " (4+5) with a score of 27. Word "xxxz " only get a score of 25. **Example 3:** **Input:** words = \[ "leetcode "\], letters = \[ "l ", "e ", "t ", "c ", "o ", "d "\], score = \[0,0,1,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0\] **Output:** 0 **Explanation:** Letter "e " can only be used once. **Constraints:** * `1 <= words.length <= 14` * `1 <= words[i].length <= 15` * `1 <= letters.length <= 100` * `letters[i].length == 1` * `score.length == 26` * `0 <= score[i] <= 10` * `words[i]`, `letters[i]` contains only lower case English letters.
What's the score after reversing a sub-array [L, R] ? It's the score without reversing it + abs(a[R] - a[L-1]) + abs(a[L] - a[R+1]) - abs(a[L] - a[L-1]) - abs(a[R] - a[R+1]) How to maximize that formula given that abs(x - y) = max(x - y, y - x) ? This can be written as max(max(a[R] - a[L - 1], a[L - 1] - a[R]) + max(a[R + 1] - a[L], a[L] - a[R + 1]) - value(L) - value(R + 1)) over all L < R where value(i) = abs(a[i] - a[i-1]) This can be divided into 4 cases.
Array,Math,Greedy
Hard
null
152
Ask question will solve maximum products sub is aa products sub is un given date has largest product and return d product non empty sequence of element with it saying ok first let's see how to solve it here 2 * This is the first one which is taking 3 = 6, the 2 * This is the first one which is taking 3 = 6, the 2 * This is the first one which is taking 3 = 6, the next one after this will be negative, so let's see how we will solve it, now we have done it to express Question Related Topics Dining Programming done it to express Question Related Topics Dining Programming done it to express Question Related Topics Dining Programming Okay here. Maximum product is all right, it will be solved, so what will be your output here? If it becomes negative then it will not be maximum. What will we take? One, we will take minimum, we will maintain minimum and we will maintain maximum. Two things, we will maintain minimum and maximum. Why? We will maintain it because there may be a case like this, I have a negative data, later another negative data came, here I have positive data, so to handle it, I need both minimum and maximum because here the product. I am doing another one, I have to handle another case, if zero is gone in between, what will happen in that case, in this case, if you multiply any data, it will become zero, then to handle it, find the minimum. In that case, I will close the minimum and make the maximum gobi maa simple Now what, when the next turn comes, what will happen in this case, tell you 72 So here is negative -72 And here pe so The maximum is 36 till now, -72 And here pe so The maximum is 36 till now, 36 here like this -4 * 9 36 here like this -4 * 9 36 here like this -4 * 9 If I take this much from here, then eight will come from here If I take this much from here, so let's open a new folder and put [ new folder and put [ new folder and put So here Maximum Products are ok After earning in music, I will slice the van to Max, I will come to the next line, but I will leave, I will take him, it's simple, all three have passed, in some languages, all three cannot pass, its alternative, now if a video of it will be made then I will tell you or you can check already then it will be updated then I will take it here then it will be messed up so I have already done it to fix it then I will do it now then I will not have any problem if it is updated Going And then to find N*, I don't need it right now. to find N*, I don't need it right now. to find N*, I don't need it right now. If after that I still need any data in which I comment, then in the net case, I used to update something in my scale. No need, now what will I do with the result, I will take max of max and our current match will be there. I know this much that my friend, everything is going well, how can I find out in a simple way, if I tell you in a simple way, before I wind up, let me tell you a little bit, what have I done, what have we done, nothing have we done. Kar Max and Karma Liya Tu Mainten Main End Data Kyun We are doing it, nothing else is doing it, so now only time will remain simple, there was so much in this video I will go now, I will meet you in the next video I had ended the video but before that I forgot to tell you one small thing, let me tell you a simple condition, this condition is written, there is no need of any condition, it will reduce it because of Max and Mini. If we are doing this, then in the maximum it will be zero in case, then it will be A in the minimum and zero in whatever and whatever. Exactly means we are also writing n here, which is going to be xid, there is a variable here which is a. So it will not make any difference if I take this case here, where in the first indication, where will be the zero from zero max and what is the minimum, here it will reach the next step in this way, then how much will it be if If I look at the photo here, it will be zero, but there is already -4 here, the smaller one, so here it will -4 here, the smaller one, so here it will -4 here, the smaller one, so here it will be -4. In this case, because we are be -4. In this case, because we are be -4. In this case, because we are also looking at N, it is not small in one, but it is not small, then it is in one. It is not big, he is also doing it as per his requirement, then now when these people come here, what will happen here also, 982 is -72, here 94 will be plus, 36 will be the is -72, here 94 will be plus, 36 will be the is -72, here 94 will be plus, 36 will be the maximum, here this is the maximum and 136 is the zero case. Now I remove it here, there is no need for this one, its condition is not needed here, you can do without it also, so I do not need to put its condition here, directly like this. It will be less, this was the little thing that I had to cover, so I started the video again and if you liked the video, please subscribe
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
1,541
hello everyone today we will be going to discuss uh question number three from today's bi-weekly contest from lead code bi-weekly contest from lead code bi-weekly contest from lead code uh by weekly contest 32 so the problem we are going to discuss today is minimum insertions to make a parenthesis uh string balanced so uh what we meant by balance parenthesis in this question is uh we have given a string s and it only consists of opening and closing parenthesis so a string is balanced if and only if the opening parenthesis uh comes before the closing parenthesis and the opening parenthesis is followed by two consecutive closing parenthesis in generally we have only one consecutive uh one closing parenthesis but in this case in order to make a balanced uh balanced parenthesis string we just have to make sure that one opening bracket is one opening parenthesis is followed by two consecutive parentheses so here ah but we don't have to ah check if the string is balanced or not but we have to check how many characters we how many minimum number of characters we need to add in this string such that we in the end the string is a balanced parenthesis for example in this sample input one we have this string okay so uh this i got first opening parenthesis then we have one more opening parenthesis then it is followed by two uh closing parenthesis so this string is balanced but in the end uh this opening parenthesis have only one closing parenthesis so we need to add one more character that is one more closing parenthesis so that this uh whole this whole string gets balanced so we just have to output one because we just need to add one more closing parenthesis so here we have this string is already balanced because this opening parenthesis followed by two closing parentheses that's we output zero so this problem can be solved by using similar approach which we used in uh in order to check if the string is balanced or not by using stack so but in this case we just have to make sure and aware of some special cases so we'll be discussing on the on while implementing the solution so first we take a stack of character st and we trade from left to right uh in a string okay i is s dot size okay now if we have two case if the ith character in the string is an opening parenthesis okay and if the ith character in the string is a closing parenthesis so if we got an opening parenthesis we just we do just nothing we just push it in the stack okay push it into the stack so sf5 and we just do i plus now if we got a closing parenthesis so if we got a closing parenthesis we can have two cases that is if our stack is empty or if our stack is not empty now let's first discuss about the case when stack is empty so when stack is empty that means we don't have any opening parenthesis for this one okay now this can be the k now and we also have to make sure that the closing parenthesis we have should have two consecutive closing parentheses that we have to just to check whether the i plus one character is also a closing parenthesis or not what if the i plus one character is in opening parenthesis okay so if our stack is empty like if our stack is empty okay then we have to check for two cases uh that whether our i plus one character is an opening parenthesis or a closing parenthesis if it's in closing parenthesis if our i plus one if a character at i plus one is a closing parenthesis then we just don't have to do anything we just uh count plus because we just have to add one opening path one opening parenthesis okay just to make the string balance because we know that we have this string just we have to add one opening parenthesis okay in order to make the string balance and we just do i plus equals to 2 because we just now move at i plus uh third index okay but what if our i plus 1 character is not a closing parenthesis then we have to add count plus equals to 2 and we just do i plus because i plus at i because the character at i plus 2 is an opening parenthesis okay this also handles that case whenever i plus 1 character when the position uh but what if the i plus one character is out of bound let's say we have this closing parenthesis then it will be out of bound right so then we have to make sure that i plus one is in the bounds of string okay and if it also handles the case like when we have only one closing parenthesis then we go to the else part and we just add count plus and we just count plus equals to 2 and we just add i plus so this is all about when stack is empty but what if stack is not empty that means we have uh one opening parenthesis okay that means we have uh one opening parenthesis just before the closing parenthesis okay so the and now we in this case also we have two cases when i plus one but the character at i plus one character is an uh is a should is closing parenthesis and if it's not so if it is closing parenthesis we just don't have to do anything we just have to do this i plus equals to 2 okay but if it's not a closing parenthesis then we just have to add a closing parenthesis is here and we just have to do uh i plus okay and we just have to also make sure that i plus one character is in the uh bounds of the string and if it's not in the bounds of the string then we just have to do it also handle that case two because we just have to do i count plus and i plus yeah and also make sure that uh for when the string when the stack is not empty we just also pop out the last opening parenthesis from the stack so that's it uh we just written in the end answer and okay like count we took count and count equals to zero yeah uh sorry i just forgot one more case where like we don't have any closing parentheses we just have uh like what if in the end we don't have an empty stack like we have followed by with couple of opening parenthesis oh all right so here for all opening parenthesis we should add to closing parenthesis so while our stack is not empty we just have to pop the stack and we just have to count plus equals to 2 yes so all right okay 1 0 3 twelve five and let me submit it accept it so thanks for watching guys i hope you got the solution of this problem uh see you in the next video
Minimum Insertions to Balance a Parentheses String
top-travellers
Given a parentheses string `s` containing only the characters `'('` and `')'`. A parentheses string is **balanced** if: * Any left parenthesis `'('` must have a corresponding two consecutive right parenthesis `'))'`. * Left parenthesis `'('` must go before the corresponding two consecutive right parenthesis `'))'`. In other words, we treat `'('` as an opening parenthesis and `'))'` as a closing parenthesis. * For example, `"()) "`, `"())(()))) "` and `"(())()))) "` are balanced, `")() "`, `"())) "` and `"(())) "` are not balanced. You can insert the characters `'('` and `')'` at any position of the string to balance it if needed. Return _the minimum number of insertions_ needed to make `s` balanced. **Example 1:** **Input:** s = "(())) " **Output:** 1 **Explanation:** The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(()))) " which is balanced. **Example 2:** **Input:** s = "()) " **Output:** 0 **Explanation:** The string is already balanced. **Example 3:** **Input:** s = "))())( " **Output:** 3 **Explanation:** Add '(' to match the first '))', Add '))' to match the last '('. **Constraints:** * `1 <= s.length <= 105` * `s` consists of `'('` and `')'` only.
null
Database
Easy
null
904
Problem is today's problem, you have to solve this fruits in basket so let's get into this problem. So today's problem is that you have put two food baskets inside it and told yourself that you have only one fruit in one basket. Now you have given yourself many different numbers of fruits and you have to tell yourself what is your maximum number of fruits out of all these fruits. You can put them in both the baskets and tell yourself the maximum number of fruits. Now, there is a small condition of its own in this, that is, if you have started with any fruits, it is if you have started with your first root, now it is not necessary that you should start with your first fruit only. You can also start from the fruit, but if you start from your first route, then you cannot do this. Skip the second fruit and come to your third route. If you are starting from any one fruit, then your You will have to take all the fruits behind it till the last, till then the condition of your basket becomes false. If any fruit is skipped, along with it, you have to return the answer with maximum fruits. This is a simple question, so if you understand this question from this example, then in this example you have given yourself only two types of fruits and you have only two baskets, then you can take all these fruits in your basket. And three is your answer to all the foods you have given yourself. If you talk about this example, then in this example you have given yourself three types of fruits, one is zero type fruit and one is first type fruit. And this is our second type of fruit. We have only two baskets and in each basket we can keep only one type of fruit. So if we keep our type of fruit in one basket and the first type of fruit in the other basket. If you keep your second type of fruit, then you have nowhere to go, so you will not do this. What will you do if you did this? You kept your first type of fruit in one basket and your second type of fruit in another basket. What will you be able to do if you keep one fruit, you have kept one fruit once and these two fruits of second type and I have kept both the fruits in one basket, then how many fruits are you taking in total, you are taking three fruits and three Your answer is, if you look at it from this example, then in this example too, keep yourself with three types of fruits, but if you start from the beginning, then you will put the first fruit in one of your baskets and put the second fruit in one of your baskets. There is no space left and we cannot do this by skipping the third fruit and putting these two fruits back in the second basket because it is not possible to do this. We have already told ourselves that we can start with any fruit but After that, you cannot skip any of your fruits. Okay, so what will you do, you will start with your second fruit, put this fruit in the basket, then put this third fruit in another basket, and then return to these two. If you want to solve all your questions then Let us see how we will solve this question. To solve this question, I have taken this example. Now what will be our answer in this example? Our answer will be six, three will be our zero-root fruits and three will be our own zero-root fruits and three will be our own zero-root fruits and three will be our own first. There will be types of fruits, okay, so six should be your answer. If you take this stack of yours, then your answer would be five and here you are getting the answer six and you want the maximum answer which is your six, okay now. Let us see how you will solve this, then what will you do to solve this, you will travel in your simple map, that is, you will keep putting all the values ​​in the map and whenever the size of your map putting all the values ​​in the map and whenever the size of your map putting all the values ​​in the map and whenever the size of your map becomes more than yours, that is. If you come to know that you have three types of fruits, then what will you do? In case yours is the first type of fruit or will you make a race with the one that came first, that you want only two types of fruits? Okay, so what did you do? First of all, you took this first fruit of zero type, put it in your map and also closed your answer that now you have got a fruit in your answer, then what did you do with the zero type? There was only one fruit so here you made it a plus and in the answer also you made it 2 so that you have got two fruits, then when your third zero came, here too you made it a plus and made it three and here also you made a three. Given that I have got three fruits of the same type, now I have adopted them, so what did I do by becoming one and stopped corresponding. In this case too, the size of your map is yours, your two are the same meaning, what do you do with Princess A before, what do you do with Princess A after? Let's take it and Apna has also started doing it for the second time. Apna has two types of fruits, so as of now Apna does not have any invitation condition, Apna will say that she has got four fruits, three are of one type and one is of another type. Okay, then similarly it will happen for both of them that there will be three here and you will get six pilot fruits, that means you will get six fruits, one or two, three will be of zero type and three will be of first type, aaya tu to spawning like. When you expand your map, you will come to know that the size of your map has been reached, that is, you have got your three types of fruits, like if your three types of fruits are available, then what will you do to check this, you will get all the growth type fruits in your map. If you remove it from the map, your size will return to yours. How many fruits do you have? One, in your map, these three fruits are of first type and this one fruit is of second type, so what will be your answer? Answer is 4 but you have already got answer 6, hence you will not update your answer. Then if this last second type of fruit comes then you will make it a plus and still your answer in this case means this one. In your condition, my answer is five and I am already answer 6 of the patient, hence I will not update my answer. apneutation is over and we will return whatever our answer is in the last, once we see its code, then in its code, I have first created a knotted map inside which I will reduce this one, then I have created a great map inside my area. To do this, another answer has been created inside which we will store it manually, then I created it like this, now how I traded like this, let me first explain to you, Han, I have kept the concept of sliding window, what I did inside it. If you have taken the numbered fruit, then what will you do, meaning both of these become zero and plus van's Apna means that you have got one of your fruits, then what will you do? Answer, we will get one fruit stored. Similarly, then what will happen to Apna? K plus will come here after getting plus, okay then what will happen to you, if the value of I is one, the value of I is zero and here you have done plus, similarly in your answer, the fruits will go till here, meaning as soon as the value of K reaches here, you will be on. Will reach means what will we do by pressing plus icon means we will make zero here, if we remove those three zero fruits, then one open pressed once, then did it twice and then did it three times. After pressing plus three times, it has come here and these are our All the three fruits of zero type have been done. Now we are seeing here. Okay, so as soon as Apna has reached where it is, Apna Three and Three Six Seven means it has reached the six position and Apna has reached the third position. If you have reached 6 - third position. If you have reached 6 - third position. If you have reached 6 - 3 + 1, 3 + 1, 3 + 1, then what is your answer? What is your answer? Four has come, but you have already got 6 in the answer, so you will not update it, similarly, then you will look here, like this, you will move on, so this is what I have said here. What I did was that I iterated it completely, after that I said that in your map, add plus to the value and then see that if the size of your monastery is greater than yours, then what will happen to you, what will you do when yours? Till the size of your account, that is, the first value of your account which was correct in the map, which was the highest value in the map, keep mining his account till it becomes zero and such that his account becomes zero. So race it from your map and keep adding plus to your i, then your i will be three times and your i will go here and there, ok and what will happen to your, store the maximum value in your answer and min's i plus van's. And in the last answer, if you have your answer, then return your answer, then it is absolutely submitted, that means it is an accurate solution, now you can consider it, hope you have understood, if you like the video, then like the video. Do subscribe the channel and if you have any doubt then please mention it in the comment box. We are always ready to help you in doubt sales. Thank you so much for watching. Have a nice day.
Fruit Into Baskets
leaf-similar-trees
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
Tree,Depth-First Search,Binary Tree
Easy
null
847
hello everyone welcome to day 27 of the february decode challenge and the question that we have in today's maximum width of binary tree here in this question we are given a binary tree and we need to identify the maximum width that exists among all the levels in this tree as soon as you read the word levels you should get the hint that bfs traversal is the way to go and how do you define width value width at any level is defined as the length between the end nodes the right most and the left most non-null nodes left most non-null nodes left most non-null nodes wherein the null nodes between them are counted into the length calculation so remember this definition and let's walk through a few examples here they have provided us with this binary tree and the maximum would be equal to four how we have five this node this is the leftmost node this is the rightmost node how many nodes are in between them one two three four so we have to count the null nodes as well that exists in between them so the total bits becomes four let's walk through this particular case what is the left most node left most what is this right most node is this and we need to identify the bits between them so the maximum bits would be of two units and this is what the answer is let's walk through this particular case here the leftmost node happens to be this one however there is no right most note to complete it so we have to skip this level we will go back to the previous level which is three and two what is the maximum bits between them it is of two units and the answer is two also i would like to highlight one more case which is not that intended from this question which is this one we have 1 3 2 5 3 6 46 15 and from the look of it uh what would be the answer corresponding to this we have 46 here so we have null and this is the leftmost node 15 is the rightmost node so upfront it may appear to you that the maximum would be equal to one two null here because we have null here we have three here so we will when both the children are null three four and five from the look of it you may feel the answer should be five however that's not true the answer for this particular case would be 7 and this is the most important test case which most folks will tend to miss how will it be 7 i'll explain the presentation so let's quickly hop on to it maximum bits of binary tree lead code 662 it's a medium level question on lead code and i totally feel the same so let's go back to the basic example we have a binary tree with two nodes and one is the root of the tree the left child is three the right child is two so what can i do i can assign weights onto this nodes so the root will have zeroth weight the leftmost node will automatically inherit the weight twice the parent node so it would be equal to two times of zero which again makes it zero and the rightmost node will acquire the weight two times the parent plus one so it would give us 2 into 0 plus 1 which is 1. here we did 2 into parent i'll tell you why will this work and how will this work once you have calculated this you will start the bfs iteration level by level and what do you will calculate the bits between the leftmost node and the rightmost node it would be equal to the leftmost node weight is zero the rightmost node weight is one so one minus zero plus one would give you the answer which is 2 in sync with our expectation let's proceed ahead let's go and start assigning weights to it we have 0 to the root next we have 3 so 2 into 0 gives us 0 so we'll have 0 here we'll have 2 into 0 plus 1 so we'll have 1 here let's proceed ahead we'll have 0 here 2 into 0 is 0 2 into 0 plus 1 is 1 here we will have 2 into 1 plus 1 because we're moving we are moving in the right direction so this will give us 3 and let's go level by level we will calculate the value for this particular level it will give us 1 minus 0 plus 1 in sync with our expectation the maximum width for this particular level happens to be 2. we did it in the previous section as well with respect to this what is the leftmost node this one what is the rightmost node this one so what would be the value 3 minus 0 plus 1 and this will give us 4. so far the algorithm seems pretty easy and simple and we have appropriately calculated the expected value for width and so once you have calculated these values across levels you can pick up the one which gives you the maximum answer now comes the most interesting case this is a same tree that i showed in the presentation so we have 1 3 2 5 3 6 46 and 15. the answer for this turned out to be 7 as i how let's have a look at it so we have 46 here we have null here and what people tend to miss is this null node so we have null here we also have two nulls here which upfront doesn't exist but yes if you think that it's a complete binary tree then it will exist now if you count the number of nodes between 46 and 15 it will turn out to be 1 2 3 4 5 6 7 which is in sync with our expectation the answer should be 7 rather than 5 people tend to miss out on these nodes as a result of which their algorithm will never work this is the most important part of this problem which is not that intended from the description now comes the question our algorithm be appropriately fit into this the answer is yes how let's walk through it let me just change the color of pen and let's get started so we have zero here we are moving towards the left so we'll multiply the parent value weight with two so zero into two is zero here we'll have one zero into two plus one let's proceed ahead next we have five and here the weight would be zero here the weight would be one here the weight would be zero and let's move towards this part of the tree here we are moving towards right so we'll multiply the weight by two and add one to it this gives us three let's proceed ahead since here we are moving towards the left most direction not the right one so we'll multiply the parent weight into two so parent two into parent will give us the weight for this particular node and it turns out to be six now let's use the formula and calculate the width at various levels here the width would be equal to 1 minus 0 plus 1 so one possibility for answer turns out to be 2 absolutely correct here the width would be equal to three minus zero plus one what is the node value here three so three minus zero plus one gives us four so the other possibility counts out to eight to four and here the last possibility would be equal to six minus zero plus one which is seven and the maximum width that you were able to identify turns out to be seven and this becomes the answer to conclude it further let's quickly have a look at the coding section here i've taken a max fit variable here i have taken the map and the key would be the tree node and the value would be the way that we have allocated to it so this is node comma weight and i have declared as a hash map i have put the value for the root as zero and i start the bfs reversal i add the root into the queue while my queue is not empty i calculate the size i calculate the weight associated with my left most um node in my map and i use q dot peak for finding out the left most node corresponding to a particular level this is slightly different and unusual but that we usually don't peek out elements up front from a particular level but if you carefully visualize this will give you the left most weight value associated with the leftmost node while size minus is greater than 0 i pull out the head value i calculate the current width the current would be equal to map dot get head minus left plus 1 and i compare it with the maximum width variable that i have already calculated if moving ahead if my map dot head is not null i what do i add it to my queue and i update the weight associated with my head dot left node that is equal to 2 into map.head that is equal to 2 into map.head that is equal to 2 into map.head map dot get head this is important and in case my right is also not null i add it to my queue and update my map with write dot head node comma 2 into the parent's weight value plus one so two into parent's weight value plus one here we simply use two into parent's weight value once i'm done with this i simply return the maximum weight that i have calculated so far awesome uh it is six seven times better there can be slight improvement done uh over here but i think it's fine if you are able to come up with this kind of an approach in an interview this brings me to the end of today's session if you are interested in more tree playlist then i am attaching the link in the description below do give it a shot and also don't forget to like share and subscribe to the channel for more updates from coding decoded thank you
Shortest Path Visiting All Nodes
shortest-path-visiting-all-nodes
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. **Example 1:** **Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\] **Output:** 4 **Explanation:** One possible path is \[1,0,2,0,3\] **Example 2:** **Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\] **Output:** 4 **Explanation:** One possible path is \[0,1,4,2,3\] **Constraints:** * `n == graph.length` * `1 <= n <= 12` * `0 <= graph[i].length < n` * `graph[i]` does not contain `i`. * If `graph[a]` contains `b`, then `graph[b]` contains `a`. * The input graph is always connected.
null
null
Hard
null
108
hi guys welcome to one more video in this video we'll take a look at convert sorted array to binary search free difficulty level is easy so the problem title itself gives out that we would be given a sorted array and then we need to convert it to a binary search tree so it's kind of a d serialized operation like we're given an array or string and we need to deserialize it to binary so that's the problem statement however there are two important things first of all it's a binary search tree so what is a binary search tree so binary search tree is a binary tree where root node is always greater than the right i mean left child so root is greater than the left hand left child is smaller than the root and right child is always greater than root so root is kind of middle left child is smaller and right child is bigger so that's a binary search tree and what we need to make sure it's that it's a height balance minor tree so what is height balance monitoring means so height balance tree means that the height difference between the complete lift or complete left tree and complete right tree cannot be greater than one so if the depth of left tree is let's say five then depth of right tree can be either four or six or five it cannot it can differ but not more than one so that's height balance tree so that's the problem uh we have couple of examples we'll do those examples on the whiteboard and we'll understand how we can solve it and then come back and run the code okay so this is our array we'll take our array as minus three to three and we'll try to convert it into a binary search tree which is also height balance and this is our complete code so this is a recursive function and all we are doing is we are splitting the array into two half so what we do so we have all the elements in the array we take a middle element and we put that as our node and everything left from that node or the middle element is part of the left tree and everything right from that middle is part of the right tree and we just keep we recursively keep doing that until all the elements are done and we get our tree so let's see how will our draw out or how the tree will become so what we do is let's say our this is our array so from zeroth element sixth element right and when we do middle so obviously zero is our middle element so that's our first node and what we do we say this is our left tree and this is our right tree now we recursively call those uh as left node and right node with low and mid minus one and mid plus one and high so this is our left tree this is our right tree now let's do the left tree first okay so now this becomes our array right minus 3 minus 2 minus 1 and what we do we repeat the process take the middle number minus 2 and then this is the left tree this is the right tree so this will come out as minus 3 and minus -1 and minus -1 and minus -1 and that's the left tree now left part is done now let's move on to the right part we'll follow the same process we'll take out the middle element which is two this is the left tree this is the right tree so this is the left tree this is the right tree there you go so we have our binary search fee which is also height balance so simple process to make our binary search free from and sorted array so let's take one more example let's take a bit bigger array and let's see how the uh how our binary search tree looks like in that case okay so this is our second example we just added two more elements to our previous array we added minus four and four so a little bit larger array not that pretty large but still so let's try to draw the tree from this array using this logic so what we'll do is we'll pick the middle element and then we'll say this is your left tree and then this is your right tree right same process so we'll have zero as our node and then left tree and then right tree right so let's first do the left tree so now in this one our middle would be again minus 3 so minus 3 would be the root and then this would be the left tree right now over here what will the middle in two elements so minus 2 would be the middle there's no left there's only right so minus one would be the right node and likewise same here in this array the middle would be two and left tree would be one right tree right so in three four three would be the middle element root and then four would be the right shadow right there's no left child so there you go guys if you look here the height difference between these this left tree and this right tree there is only one and likewise height difference between this left tree and this right tree is one so it's height balance also it's binary search free and that's what the question needs so there you go guys uh i'll spare you from looking at my code which is like written with a very bad handwriting let's go to the vs code where the code is nicely indented consistent fonts and everything so let's do that okay guys this is our final code so we have our main method in which we are taking those two examples of array and then we are passing it to sorted array to bst method now this method in turn calls that make bst right and in make bst what we do is what we discuss on the whiteboard right take the array find the middle element and then middle element becomes a node and then left child of that node is the complete left part of the array and right child of that node is complete right part of the array i figured out left right for you guys so anyway guys uh i don't have uh i haven't written any way to like print array or print the tree so we just have to run it and assume that uh it does what it's supposed to do so i'm sure you guys believe me so there you go guys the code is there uh i'll put the link to the code in the description and if you guys like the video give me a big thumbs up let me know your feedback and suggestion in the comments uh this is not the only way to do it there are multiple ways but this is the way i found it which is more logical so if you guys have a better way let me know and then as usual subscribe to the channel for more videos see you in next one
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
134
problem is called a gas station problem and it has been asked quite a few times in amazon google microsoft uber and apple interviews so let's see what is this problem so in this problem you have a few gas stations so this array or list of gas denotes the different gas stations so gas station 0 1 2 3 4. so let's draw them here so you have to think that they are in a circle so you visit these gas stations in a circular fashion and you can start from any of those so let's say this is zero this is one this is two this is three and this is four these are the five gas stations and these are different capacities which you can fill your car with so when you go to gas station 0 you can take one unit of fuel from this and this cost which is of same size as this denotes that cost 0 will denote that you need at least 3 units of fuel to go to next station that is if you are at 0 next would be 1 so you have to go in this clockwise fashion so you need three units to go from zero to one so let's say you start from zero so you can fill with your car with one unit of fuel but you need three units to go to one so you cannot do that so initially your car is empty the tank of your car is empty so you will this is not possible you cannot start from here similarly when you start from here you will fill it with two units so you have two units of fuel but at one you need four units to go to two so again you cannot make this trip so you will also not start from here so what thing we are checking that gas i should be greater than or equal to cost i in order to start from there so we can think of this as a difference or surplus so let's call it delta gas i minus cost i this should be positive in order to start so till you are getting negative you cannot start now here look at this gas you can fill is 3 but you need 5 again not possible here you can fill your tank with four units of fuel and you need just one unit to go from three to four so you will you can start from here you will start or not will depend on the future values but here you can definitely start since here you will have surplus so here we filled with plus four unit then we came here we lost one unit because we need one unit so minus one now we have a surplus of three at 4 we can fill another 5 so 3 plus 5 8 now we have 8 and we come here and we lose 2 units of fuel so now we have 6 here so we fill with one so seven we consume three when going here so minus three so now we have four and we fill with two so six then we consume four units so minus 4 now we have 2 here and we fill with 3 so 5 and when going from here to here we need 5 units so minus 5 and now it becomes 0. so we have completed a trip we started from here and we reached here so this is what we are required to answer here so which what should be the starting index so in this case the answer should be 3 because we can start from here and reach a round trip and another thing to note is that let's say the cost is the total cost is more than total gas available then definitely you cannot make any trip no matter where you start uh because let's say you have cost is 50 units of fuel and total available fuel is just 45 units then no matter where you start you cannot complete the trip so this is another point this total should be always more than this or that is total delta sum of deltas should be positive or 0 greater than equal to 0 in this case it was exactly 0 so that was good enough now is the problem for finding the starting point so you can also draw this circle here 0 1 2 3 and 4 so you start in this direction and then go back to 0 so let's see how we will find the starting point so let's take a general example let's say we have some points and i will draw just one point let's merge these two into one this cost and gas with this delta that is gas minus cost so it should be if it's greater than equal to 0 at a given point we can start from there so what we will do we will keep track of two variables we also need this total maybe you started from here and reached here but overall total was less than zero this total delta then we cannot complete the journey so we keep track of two variables total delta and current delta so let's say it's negative here negative so you start from here you see it's negative so you come here you reset everything to zero so initially it's zero both are zero we have not started yet so when it's negative let's say it's negative a negative b then it's plus c so this will keep incrementing you will keep accumulating this is nothing but accumulator and in the end we will just use it to check if it's less than zero or not if it's less than zero we will straight away return false otherwise we will return the starting point so you can even forget this for now this is just accumulated no other purpose so we come here we check what is current delta so current delta will be current delta plus this value let's call it so this is nothing but gas i minus cost i so this is the delta so we are adding so initially it was zero now it becomes if it's negative then it's minus so if it's negative we will not start journey from here or whatever was our previous starting point so we started from some point and we moved to some points and we reached here and now it has become negative that means this starting point was invalid because when we start from here now once we reach here it's negative so it was false it was the wrong starting point we cannot complete the journey so what can be the next starting point after this why not here or here let's see we started from here and this point was positive this delta was positive that's why we started otherwise we cannot even start next let's say it was also positive so you'd say that why you reset the starting point only when the current running delta becomes negative why not try from this point also this is also positive we don't try from this point because when we started from this point when we when our car reached here this is the starting point so our fuel was zero so it was exactly zero when we came here and we loaded our tank with this fuel so when we go from here to here we already have something positive if it becomes negative we are resetting it anyway so we are not resetting it that means we reached with some positive capacity or in the worst case may be 0 not less than 0. so we reached with some positive capacity so obviously this point is better because if you start from here you reach this point with some positive delta and then you will add this value also the tank the fuel capacity at this station so total will be more so you have this fuel capacity gas i this you will load and you already reach with this positive delta so now it will become plus delta but if you start from here its value will be just gi so it's always better to start from here so that's why starting from any of these intermediate points will not be better than this one so we will start from here and when we the running delta becomes negative then we know that the starting point was invalid and if starting from here we reach a negative value then starting from here also we will reach negative when we reach here because when we start from here our tank will have even less value gi when we start from here our tank had gi plus delta so gi plus delta becomes negative that means gi will also become negative so this was the best starting point that we chose and still we got negative so this was invalid so next starting point will be 1 after this because this was negative anyway that's why the overall become negative so next we will start from here and again the same logic if it's remaining positive we will continue if at any point of time it becomes negative then we start from here and when we reach the end and the value is greater than equal to 0 then we know that from this starting point s we have reached here with some positive capacity left then we check if the total delta is greater than 0 or not so if it's less than 0 no point in checking further return false total is less than 0 no there is no way we can reach but if this total is greater than 0 or equal to 0 then return this starting point this will be a valid starting point now in this problem we have seen that from here when we started from here we did not face any such situation where it became negative otherwise we would have reset it we did not reset till the end that means from here we have reached still here now our only concern is that we have to prove that with whatever capacity we have here delta we can reach from this 0 till this node and if we can prove that we are done so this is now guaranteed that t delta is greater than zero otherwise we will return false so now we have these things so we have this is the starting point from there when we started we reached end point so let's call it n for nth point and this is zero starting point and this is the last starting point that did not violate anything and we still end so reaching from here to here is valid we have seen and total delta is greater than zero or greater than equal to zero 0 now we have to prove that we can reach from 0 to s in this round trip so after this we go here so at nth point we added the capacity of g n minus 1 and subtracted cost n minus 1 and if it's positive that means we can go to 0. so from s we can go to 0. so we are here at 0. so here we will again add the cost for 0 plus g 0 and subtract cost 0. so we have to prove that from 0 we can reach s with this surplus plus delta we reached here with plus delta so let's say uh we cannot reach from 0 to s let's prove it by contradiction so let's say from s to n we successfully came then from n we go to zero because it was greater than equal to zero this difference now from zero we started moving at some direction at next gas stations and somewhere at this gas station let's say point p it became negative so if we face such situation then we will say that we cannot complete the trip when we start from s but we have to prove that such point will not exist if total delta was greater than equal to 0 this thing so let's assume that there is such point where it's negative then what is the condition for this to be negative we started from here when our capacity was 0 so this point let's call it x this part and let's call it this part as y and this part as z so x plus y plus z will be this total delta so this we know that is greater than equal to zero this is equation one this is same as this variable that we were keeping track of here cumulative sum so this is greater than equal to zero otherwise we would have returned earlier only so this is first equation next we stop here that is from s we cannot go past five we go past p so what this means this part is x and this part is y so that means this is less than zero that's why we have got a overall negative when we reach here we started with 0 now it's negative so this x plus y is negative this is second so x plus y is negative okay this is negative and this complete thing is positive so z is positive now if z is positive from this first and second equation if we combine this clearly z has to be positive then only this negative plus some positive will make it positive so if z is positive we would have started before only not s why because uh we had some positive values let's break the z this is z we are looking at z so z will have some positive some negative some positive we are merging positives together so this if we have plus then we would take it as one plus so it would have different regions of positive and negative and this overall is positive we are in the contradiction part only so if let's say this part so if this positive was more than negative that is this much positive and this much negative so this positive is more so if we start from here when we reach here we will still have some positive left and then this positive again will add to it so we will have even more positive and we know that it's positive so we will successfully cross this so we would have never reached negative here we started from here because just before it was negative so in that case we would have started from p only so this is the first case where this positive was more now let's say this positive is less negative was more then what will happen we start from here when we reach here overall it's negative so we would have started from here so this part is now negative overall sum this plus let's say plus 2 minus 4 so this overall becomes negative so now it becomes minus plus minus so we would have started from here and we had said that this complete thing is positive so this thing also will be positive so again by the same logic if you start from here you would cross this with positive since the total is positive so that contradicts that jet cannot be greater than zero so z will be less than zero now we arrive at a contradiction from one and two if such point p exists then from one and two this z has to be positive but we have shown that z will be negative that's why we started from here so we arrive at a contradiction and such point p will not exist at all so what will be our strategy what we had done we started from here we kept two variables one is for running delta or surplus other is cumulative this cumulative is not used anywhere it's used just when we complete this iteration we check if cumulative is negative return false else return the last starting point and we started from here and we at every point we added this value to both the current delta and total delta and at any point of time if current delta is negative then we reset it because our starting point was wrong so we start from next point so that's why we reset and finally when it's greater than zero then we return the starting point so let's write the code for this understanding is this is more tough writing the code is very simple just a few lines of code and in this problem it's given that it's a unique solution but that does not make a difference we are already picking the best starting point possible so even if it's not unique we would return a valid starting point both sizes are equal you can pick any of those total surplus it's not the total fuel will be the sum of all values here and we are subtracting total cost so total surplus equal to zero and current surplus or just right surplus equal to zero next uh starting point let's denote my capital s is zero this is the first starting point gas i minus cost i and the same thing will be added to surplus so if surplus becomes negative then the starting point was wrong so we reset it and starting point s becomes next point because this current point is a big negative that's why the total became negative or related was positive and when this loop ends we will check if this total surplus is negative then return uh minus one so if the solution does not exist you have to return minus one otherwise the actual index so we can combine it into one return with this statement ternary operator then return -1 else or return the then return -1 else or return the then return -1 else or return the starting point s and let's see so this answer is correct and the solution is accepted so now what is the time complexity of this solution we are just iterating through this array both are same size and we are traversing from left to right so this is o of n so time complexity is o of n and space we are just keeping a few variables like total surplus and starting point so space complexities of one now let's write the same thing in java and python and the solution is accepted in java also finally python so minus 1 if total surplus is less than 0 else 7 else s and the python solution is also accepted
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
15
on everyone so today we are looking at lead code number 15. it's a question called threesome okay so this is a very popular question it builds off of its predecessor which is a is leak code number one which is twosome also extremely popular and we're going to look at three different ways we can approach this we'll look at a brute force strategy and then we'll look at a more efficient strategy on approaching this and we can see here that this is very frequently asked amazon facebook in the last six months it's one of the most frequently asked types of questions two sum and threesomes so it's good to be familiar with this pattern and understand how to solve this and the drawbacks and the different strategies to approach this particular problem okay so let's take a look at the prompt given an integer array nums return all triplets num of i num of j num of k such that i does not equal j i does not equal k and j does not equal k and nums of i plus numbers of j plus nums of k is going to equal zero notice that the solution must not contain duplicate triplets so here we have an input of minus one zero one two minus one and four and we have our triplets of minus one and 2 and minus 1 0 and 1. empty array is going to return an empty array and nums of 0 is also going to return an empty array okay so let's take a look at different ways we can approach this let's see this input is minus one zero one two so we're gonna have minus one uh let's see here what was it minus one zero one two minus one and minus four let's just double check make sure that's right zero one two minus one minus four okay so what we wanna do now we can do this in a brute force way with just three for loops okay i'll quickly kind of go over that strategy here let's say we have an index i an index j and an index k right and we can just check does this equal zero do the three values that these indices equal zero this one it does so what we're going to do is just put this in a result we'll go ahead and put in -1 0 and 1 we'll go ahead and put in -1 0 and 1 we'll go ahead and put in -1 0 and 1 and then move the k-th into c and then move the k-th into c and then move the k-th into c forward so does this equal 0 no it does not and then what we do is we go back and we increment our j index whoops okay we'll go ahead and increment j and then just rinse and repeat all right so now j will be over here k will increment and we'll go and find all the combinations of three values that equal zero now we may get duplicates so what we could do is we could create a hash set the value convert the arrays stringify them set them as the keys and then make sure that and pull out the duplicates make sure there's no duplicates okay so that's one way we could go about this what would be the performance on that let's kind of analyze that okay let me clear this out here so if we're doing three for loops what are we gonna have to do space or time wise well it's going to be o of n cubed on time okay if we use the hash method to remove the duplicates it's going to be o of n space but we might be able to figure out a way uh to check if we've been there before and we might be able to get this in constant space we actually should be able to get that in constant space but the time would be really bad we're going to get o of n cube time actually we would not have constant space we've got o of n space because we're going to have to return all the triplets which could be worst case the size of the input okay so not really that great now if you're familiar with the problem twosome we can use a modified approach that we used in two sum to solve this one okay so what if we use a three point our approach here okay so we have um i j and k but we do it a little bit differently so let's say we have the ith index here we're going to start with i as our first value and we're going to uh flip the operator so we're going to flip it if it's negative we'll make it positive it's positive we'll make it negative so let's just say target is going to equal and we'll call this input array nums okay so we're going to do nums of i times -1 and all that's going to do is times -1 and all that's going to do is times -1 and all that's going to do is just negate it so if we have one it's going to turn it into one and now all we have to do is in this portion of the array the rest of the array we can just run our regular twosum strategy and see if the target if it equals a target we just go ahead and flip that sign again and take the two values that equal that target package it into a sub result and then pass that push that into a final result okay so let's kind of just walk through that i know that's a lot to take in but let's just kind of walk through what we're going to do and also if we're going to take this approach we're going to have to sort this input array okay so we have to sort it if we're going to use that two-pointer approach going to use that two-pointer approach going to use that two-pointer approach so let's just go ahead and do that let me clear this out let's go ahead and clear this out and take a look at those inputs again we have the input of minus one zero one two minus one and minus four okay so the first thing we wanna do with this nums here is sort it okay and when we sort this what's our cost going to be it's going to be and time complexity it's going to be an n log n cost that we're gonna have to do for this okay so now that we have sorted this let's go ahead and look at what this looks like sorted we're going to have minus four minus one zero one and two okay so we have just we've taken that input array and we have sorted it now what we're gonna do is we're gonna basically run through this array iterate through this array but at every iteration the rest of the array we're gonna run two sum on okay so i'll just kind of step through that so here we have i and now we're going to go ahead and take everything from this index here the i plus one index which is where i'll set j and the end of the array which is where k will be and now j and k are going to act like two sum with the target being the value at i with a flipped uh flipped operator like a flipped symbol so if it's positive it's going to be negative it's going to be positive because we want the target to be zero so let's just go ahead and walk through that we're going to have a target okay and from our sorted numbs array we're going to go ahead and take the i element so nums at index i and we're just going to multiply it by -1 to flip the symbol on it by -1 to flip the symbol on it by -1 to flip the symbol on it now what we're going to do is we're going to run two sum on the rest of the array on the j and k so we're going to say okay does j plus k equal the target which is four okay the target is going to be four in this case uh no it doesn't okay and is if it doesn't then is it greater than is the combination of j and k is it greater than four no it's not if it's not greater than 4 then we're going to increment the jth element okay here we're going to do the same thing is the target which is 4 is the sum of the value at j and the value at k the sum of those two does it equal uh does it equal four no it does not is it greater than four no it's not it's less than four if it's less than four we're going to go ahead and increment j we're going to increment j all the way until we get to our base case uh where j has to be lower than k we break out of that okay so there's no viable sum there all right so let's just go ahead and remove all this now what we're going to do is go back to our main loop and we're going to go ahead and increment our i okay so now i is going to increment here and we're going to have j and we're going to have k and now we have to check does we're going to flip the target so the target now is 1 minus 1. we're going to go ahead and flip that so it's going to be 1. and now we check does the sum of the j-th value and the k-th value j-th value and the k-th value j-th value and the k-th value equal 1 yes it does okay because 2 plus -1 is um 2 plus -1 is um 2 plus -1 is um is one okay or one minus two is one okay so now what we're going to do is in our sub result we're gonna go ahead and re-flip that we're gonna go ahead and re-flip that we're gonna go ahead and re-flip that target so we'll go ahead and put that back to -1 back to -1 back to -1 and we're going to add the value of j and add the value at k okay the sum of all three of those equals zero and now we move on we go and check increment and decrement k and we check does that equal our target which is one okay so the sum of one zero and equals one and that does equal our target so now we're going to do the same thing we're gonna flip our target which is going to be -1 and our target which is going to be -1 and our target which is going to be -1 and we're going to add 0 and 1. okay and now we decrement k and increment j and we're going to see we're out of range and we move on so that's the basic idea now there is a bug with this approach there is an edge case here in the edge cases the solution set must not contain duplicate triplets okay so that's a tricky edge case here where let's take in another example and if this solution right here is not clear i suggest just stepping through it just writing out the numbers and stepping through it so it becomes clear or if you're not clear with how we're kind of working this part of the solution i suggest reviewing twosome reviewing the solution for twosome okay so now let's say we have an input we have an edge case here or we have an input where the numbers are minus two zero 0 2 and 2. okay and so what's going to happen here is let's say we use that approach this is already sorted but let's just say we use that approach we used before we have the ith variable here we have j here and we have k here well this is going to equal zero so we're going to get minus two zero and two but now when we decrement j and uh or when we increment j and decrement k we're going to see it's the same numbers and now we're going to get a repeat we're going to get a duplicate which is not what we want okay so what we need to do three things okay we're going to have an outer loop and then we're going to have an inner loop where we're basically performing two sum and we'll do we'll use a helper function to accomplish that but what we want to do is first you want to check if we have if the ith variable and the previous one i minus 1 if these are the same okay then we just want to move we want to move i forward we don't want to deal with any duplicates okay so that's what we want to do in the outer loop we want to first check have we already checked this number okay so if i increment and the previous number is the same number as the current number then we just want to increment even further we want to get out of any duplicates so that's what we want to handle on the outer loop on the inner loop what do we want to do okay let me clear some of this out here what we want to do on the interlap is the inner loop is the same thing we want to handle any duplicates and the way we do that is let's say we have our ith variable here our jth variable here and our kth variable here and we have gotten our first result here subresult now we go ahead and increment j and decrement k and what we need to check is while k is equal to its uh previous element so k plus one so while these are equal we need to just keep on decrementing k and similarly while j is equal to its previous element j minus one we need to keep on incrementing j and if it gets out of the range we just break out of there okay and that will guarantee that we don't go and get uh we don't have duplicates that we're only seeing each triplet once all right so let's just quickly talk about time and space complexity so what is our time complexity well we have an outer loop that we're running okay so that's n and then we have our inner loop which is also a linear operation okay so our time complexity here is going to be o of n squared okay we do have the sorting but because we have we're gonna then run an outer loop and then we have to run an inner loop we're running two sum again this is gonna be at o of n squared and our space complexity here is going to be o of n okay we're going to have to create relative amount of space relative to the size of the input but it'll never be bigger than the size of the input okay so let's go ahead and jump into the code all right so first what do we want to do first we want to sort the input array so we can just do a nums.sort okay so that will sort it and then we want to go ahead and have an uh outer result array and we'll set it to an empty array now what we're going to do is we're going to iterate over our nums so we're gonna do four let i equals zero i is less than nums dot length you can do a micro optimization and do i've nums dot length minus two but either way works we can do an i plus here and now what we want to do is we just want to make sure that if we're at the i-th i-th i-th element the previous element was not the same if it was the same then we just want to continue and this is just so we can avoid duplicates so if nums at i equals nums at i minus 1 we just want to continue okay now what do we want to do next now we have to get the target right we have to create the target variable and that's going to be whatever is at our num nums i index we want to flip the sign so we can say let target equal nums of i times minus 1. that'll just flip the sign on whatever that value is okay now we're going to use a helper function method here so we can just say let sub result is going to equal two sum and we are going to have a start a target and our nums array so now our start is just going to be i plus 1 okay because we're going to use two pointers here so we want to make sure that our j is starting at i plus one and the k at the element will always be at the end it'll be the last element okay so we'll just have target and nums all right now once we get our sub result we just want to push that into our result so we'll just do a result.push and we so we'll just do a result.push and we so we'll just do a result.push and we want to use the spread operator here and uh use that for our sub result and you'll see why when we create the helper function because we're going to have a nested array of all the results from the two sum helper function when we push that into our final result we want to make sure we spread it all out so then we don't have a bunch of nested arrays okay and then we're just going to return our result so now let's go ahead and uh create our helper function okay and this is going to take in a start um we can actually just call this j a target and our nums array okay and now we can go ahead and create our k let k equal nums dot length minus one and then we'll create a sub result array okay so now what do we want to do want to follow that same pattern that we did for before two sum and here what we're gonna do is say while j is less than k okay what do we want to check do we have a target so let's first get the values out and set them into a variable so we can say let left val equal nums at j and let right val equal nums at i or i'm sorry num's at k okay so now we have our left value and our right value and we have our target okay so now we have three cases here we want to say if uh left val plus right val is greater than target okay so if we are dealing with an addition and it's greater than the target then what do we want to decrement our k-th element we want to decrement from k-th element we want to decrement from k-th element we want to decrement from the right so we just want to say k minus okay else if left val plus right val is less than target what do we want to increment rj okay now else if they're equal what do we wanna do well we wanna push into our result and then we wanna just make sure that there's no duplicates okay so what we can do here is we can just say result dot push and then here we can just go ahead and flip our target so we can say target times -1 so we can say target times -1 so we can say target times -1 okay because we don't want that negated value as our target in our result we want it the original value and then we can just go ahead and put in our left vowel and our right vowel okay now what we want to do is make sure that we move out of any repeating numbers in the i-th out of any repeating numbers in the i-th out of any repeating numbers in the i-th or the k-th index so we can say while k is less than or log j is less than k and nums at j equals nums at k what do we want to do okay if nums at j or i'm sorry if nums at j equals nums at j plus one okay well all we want to do is just increment j and similarly we want to do while j is less than k and nums at k equals nums at k minus 1 we want to decrement k and then we want to again increment j and decrement k so if we have any uh duplicates it'll go out of range and if it you know if they're bunched together so this will take care of that and then all we want to do is return our result now because we're pushing into results and it's going to be a 2d array with the result that's why we're going to use the spread operator here so that way we spread it out and push it into our final result okay so let's go ahead and run this okay and we're good we made great uh time and space complexity 90 percentile pretty good okay so that is threesome it is a very tricky question because of these edge cases with the duplicates uh but if you're familiar with twosome then this is a great way to kind of just have a mental framework if you ever see threesome it's just really a combination of using two sum as a helper function uh to iterate over each element of the nums array and then just use two sum for that sub problem and we can solve this okay so hope you enjoyed it and i will see you guys on the next one
3Sum
3sum
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets. **Example 1:** **Input:** nums = \[-1,0,1,2,-1,-4\] **Output:** \[\[-1,-1,2\],\[-1,0,1\]\] **Explanation:** nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0. nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0. nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0. The distinct triplets are \[-1,0,1\] and \[-1,-1,2\]. Notice that the order of the output and the order of the triplets does not matter. **Example 2:** **Input:** nums = \[0,1,1\] **Output:** \[\] **Explanation:** The only possible triplet does not sum up to 0. **Example 3:** **Input:** nums = \[0,0,0\] **Output:** \[\[0,0,0\]\] **Explanation:** The only possible triplet sums up to 0. **Constraints:** * `3 <= nums.length <= 3000` * `-105 <= nums[i] <= 105`
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Two Pointers,Sorting
Medium
1,16,18,259
929
hello everyone welcome to quartus camp we are 27th day of september leco challenge and the problem we are going to cover in this video is unique email addresses so the input given here is a list of strings where a list of email addresses given and we have to return the number of email address where the that the email address actually receive mails and there are certain rules and conditions to identify them so let's understand this rules with an example so before getting into the actual example given in the problem statement let's understand the rules given in the problem so the first rule is dot rule that is the email address is first being divided into two parts the first one is local address and then the second part is domain address so the domain address does not have any rules they simply gonna stay the same as such but the rules are for the local address so first rule is if there is a dot and the dot should be ignored and this email address can be represented as dot rule at there is not a dot will at there is not a dot will at there is not a dot will be included in the receiving address and goes to the second one is the plus rule so the plus rule is nothing but whatever is left after plus will be ignored that is only applied to the local address not to the domain address so now considering removing the plus the receiving address will be plus at because after plus whatever is there in the local address will be ignored so these are the simple rules and the both the rules can be applied to a single email address and we have to return how many addresses will be receiving the email at the end so getting back to our actual example given in the problem statement there are three email addresses the first one is having dot as well as plus so as per the rule we have to ignore whatever is after the plus and we have to ignore the dot now the email address will actually become test email at now moving to our second one have two dots and one plus so after plus we have to ignore everything in the local address so bob.kathy will be local address so bob.kathy will be local address so bob.kathy will be completely ignored and two dots will be ignored in the front thing so again this email id will be test email at be test email at be test email at so going to our next one which is having only one plus so we simply ignore it so now this email address is test email at leadcode. because the rules are not applicable to the domain address they are only applicable to the local address so this is going to be different by lead code at lea. so now there are two unique addresses that is going to receive email at the end so the output is going to be true so hope you're understanding this concept now how we're going to approach this so it is going to be very simple straightforward solution where we are going to use string manipulation and get this done so first step we are going to do is we are going to split the given email address into local address and domain address by splitting it with the add sign because we have to apply the rules only to the first part of the email not to the second part so once we separate it we keep the second part for finally appending it to the final string and the first part will be going to apply with the plus and dot rule and filter finally to add it with the domain address so first we are going to split it with the plus and if there is a plus we are going to ignore the second half and then we will get the rest of the address only with dot so once there is the rest of the address we check for dots and replace them with the empty space or no space so that we will get the rest of the domain at local address without dots and we finally have a string without dots and without after removing plus and we will append that with the second part which is the domain name and we are going to return the result in the form of uh like we are going to save them in a set and the set will be having the unique values so finally the size of the set will be our output so this is going to take big o of n time and n space complexity as we are going to store them in an array and execute the number of email address given in the input stream array so let's go to the code as i said we are going to first have a set which is going to store the final filtered email addresses so now we are going to separate the email addresses into two parts which is local and domain so the string paths will be separated or split using the at sign so once this is split parts of 0 will be having the domain address sorry local address and parts of one will be having the domain address so now again with the local address we are going to split it based on the plus sign so now this will actually have local of xero will have text before plus and local of one will have text after plus so we don't need local of one actually because we don't need anything we have to ignore the text which is present after uh plus so we now have to pick only local of zero and put the test the next rule which is the dot rule so we are directly gonna add to our result local of zero in that we are going to replace the dots with empty space and once that is added we are going to put the rest of the part by adding the add signature sorry add sign and the second part of the email address that is the domain name so yes this will complete the email address which is valid and added towards it now our set will be having only the unique email addresses that will be returned as part of the result so we are finally going to return its size but then we forgot to do one thing which is iterating the email addresses so yes let's run and try yes so let's submit and try yes a solution is accepted and runs in 16 milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Unique Email Addresses
groups-of-special-equivalent-strings
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"alice@leetcode.com "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"alice.z@leetcode.com "` and `"alicez@leetcode.com "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"m.y+name@email.com "` will be forwarded to `"my@email.com "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "test.email+alex@leetcode.com ", "test.e.mail+bob.cathy@leetcode.com ", "testemail+david@lee.tcode.com "\] **Output:** 2 **Explanation:** "testemail@leetcode.com " and "testemail@lee.tcode.com " actually receive mails. **Example 2:** **Input:** emails = \[ "a@leetcode.com ", "b@leetcode.com ", "c@leetcode.com "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Array,Hash Table,String
Medium
null
1,011
hello and welcome back to the cracking fang youtube channel today we're going to be solving leak code problem 1011 capacity to ship packages within d days at the moment this question is really popular with facebook amazon and google so definitely want to know if you have an upcoming on-site interview with any an upcoming on-site interview with any an upcoming on-site interview with any of these companies let's read the problem statement a conveyor belt has packages that must be shipped from one port to another within day's days the ith package on the conveyor belt has a weight of weights of eye each day we load the ship with packages on the conveyor belt in the order given by weights we may not load more weight than the maximum weight capacity of the ship return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days cool so that's the problem statement but let's go through an example for example if we were given this array here weights 1 2 3 4 5 6 7 8 9 10 and we were given five days to ship these packages then our answer here would be 15 and let's kind of see how they derived that well you know if we chose 15 we could ship these first packages on the day so this would be what this would be weights of 14 on that first day this would be a way of 13 then 8 9 and 10. but that's not really intuitive you know how the hell did they come up with 15 right like it doesn't make any sense at all so let's break this down and figure out a practical way to solve this problem that makes sense because right now it seems like they just picked 15 out of a hat so let's do that all right we've seen the example and we realized hey this doesn't make much sense how did they get 15 well let's do this in an intuitive way what is the minimum amount of weight that we could ship on a day well if we think about this the minimum weight we could choose has to be whatever the maximum weight of our packages here is why is that which in this case is going to be 10 right why is that well if we chose anything less than the maximum weight of our array here then we would never be able to ship that weight for example if we chose 9 as our maximum weight we could ship every single package here but we would never be able to ship this 10. therefore you know this would take an infinity amount of time and it would never work so we know that the minimum weight we can choose from has to be the maximum of our array otherwise we can't ship it cool so that's the minimum weight we can choose but what's the maximum weight we can choose well if we think about it the maximum weight is going to be whatever the sum of our weights is right because in that case we could ship everything on a single day so you know if we sum up this array we're going to get that the weight here is actually 55. so you know we could choose 56 57 100 000 10 million 100 billion for our weight it wouldn't matter we could still ship everything here but remember that we're trying to result we're trying to find the least weight capacity that would allow us to ship uh these packages right if we chose 100 billion we could ship this in one day still but all we need is 55 so we're wasting weight capacity so there's no reason to go any higher than whatever the sum of our weights here is so that gives us the bounds of our you know weight search right it's somewhere between 10 and 55. so if we kind of draw this out you know we have 10 11 12 and then you know some values here and then we have like 54 and 55 right and it's going to be all the values between you know 10 and 55 and here i'm just kind of i don't want to draw everything out so what we could do is you know we could start at 10 and we could say okay you know how many days would it take to ship um these packages if we only use 10 and remember we have to ship them in the order they come so on the first day we could ship one two three so that would be six so we could ship these packages and that would take one day then on the next day uh we have to ship this package five but we can't ship five and six because that would be eleven so we have to ship five on the next day so that would take two days on the next day we'd have to ship the six so we'd ship that it would take an extra day then we ship the seven that takes an extra day so now we're at four eight would take its own day so now we're at five and then nine would take its own day and then ten would take one day so we'd be at seven so it would take seven total days if we chose ten and remember we have five so this weight doesn't work okay well what if we tried eleven um you know it's the same thing i think it would take like six days in this case but the point is we can't ship it with this obviously we know that the answer here is 15 so i'm going to kind of just do a little bit of skipping here uh you know we would try 12 and we can't do it so as you can see we're going from left to right here and we're basically just trying all of the weights so that's you know the first way to solve this is going to be you know the linear solution where basically we're going to start at the minimum weight we can do which is going to be the maximum of the array and we're going to walk towards whatever the sum of the arrays which is like the maximum possible weight we could choose for that day and we're going to find the first value that trips this um you know that we can ship with and we know that's going to be our answer so you know doing this would take o of n time in the worst case times whatever the function cost is to figure out whether or not we can ship it so you know we'll kind of just assume that function takes o of n time to like sum up whether or not we can do it right because we have to check all the days so we'll just be going from left to right of the actual weights here so this would be an o of n squared solution okay but like i said this is the first solution and it's the linear solution how can we do better than that well one thing to realize is that we can't get away from this function here that does the summing to figure out you know whether or not we can ship something on a day this part we can't do better on but do we actually have to scan from left to right to find this first point and you know the more keen of you will have realized okay well we actually can do this in log time because if you notice we're going from 10 to 55 and this is increasing by one every time which means that this array is actually sorted so we're looking for the first value that trips you know um that would work for us and we have a sorted array so this should be screaming to you hey we need this binary search here so we can actually take our run time complexity from o of you know n squared down to you know n log n times o of n so we can reduce oh sorry this isn't n log n this would just be log n so our final solution is going to be n log n so that's gonna be the best thing we can do if we use a binary search here and this is really what your interviewer is looking for how you're gonna set up this binary search and also you know how you do this the check whether or not you can ship it so that's the two parts we need right we need the binary search part uh and then we also need the some function to tell us whether or not we can ship our weights here so now that we know that's what we're looking for let's go to the editor and actually write the code and it's quite simple all right i'll see you there welcome back now we're in the editor let's write the code so we know that we're going to do a binary search so to do a binary search you need a left and a right endpoint for your search so let's define those remember that the left which is going to represent the minimum weight that we can ship on a day is going to be the maximum of the weights that we're given right so we're going to say max of weights and the right endpoint is going to be the sum of the weights we're given and if you don't understand how we got those go back to the explanation portion where i go over why we choose the max as the minimum weight and the sum as the right endpoint cool so let's set up our binary search and remember that we're looking for the least value um so we won't actually be returning within our binary search so we need to be careful to set up the binary search correctly so in these cases where you're not actually returning a value from within the binary search usually you use while left is less than right if we're looking for something inside of the array we would use less left less than or equal to right but in this case since we're moving our pointer down and we're actually going to move the point we're going to return the pointer value we don't want to use the less than or equal to so with a standard binary search we're going to do mid equals to left oops left plus right divide by two and there is a way to avoid overflow in java i'm using python here so um you know look it up how to avoid the overflow in java if you're using that or c plus anyway um so what are the two things that can happen here in our search right either we can ship the weight or we can't so we're going to define a function to do that in a second but let's kind of just go through it conceptually so we're going to say if self dot can ship so if we can ship the weight with whatever our mid because that's going to represent the weight we're using uh we're going to pass weights and we're going to ship the days that we're allowed if we can ship it with this weight we need to move our endpoint right so we're going to say right equals mid and why do we use mid instead of mid minus one well let's think about this if we did mid minus one and it turns out that this weight mid was actually the answer then if we did mid minus one then we would never return that value because we would accidentally go over it so we can never do mid minus one when we know that we can ship it because that could actually be that left most point and therefore our answer so if we can ship with a weight we have to use right equals mid conversely if we can't ship the weight then we know for sure that value and anything to the left of it will never work right if a certain weight is not shippable then any weight smaller than it will never be shippable we can only look for larger weights so when it's not shippable then we can do mid plus one so in the end all we have to do is actually return that right because this is gonna be the solution and this is usually the case when you're looking for kind of the left most or the right most value with the binary search if you're just returning a value you can typically do mid plus one and then mid minus one for you know whatever your left and right is and you would use the less than or equal to up here but in this case we're trying to move our we're trying to find the left most or the smallest weight that we can use uh we need to set it up this way and if this is a little bit unclear we're going to go back to the drawing board in the end and i'll show you why this is the case so you can see it visually because it is a little bit hard to conceptualize the binary search this way um so it is a little bit easier to just see it in actual you know a diagram anyway this is how the function to ship within days is going to need to look like but we need to define our can ship so let's do that so we're going to say def can ship and we're going to say self and this is going to be the candidate weight it's going to take the weights and the days that we're allowed to use so what we need to do is we need to track the current weight capacity of our ship and we need to track the days that we've taken so far so the current weight is going to equal zero because we haven't loaded anything onto our ship and we're going to say that days taken is going to equal to one uh and the reason that we're going to use one i'll explain at the end but basically what we want to do is that we know that if we have the case where we're actually using the maximum amount of weight then it's always gonna take one if we did zero um within our code here which you'll see in a second we would never actually increment the days and we would return zero which isn't correct because we have to ship it in at least one day right we can't unless you can't ship in zero days so let's go through it so we're gonna say for the weight in weights what's gonna happen we're gonna say that the current weight of our ship it we're gonna add the weight to it now if the current weight of our ship exceeds the weight that we're allowed to use which is the candidate weight we know that our ship is overloaded and we weren't actually allowed to take that last weight so what we need to do is we need to say okay well we can send the ship off without this last weight here so we're going to send it off and we're going to say that day is taken we're going to add one to it and then we need to reset our weight back to whatever the weight we just took was that caused us to trip so for example if the weight of our ship was 9 and the next weight was say 4 and we were only allowed to load 10 on a given day obviously if we took the 4 then we'd be at a weight of 13 we can't do that so we have to ship that 9 weight and then the 4 is going to remain for the next day so we do this for all the weights and we're going to increment you know our days taken as we go along and this is the reason that actually um you know we need to start with days taken as one because if the candidate is actually the maximum weight this curve weight will actually never be greater than um the candidate because they'll just be equal in the end and we would never have incremented days taken and therefore we would return zero so that's why we need to return days to uh we need to start with days taken as one and in the end all we need to do is return days taken is less than or equal to days right because that's what we're looking for we need to be able to ship the day uh the weight within days so either we ship it within you know five days here or less than that you know for this particular example so that's how you define the canship function let's submit this and double check that it works and once this runs cool we can see that it does and it's quite quick because it's the binary search solution so before we go back to the drawing board to actually talk about kind of how the binary search is set up in this case let us talk about the time and space complexity so you know what's going on here well we know that we have a binary search so any binary search is always going to be log of n right now that's going to be the binary search part but within each binary search we need to call this can ship function so let's find out what the time complexity of this can ship function is well in this case what we do in the can ship is basically we go from left to right to sum up you know the current weight that we have and then compare it to our candidate so really what we're doing is we're just doing a sum over the weights here and in the worst case we would have the maximum uh weight which is going to be remember the total sum of the weight so we would basically just sum our entire array so in the worst case this is going to be an o of n operation so our time complexity in the end is going to be big o of n log n space complexity wise at no point do we actually define any extra space for our solution here we have this left and right pointer but these are just pointers these are constant space variables so we don't actually define any new variables here same with these are just you know pointer variables like what's the current weight what's the days taken so we don't you know define any arrays or anything like that so the space complexity is actually going to be constant space right so that's the time and space complexity cool at this point let's go back to the drawing board and walk through a simple example so you can see why the binary search is set up in the way that it is because it's a little bit hard to grasp if you've not really seen this before and you don't understand how binary searches uh that follow this pattern work so i'll see you back at the editor in a second let's go over why the binary search actually is set up in the way that it is if you already understand it and it's pretty intuitive to you can skip this part go watch another video if you want um you don't need it if you were a little bit unclear this is the portion of the video for you so let's go into it so we remember you know what we do is we set up our left to be you know this point here which is the maximum of our array here so this is gonna be four and remember that the right point is going to be the actual sum of this array so you know if we sum this up we actually get 16 and i've drawn this out so basically we have all the values between 4 and 16 that could be the weight that we use so remember you know we're going to do while left is less than right so you know we pick a midpoint what's the midpoint here so it's going to be 4 plus 16 so 4 plus 16 equals 20 divided by 2 uh is going to be 10 right so the midpoint is going to be 10 here so we're going to choose 10 as our weight cool so you know can we ship with 10 okay let's check it out so we could ship the three plus the two so that's gonna be a way of five plus the two again so that's going to be seven and then we get to the four so we can't ship that because it would go up to 11 here so this weights would take one day then the next one would take okay well we could ship the four plus one so that's gonna be five plus four so that's going to be nine so we can actually ship everything else on the second day so it would take two days so 10 works right so 10 works which means that um you know 10 could be a potential solution we don't need to check anything else here because these are all values greater than 10 and remember we're looking for the least weight capacity so we know if 10 works we don't care about anything to the right of it because we know that at this point it's fine uh 10 could be our potential solution we don't need to try anything larger than 10 because we're looking again for the least weight capacity cool so now our right if we remember back from the code is going to equal to whatever the midpoint value was so now our right is going to be 10. so let's keep going you know is 4 still less than 10 yes it is so that means we have to calculate a new pinpoint so we're going to say 4 plus 10 divide by 2 so this is going to be what seven right so that so now we're at the seven so let's try seven okay well you know if we have our array here um let's see we have three so on the first day we could ship the three we could ship the two so that would be six and then trying or started five and then this one uh that would be seven so this would be you know we could still ship it on one day and then so that would take one day in this case you know it would be four plus one five but we can't ship this last four because that would be nine so that means that would take two and then this last four would take three days so seven works because it's um you know at least you know within d days so we're allowed you know less than or equal to here so 7 works so that means that anything to the right of 7 is no longer valid as well so we found a new best answer so now our right is going to become 7. so what we want to do now is okay we need to calculate a new midpoint so we're going to say 4 plus 7 divide by 2 so this is 11 remember we're using integer division so this would really be uh so this would be 11 by 2 is what 5.5 and then since it's integer it what 5.5 and then since it's integer it what 5.5 and then since it's integer it goes down to 5. so we're going to choose 5 here so uh let us and then i'll redraw this thing so we have 3 2 four one four okay so can we ship it with five okay well we could ship this in one day because that's five this is gonna be six here so we can't do it so we have to ship the two separately so we'd ship it takes its own day we could ship this because it's five so that would take one another day and then this would take its own day so this would take four days so obviously four is greater than our allowed allotment of three so we can't actually ship it there so that wouldn't work so that means that five is not a viable solution so that means our left pointer has to move up right so we set is mid plus one so it's going to be six here so now our left is six cool so now let's go through the process again and let's find a new pin point so we're gonna say six plus seven divide by two so this is 13 divided by two so that's going to be what six right uh because it's um you know 6.5 6.5 6.5 and then obviously it's integer division uh so we're truncating down to six cool so let's try now six so we're going to try okay can we ship this packages yes this is going to be five so this is going to take one day obviously using the two wouldn't work because that would take us to seven so then we reset it so then on the second day we could ship this because this is six and then on the last day we could ship these two because this is going to be uh five so this would take three days cool so we know that six works because we are within our three days right we take the three days that's fine so now we are good here so now our right pointer becomes six because we set it equal to mid so at this point we have left equals six and right equals six and remember that our binary search is going to be while left uh left is less than right so in this case they're actually equal so this binary search would break and remember the last thing we need to do is actually just return the right which is going to be 6. so that's how they derived it hopefully that's a little bit clearer explanation of how you know the binary search works in this case using you know left minus right and then moving you know right equals mid uh if it's good and then left equals i guess mid plus one uh if it doesn't work if that was still unclear go back over this explanation and hopefully you know re-watch it as many times as you need to re-watch it as many times as you need to re-watch it as many times as you need to kind of visualize it maybe even work through the example yourself and it should start to click so that's how you do leak code problem 1011 or i guess 1011 capacity to ship packages within d days hopefully you've enjoyed this video this is actually a very common problem that you're going to see on leak code not only because it uses binary search which comes up in pretty much any company's onsite interviews these days but i think the problems that are very similar to this are going to be cutting ribbons and cocoa eating bananas so if you want to take the knowledge that you learned from this problem uh go try those out if you don't understand it i should have a video coming out real soon about those two videos about those two problems so if you don't understand how to do those problems you can watch my videos and then hopefully you'll know how to do them so thank you for watching if you enjoyed this video please like comment and subscribe and make sure to watch all of my other videos if you're prepping for an on-site interview have a good one
Capacity To Ship Packages Within D Days
flip-binary-tree-to-match-preorder-traversal
A conveyor belt has packages that must be shipped from one port to another within `days` days. The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within `days` days. **Example 1:** **Input:** weights = \[1,2,3,4,5,6,7,8,9,10\], days = 5 **Output:** 15 **Explanation:** A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. **Example 2:** **Input:** weights = \[3,2,2,4,1,4\], days = 3 **Output:** 6 **Explanation:** A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 **Example 3:** **Input:** weights = \[1,2,3,1,1\], days = 4 **Output:** 3 **Explanation:** 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 **Constraints:** * `1 <= days <= weights.length <= 5 * 104` * `1 <= weights[i] <= 500`
null
Tree,Depth-First Search,Binary Tree
Medium
null
338
hey how's it goin guys so in this video we'll discuss about this problem counting bits given a non-negative counting bits given a non-negative counting bits given a non-negative integer number now for every numbers I in the range 0 to num calculate the number of buns in their binary representation and it turned imagine Eddie so let us consider some examples first so for this example 5 the output is something like 0 1 2 so I'd represent numbers from 0 to 5 over here in their binary format so you get can be clearly seen that number of ones in 0 is 0 so we have 0 over here number of ones in 1 is 1 so we have 1 over here similarly number of ones in 2 is also 1 so we have 1 over here for 3 the number of buns are 2 so we have 2 over here and so on now let us see how we can solve this problem so this is the number and this is a general number end ok and for this general number end this is the least significant one what is the meaning of least significant one it means that this is the rightmost one so in case there exist bits on the tightening side of it though those all will be 0 so this is the general number and given to us now if you see this is the general number n minus 1 now if you see carefully what happens is on the left of the least significant one that is this part remains same for n minus 1 the least significant one will be converted to 0 and in case there exist bits on the dynein side of the least significant one which will be all zeros for n will be converted to all ones now you might think that why this holds so this is a very general thing this will hold for any two conjugative numbers so you can take any two consecutive numbers like 15 16 or 100 hundred 1 or any two numbers it this thing will hold so I can show you this thing with the help of an example so this is the number 52 and this is the number 51 so if you see carefully this is the least significant one for 52 that is the rightmost one so what I just said is the left-hand part of the least is the left-hand part of the least is the left-hand part of the least significant one will remain same that is this 1 0 will remain same for 51 as per the least significant one will be converted to 0 and only died inside all zeros will be converted to all much now if I take the bit by the end of these two numbers n and n minus 1 so what will happen is see on the left hand side of the least significant one this part is same for n and n minus 1 so this part will remain same for this and end and minus 1 as well this is 1 over here and a 0 over here so this will be 0 and on the items right there will be all zeros over here there will be all ones over here so if this will be all zeros correct so this is an end and minus 1 now if you see carefully let us compare these two numbers this number n and this number and end and minus 1 so if you see carefully these two numbers will only differ in this bit this is 1 over here and this is 0 over here everything else will be seen so actually this is a common technique to remove the rightmost bit or the least significant one so using this what you just did is for from the end you have removed the least significant one so this is the common technique that we use so what I can say is this number and this number differ only at one place that is this place correct so we have removed the least significant one so what can I say that the number of ones for distal will be equal to the number of ones for this number plus one let me repeat it again what I just said is this number and this number these two numbers only differ at one bit that is the least significant one which is removed from one we have moved to 0 so what I just said is the number of ones for this number will be equal to the number of ones in this number plus one so this is what we are going to do in the problem so for any number n we will try to find it for this number and we'll just add one to the result and then we will find the number of ones for this n so I written the algorithm over here you can pause the video you can read it out and I will write the code now and then things will be more clear so first what we'll do is we'll create a result ignoring off size num plus 1y num plus 1 because we want number of ones in all numbers from zero to none now so result of zero will be actually zero why is that what I'm saying is the number of ones in zero is zero this is already discussed the number of ones in zeros is actually zero and actually we don't have even have to write this thing why because it will be niche light to zero only so I can just remove this thing and I will today from I equals 1 to I less then num plus 1 I plus 2 is now what I did do is result of I will be same as result of I and I minus 1 plus 1 so this is what we discussed over here there are number of ones for this number will be same as number of ones for this number plus one so this is what we are doing over here and after this is done you can simply return the result so I guess that's it let me submit the solution so it got accepted so I guess that's it from the video in case you have learned anything from the video you can hit that like button and in order to support my book you may consider subscribing to my channel thank you
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191
1,456
hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximum number of vowels in a substring of a given length we're given a string s and an integer k represents the size of our substring but I prefer to call it a window because substring problems are commonly sliding window problems so that's the first thing that I usually look for and in this case that's exactly what's going to happen but don't worry if you're not familiar with the sliding window algorithm I will really try to explain the intuition behind it because it's not a super crazy algorithm but if you're already familiar with it this problem is pretty much a textbook example of the fixed sliding window algorithm sometimes you also have variable sliding windows but in this case we are just given the integer K and of course K is fixed so we have fixed sliding Windows okay but what is the problem even asking of us so basically given a string we can take Windows of size K in this case k is three so the first three characters this is a window the next three characters and these three characters and just keep going exactly like that so for every single window well how many windows are there roughly there are going to be n Windows what's the size of each window well of course it's going to be K so if we had to go through every single substring and just count the characters character by character this is what the time complexity would be and that's pretty much what we're doing in this problem we're not actually counting each character we are checking each character to see if it is a English vowel so we want to count the number of vowels in each of these substrings and what we want to return is the maximum so whichever one of these substrings has the maximum number of vowels that's the number that we want to return the maximum number of vowels in any of those substrings and it's as simple as Big O of n times K we could do it with a nested for Loop just to walk through it we'd go character the a is not a vowel this is not a vowel and this is not a vowel so all three characters starting from here next we'd start at the second character here is this a vowel nope is this a vowel yes so here we had one vowel next we're going to do something similar we're gonna go to the next character it's not a vowel next character it's a vowel so here we have two vowels we can just continue going like this but are you kind of noticing we're doing something a little bit dumb here when we're over here we know that this window has a single vowel in it and we just went character by character we went through all three characters so if the next question is what about this substring or window how many vowels are in this substring well most of the problem is already solved we already know how many vowels are in this portion this green portion we already did that well we also did this but we don't need this right so we kind of want to remove this we're chopping this off and adding this next character just one character we remove this and add one character so you can see going from one window to the next window is actually an O of one time operation and how many windows we have is n so actually this algorithm is Big O of n it's not super crazy is it the idea is that we can keep track of each window using exactly two pointers I like to call them the left and right pointer of course the left pointer will tell us the beginning of our window and the right pointer will tell us the ending of our window now we're not going to quite start out like this we're actually going to start out like this where both pointers are going to be at the first character left and right but then we're going to take this right pointer and shift it to the next character so right pointers here now then we shift it again now we finally have a window of size K we could still consider these smaller Windows that's not going to change our result so I won't pay any attention to that but now we're finally at our first window it doesn't have any vowels so what are we gonna do well chop off this guy so shift our left pointer to the right by one over here and also shift our right pointer this guy to the right over here and now this is our window when we remove this character we have to check is it a vowel or not for our window we are going to keep track of a count variable we want to count how many vowels are in this window at any given point originally it was zero for the first window we had zero when we shifted to the right we removed a non-vowel to the right we removed a non-vowel to the right we removed a non-vowel character and we added a vowel character we added an i is a vowel so now we should increment our count so this window has a count of one and of course at the end we want to return what the max count was among any of the windows I know I went pretty deep for a relatively simple problem but I think taking the time to really understand exactly what's going on helps for a lot of the more difficult problems so now let's code this up so the first thing I'm going to do is just create a vowel set so the five vowel characters are lowercase a e i o and you since it's just five characters we probably don't need to put it in a hash set this is a hash set in Python that's the Syntax for it we could have put it in an array it doesn't really matter because searching it is going to be a constant operation but you know I digress the space complexity of this function is constant because there's just five characters we don't really need extra space here now we are gonna start iterating we're gonna go through the entire string the way I like to do it is have an R pointer and you'll just have it iterate like this with a for Loop some people use while Loops it's up to you but we just take the length of the string have a right pointer that's going to go character by character through the input string we also though have a left pointer I'm going to declare it up here it's going to initially be zero and we're also going to have a couple more variables the count and the result so those are also initially going to be zero now as we go character by character we know we want to add one to the count if our character at index R is a vowel character so if this is in our vowel set and I'm actually just going to change it to vowel just to make it a little bit shorter but if it's not in the vowel set of course we want to do nothing so I would just put 0 here which basically adds zero to count basically not doing anything and of course we want to update our result we want to set it to the max of the result and the count and you might think that's pretty much it and then we can go ahead and just return the result but not quite because remember we forgot about a parameter here K our window can't be any bigger than K so before we even try to take the result let's make sure we have a valid window what happens if our window is invalid well the lengths would be bigger than K how do we get the length we can take the right index minus left plus one that gives us the length of the window if you don't believe me try it out on an example prove it to yourself so this is the length if it's bigger than k then the window is simply too large we have to make it smaller just by A Single Character so we want to shift r our left pointer by one you might think we want to shift our right pointer but we're already doing that with the for Loop that's kind of why I like to code it up this way but again you can kind of feel free to switch it up how you like don't forget we don't just need to update the left index we also have to update the count because as we remove characters from our window we possibly want to decrement the count by one so if the character at index left the reason I'm putting this line before the incrementioned by the way by before incrementing is because of course we want to use the original left index before we shift it we want to know was this character a vowel so is this in vowel if it's not just add zero or just decrement zero which doesn't do anything of course so this is the sliding window approach for this problem let's run it to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has a ton of free resources code.io it has a ton of free resources code.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon
Maximum Number of Vowels in a Substring of Given Length
find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance
Given a string `s` and an integer `k`, return _the maximum number of vowel letters in any substring of_ `s` _with length_ `k`. **Vowel letters** in English are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`. **Example 1:** **Input:** s = "abciiidef ", k = 3 **Output:** 3 **Explanation:** The substring "iii " contains 3 vowel letters. **Example 2:** **Input:** s = "aeiou ", k = 2 **Output:** 2 **Explanation:** Any substring of length 2 contains 2 vowels. **Example 3:** **Input:** s = "leetcode ", k = 3 **Output:** 2 **Explanation:** "lee ", "eet " and "ode " contain 2 vowels. **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters. * `1 <= k <= s.length`
Use Floyd-Warshall's algorithm to compute any-point to any-point distances. (Or can also do Dijkstra from every node due to the weights are non-negative). For each city calculate the number of reachable cities within the threshold, then search for the optimal city.
Dynamic Programming,Graph,Shortest Path
Medium
2171
2
welcome to part two of leeco the day keeps the dances away high script edition we're gonna be solving lead code questions using typescript and now as always i'll be showing you guys multiple solutions to the same problem and this one is add two numbers if this is your first time on this channel uh i do these lethal type of questions time to time i'm only on the second one uh it is my goal to get through all of these i don't know if that's possible but we'll try especially if you guys like this content by clicking like and subscribing to my channel that will help me tons but i'm going to be going through these and my goal is to make the most in-depth my goal is to make the most in-depth my goal is to make the most in-depth tutorial for these in youtube quick interjection here if this is your first time attempting a singly linked list question i do have a very comprehensive a deep dive into singly linked lists uh this is my data structures and algorithm series in javascript and typescript so please check that out if you haven't done so already so let's read this question and then i'll have you guys pause the video try it on your own and then come back to me and i will show you the multiple solutions that i have come up with add two numbers you are given two non-empty linked lists representing two non-empty linked lists representing two non-empty linked lists representing two non-negative integers non-negative integers non-negative integers the digits are stored in reverse order and each of their nodes contain a single digit add the two numbers and return the sum as a linked list you may assume the two numbers that contain any leading zero except the number zero itself so there was a lot of nuggets in there um let's look at the example first 243 564 that would somehow give us 708 and let's remember what they have said so the digits are stored in reverse order so this 243 is going to be 342 and this 564 linked list is going to be 465. so what is 342 plus 465 that ends up becoming 807 and if you reverse 807 that will give you 708. so that should give you the linked list of seven zero eight uh there's a couple other things to keep in mind is we are given two non-empty in mind is we are given two non-empty in mind is we are given two non-empty linked lists meaning this l1 and rl2 will never be null so i don't know why they typed it like here also they're stored in reverse order as we said uh these are representing two non-negative integers representing two non-negative integers representing two non-negative integers they will never be negative and the nodes all contain a single digit meaning we're never gonna have something like 12 here or like negative 5 here or negative 24 anything like that they're all single digits another thing that helps us out is you may assume that two numbers do not contain any leading zero except the number zero itself meaning we're not going to have extra zeros here to just pad the number because that's essentially the same thing as 342 right so that is this first question now please pause the video try this on your own and come back to this to show to look at my solutions all right so the first way i'm gonna solve this is we are gonna make a function first that gets a list node like this and gets the list node like this and produces the correct number out of them so this function is gonna take this link uh list node linked list or whatever and give us 342 meaning it's gonna give us the digits in reverse and it's gonna give us from here for 65. so our first objective is to make a function that gives us the correct number in the number type of for uh the two linked lists that we have and then we're going to add these together we're gonna add these together and then spit out the digits back in the reverse order as a linked list so that's our objective let us go to our editor now i have a code sandbox open here let me just zoom in here a little bit copy this i've already copied the list node class here so that the typescript won't complain to us whenever we define it like this and a couple important things to keep in mind they told us that we are given two non-empty linked lists meaning the way non-empty linked lists meaning the way non-empty linked lists meaning the way that they typed it is not actually correct because they're giving us they're saying that l1 is either list node or null and l2 is either this node or no that's not correct they should actually only be a list node they can never be known and because of that because we're always gonna have something for l1 and l2 that means we could always add something and our output should never be no either so let's get that out of here too now we have the correct type and as i have said where first our first goal is to make a function that takes in a link a linked list and spits out the number in the correct order so i'm just gonna define it as a function out here so what should we call this we will say uh get number from list and this will take a list as an argument which is a list node and it will spit back out to us a number like so and this function as i said we're going to be end up calling it for both l1 and l2 so what can we do to get this singly linked list as a number all right so in the beginning let's not worry about the fact that these are in the reverse order let's just worry about putting these into making this into a 243 now i got a question for you guys is it easier to make this 243 as a number or as a string um to make it a number how do you get the numbers 2 and number 4 and make them 24. it's easier to get the string to string 4 and then concatenate them together to get the string 24 right so that's what we're gonna do here so let us do this let a number in reverse order i'm just going to be explicit that this is explici uh in reverse order so that we remember to put it in the proper order afterwards and this is going to be a string type and we will instantiate it as an empty string because we're already instantiating as mp string here we don't need this typing so we'll just let typescript infer it and then we are gonna use the runner method to run through this linked list and grab each value until the runner uh is that null so let's define the runner that runner be the list it starts from the beginning of the list and we are going to do a while loop so while runner exists what do we want to do while the runner exists we want to append to this number in reverse order string the value that the runner contains in the string format so the way we are going to do that is number in reverse we if i could spell correctly reverse order we are going to add to that the um runner dot val which is a digit and we just wanna to string this to make sure that it stays as a string and then after we have added that value the current node is no longer use of use to us so we're just gonna set runner equals runner dot next he's gonna keep on going until he gets to the end and right now typescript is complaining to us because runner.next complaining to us because runner.next complaining to us because runner.next could also become null right but for this three as an example his next is no so we type the runner incorrectly or right now runner thinks his type is only a list note because that's what we pass as a list but the type of runner can be either a list note or null because at the end it's gonna become null the typescript is no longer complaining to us and now we should have had the correct number in reverse order as a string so now we want to make this into the proper order and the way that i do that is i'm feeling a little bit lazy so i'm going to be using a bunch of javascript methods that it provides us so one easy method that i know on how to reverse things is an array has a method called reverse that reverses the array so i'm just gonna convert the number in reverse order into an array i'm gonna store the result of whatever i'm gonna do as the output so this should give us the final number so first we are going to get the number in reverse order we are gonna make it into an array the easiest way to make a string into an array is just by splitting it at every single character that will give us two comma four comma three as an array and then now that it is an array we could just reverse it like so now it will give us 3 comma 4 comma 2. and after we have reversed it our usefulness of arrays are done so we're going to join it back to a string so now it becomes 342 and we just want to typecast this as number and this is going to be our output um i forgot a parenthesis here so and we want to return this output right so we could either put a return output here or just erase this and return it straight away from here like so here is our get number from list let's think about the um time complexity of this so let's take a look we are running through each of the list each of the nodes in the list that's o to the end operation we also are doing this split a reverse and join uh i don't really know the upper o to the m for reverse but i believe it's o to the n so this is something like o to the 2n operation uh one way we could speed this up is not doing this whole reverse thing and when we instead when we uh formulate the string we add it in the proper order so let me do a couple refactoring now to this remember what we were doing here we were adding each value of the node to the end of our previous string right instead of doing that why don't we just add it to the front of the string every single time the way that i am going to do that is i'm going to refactor this and i'm going to call this just number string then get this number string i know this is incorrect right now but let me just do the refactor first we don't need to do this split reverse join trap again so we are just going to call this type return the typecast of number a number string and if we fix this should work so instead of appending the value to the end of the string like this what we are going to do instead is we are going to set the number string get the value first put that in the beginning and then add the rest of the number string like so and what that would do is first we have to let me get my pen out so let me just show you guys what is going on here with this example we first start out as an empty string number string is an empty string we run through it we first start with two so the empty string now becomes two like this and then we go to the next node which is four our number string still stays as two but we are appending to that in the beginning the next value which is 4 like so that becomes what 42 and then to our 42 at the end once we are at 3 we are adding 3 to that to the beginning which gives us a string 342 so that's essentially what we are doing here this is a bit more performant than the other solution because we don't need to do the whole reverse split join stuff instead we are just this is a strictly o to the end operation and now just for fun i'm going to show you guys one more solution on how to do this that involves a little bit of math i'm not gonna stick with this solution uh for reasons i will explain later but i just wanted to show you guys notice what we're doing here we are getting our number string as a string and then typecasting as number so there is a way to do this without doing the type test where our output stays as a number and we just return that so because i'm not going to use it i'm just going to copy this code here bring it down here and what i'm going to do is i'm going to say let output let's let the output start out as zero and let's just get uh actually let's just keep this and we don't need to typecast anymore we're just gonna return the output so what we are gonna do is this let me just write out the solution first and then i'll explain what's going on first uh after i mean so i'm gonna have another variable here called index and i'm gonna start that out as an index as zero and that will pretty much be the index of each of these elements uh imagining this list node as linked list as an array so what i'm to do here we're still going to be up adding the whatever value that we get at the beginning kind of like this previous solution and of adding that to the previous number except this time is the output right and this should also be the output instead of doing this string addition we are going to do addition by actual numbers and the way that i'm going to do that is this we are going to get the runner.value we are going to get the runner.value we are going to get the runner.value which is a number times math.power math.power math.power of 10 to the index power and then we're going to add that to the output that will somehow give us the solution runner is equal to runner.next solution runner is equal to runner.next solution runner is equal to runner.next i also want to increment our index so why the heck does math.power of doing why the heck does math.power of doing why the heck does math.power of doing this work let me guys show you what's going on so at the very beginning our runner dot value is 2 right so we have 2 times 10 to the what's our index right now is 0 power plus the output i'll put started out as 0 as you guys can see here what's 10 what's anything to the zero power that's one so this gives us two times one plus zero which is two and then we go to our next node which is four so we have 4 runner.value times 10 four so we have 4 runner.value times 10 four so we have 4 runner.value times 10 to the first power plus our previous output which was 2 what's 10 to the 1 power that is just 10 times 4 is 40 and that gives us 42 and notice what is happening right we are getting the number the next number is 3 times 10 to the 2 plus our previous number which is 42. uh 3 times 10 to the 2 is 100 so 100 times 3 is 300 plus 42 is 342 and that is the number that we want so that's why this works however i'm not gonna stick with this solution uh and i'll explain that will be more clear later so let's just erase this neat solution that we have here and stick with this solution for now where we are just adding it to the beginning the string and then returning the number form of it later so we have beaten this get number from list function to def let's get to the actual problem of adding the two numbers the actual main meat of the problem and we are just gonna call this get number from list twice so we're gonna say const number one n1 is equal to get number from list of l1 and const n2 is get number from list of l2 so that will give us the two numbers and what do we want to do with the two numbers we want to add them together so sum is n1 plus n2 all right so this sum now should be for this example it should be 807 because that's the number of adding 342 and 465. so how do we get from 807 to become the linked list that is 7 uh 0 8 so how can we do this so first what we want to do is somehow iterate through each of the digits on the sum and form a linked list for each one and the way that i am going to do that is let's just pretend that we have made this iterable and there's actually a very easy way to do that just make it back to a string because strings are iterable so once we have made this to a string we're gonna iterate through each of the digits specifically eight zero and then seven and this is what we're gonna do once we get to the first digit we will create a list node that points to nothing we're gonna go to the next digit and then create a list node that points to the list node that we have graded previously like so and we're just gonna continue this process until we get seven that leads to zero that leads to eight so let's go to our editor now and try to implement that so as i've said we're gonna first make it into a string enhanced some string is equal to sum to string or to be short why don't we just get this addition here and just to string it right away that way we don't even need a sum string all right so now let's iterate through every single digit on the sum so we will do four let i is zero i is less than some dot length it's a typical for loop and let's just grab the digit that we want right away that we don't have to deal with anymore so const digit is going to be the sum at the current index and now as i've said before we have to make a list node with our first digit so our first digit here is seven and the way that i am not actually i'm sorry it should be eight because our the number that we have for this sum is 807 right and we want to return the result of all of this at the end so how about we instantiate that in the variable here so we'll say let output which is going to be a list node is not going to be null but i'm going to type it as null for now because we're going to have it started out as not now because we're always going to go with this for loop and we're going to put something here it's not going to be known any longer but for now because we want to initially be null we'll just set it as null and this is what we'll do let output be equal to a new list node we're going to create a new list node what is the first argument of list node it is the value and the second argument is the next so the value is very easy it's just going to be the digit except the digit right now is a string so if we just leave it like this typescript's gonna error out so instead we will just typecast it like so and what should our next be our first digit which was an eight should have a next of nothing but once we go to the next digit it's next should be the previous output right so why don't we just put output here like so what will happen is we've create eight that has a next two null because it starts out as null then we create zero that has a next of the previous one which was the linked list with eight then we create seven that has a next to zero and this should work so at the end we could return output now typescript is going to complain to us because we have typed the output as listnode or null uh we only did this because we want to have it started out as no but it becomes a list node at the end and we know we're always going to go through this for loop at least once so we could just a piece typescript right now by saying return output as this node so this should give us the correct answer let us copy this both functions get number from list and the attitude numbers just make sure you don't copy this class list note paste it here and if you run the code let me just zoom in here if you run the code here it should pass so this has passed now if we submit now we're gonna see something very interesting and it's gonna fail and as you can see it has failed in this ridiculous test case where one of the input is like one zillion one there is a reason why this is failing and it's because we are converting these two numbers at the end and we are trying to add the two numbers here so what is going on is look at this function here get number from list imagine passing this argument here this list here into the get number from this then it's gonna attempt to create a javascript number that is like one zillion one but there is a problem because in javascript's number type there is a maximum uh integer that the number can be and that is specifically this right here let me zoom in real quick so that you guys can see this is the maximum safe integer that the number type can be and beyond this it is no longer safe and you're going to run into errors like the air that we are seeing here and what they recommend is for larger and larger integers consider using bigent so bigint is a new type that was introduced to javascript couple years ago i believe like two or three years ago i did have a video that covers it but that is what we should be using instead to uh get around this overflow here so we will refactor our solution to use a big in instance so this should no longer be returning a number but rather it should be returning a big end all in lower case and let's see what else we have to do instead of type casting the number string as a number let us typecast it as not typecast but create an instance of a big end like so this is the javascript method it cannot accept a string and it will convert that string to a bigit so now that we have done that if you look let's go back to our editor so that we have code completion let me copy this code and come back over here erase this replace it with this if you hover over our n1 now it is a big end if you hover over on two is a big it and the sum of that was a big end i wonder if you could see that but we have converted that to a string but this all still works at this solution now should pass all of our tests so i don't think i made any changes so we could just submit this as is let us run the code first that is passes and let's submit this time and it is a success so our run time was 107 milliseconds which was 95.5 which was 95.5 which was 95.5 percent of thai script which is pretty fast i'm actually shocked by this because i didn't get this in my first attempt but regardless this is a solution now let me come up with a solution that is a different than this one so let's think about the on time complexity here what we did here this get number from list is o to the n where n is the length of the list and we are calling this twice and then we are iterating through each of the digits and making a new list node so it's o to the 2n of is technically the time complexity of this is o to the this o to the n plus m plus digits where n is the length of l1 m is the length of l2 and d is the length of the digits which i believe should be the addition of these so it's either the uh the greater of these two or the greater of these two plus one i believe that's how the amount works let's see 99 plus 99 yeah nine and then if you do 99 plus 99 that gives you like 100 something so three digits so it's either the max of these or the max of these plus one so that is our time complexity here let's see if we could reduce the time complexity by solving this solution in a different fashion so let me just reset our board here there we go and i'm gonna copy this back to my editor here let's erase these two functions that we have created and paste it here while keeping our list node still here so that typescript doesn't complain to us the fact that we are using it all right so how we are going to solve this one is a little bit tricky but i think you guys can follow along and what we are going to do is we are going to be creating our output or singly linked list as we iterate to each of the digits for both lists so we're gonna start with a runner that points to this two a runner that point another runner that points to this five add them together and create a new list node that is seven here and then we're gonna run to the next one add these two and put it here but there's a little problem right four plus six is ten but we want to only add zero here and do something with that one later so what we can do is i don't know if you guys remember from your basic uh arithmetic classes in like elementary school you carry that one over to the next one right so that's what we're going to do if our thumb of our two digits is greater than 10 or greater or equal to than 10 we are going gonna get the one extra and bring it over to the next number so we're gonna put zero here and add one either to this three or to this four it doesn't matter you just have to pick one and add one so let's just pretend that this has become four so four plus four is eight and we are going to do that on the spot and that should give us the output so let us attempt to do that and as i've said we're gonna have a runner that goes through each one each of the lists so i'm just gonna define them here let r1 that is going to be l1 and that r2 is going to be l2 and i know that technically these shouldn't be null as i said before but whatever we'll just keep it as it is not a big deal and then we are also gonna have an output here on output that we're gonna return at the end which is going to be a list node or null technically it's not going to be no but we're going to instantiate it as no uh do i want to do this actually i don't want to do this i do want to not start it as null but let's have it start out as a new list node where we're gonna pass in the value of it later so i'm actually to erase this type in here get rid of that and then we're going to do some magic in between line 14 and 15 and at the end we're going to assume that the output is correctly formatted and just return the output so the magic will cut uh in between and what we are going to do is this while how long should we let this a while loop run while the rudder one and runner two runs we want this to continue until as long as r1 exists or r2 exists we want this loop to run and the reason why i'm doing this or is because the two lists can be of different lengths so for example here in this example l1 is greater than l2 so there will come a point when r1 is running at a number that um where r2 is pointing to null so we still want to keep on running still keep on adding the two numbers treat these empty digits as just zero keep on adding them together and just uh return the output at the end so let us do that right now let's get these some other digits i'm going to put that in a left variable for a reason i'll explain it'll be clear later we'll add up the digits the values of the two runners right now and that should be our digit r1 value or r2 that value now typescript is complaining to us correctly because and there should be two signs r1 or r2 can be no and that's why you can't put get that value of null so what we have to do is if this exists we're gonna use optional chaining if this exists gives us the value or just use zero and we are going to do the same thing here and for those who are not familiar with this operator this optional chaining operator this is essentially the same thing as r1 and r1 that val so we'll just keep it concise and do this so that will give us the digit but we have to consider the case where the digit is greater than 10. and for that case and let's just think about it what's the greatest number that this could possibly be let's pretend that these two were nine and nine right and this was nine and nine so we did nine plus nine and 18 we carry the 1 over one of these becomes 10 so it's 10 and 9 is 19. and 9 10 and 9 is 19. so the greatest that this digit can ever be is 19 meaning if we are ever in this scenario if the digit is greater or equal to 10 then we know that the digit that we're gonna carry over has to be a one it will never be greater than one so we could do something simple here what i'm gonna do is i'm gonna first subtract the 10 from the digit to make the digit to be a proper digit let's do that right now digit is going to be we're subtracted by 10 and we're gonna do some other magic here to carry over magic here let's just pretend that is done and we are outside of the if loop our digit if it was greater or equal to 10 is now back to a single digit or if it was never a two-digit number to begin with never a two-digit number to begin with never a two-digit number to begin with we're just out here because we never entered this if condition what do we want to do with that digit we want to add it to this list node on the output so the way that we are going to do that is this output that value is going to be the digit and then we want our output to go to the next one but this is where it gets tricky once we start re uh reassigning what the uh output is pointing to when we return here we're going to be pointing to the last node that we created so we don't want to run with the output as a matter of fact instead we want to have a runner of the output so let's just call that um what should we just call let's just call it runner of the output like this and the type of this can be list node or no so we're never going to be doing like output equals output.next because we output equals output.next because we output equals output.next because we want to keep the reference of the original output and instead let's do this instead of saying the output.value of digit we're going to set output.value of digit we're going to set output.value of digit we're going to set the runner that value is going to be the digit and just like we have created a new list node here if we need to create the next list node let's do that in this first iteration before we go to the next one and one is a scenario when we should create a new list though for the next one is if r1 exists and it has a next or if r2 exists and it has an x as long as one of these two has a next then we know that we need one more additional digit so let's just do that right now runner down next is going to be a new list node and then we're gonna set runner is equal to runner down next like so and it just auto completed a question mark for me because it could also be null um can it be no not necessarily because we have just typed it as a new list note here but typescript doesn't know that so we'll let that be and then we also have to let our r1 and r2 run right so let's do that but they could they should only run to the next node if they are not null to begin with so let's do that here if r1 then set r1 is equal to r1.x which may then set r1 is equal to r1.x which may then set r1 is equal to r1.x which may very well be null but that's fine if r2 is going to be r2 down next so we are gonna keep on iterating over adding the digits doing some magic that carry over the one keep on doing that until we get to the end and at the end we could return the output who has started out as this empty list that we have populated uh here so now let us uh take care of this magic that is going on here that is if the digit that we have added together is greater or equal to 10 we have to carry over the one so this is gonna be a bit tricky to do and i'm gonna do this if r1 exists and it's next exist then just add it here add it to that one r1 the nexus val is going to be added by one like so that may not be the case maybe for r1 we are at the imagine this was l1 we are at the end of the line and but for l2 there is more next of values to exist then if r1 didn't exist let's try for out r2 then r2 that next stop now gets incremented by one and let's put our l-sit here and let's put our l-sit here and let's put our l-sit here because we don't want we only want to add one once but these two now also might not be the scenario they both might not have an x meaning what if for this case uh two plus four no let's imagine this was like uh six right here right 6 plus 4 is 10. we want to carry that one over but neither of them have a next so let's do this else if r1 exists then we could make have it have a next then r1 done next is going to be a new list note this time because it didn't have a list now before and we're just going to set the value to one else it r2 because maybe r1 was already known and we just had to add it to r2 then r2.next is going to be a new list then r2.next is going to be a new list then r2.next is going to be a new list node with one and these four scenarios will actually take care of all scenarios whenever we hit this because we know that r1 or r2 at least one of them has to exist so worst case scenario is gonna hit this or it's gonna hit this it's never gonna pass on all of these if statements because of this fact right here so this should give us the correct solution now let us copy this and bring over to our lead code like so copy and paste it let's run the code for now to see if it passes and it fails and the reason why it failed is i did something incredibly stupid uh you guys probably caught this hopefully this digit right here should have been a plus like so let me go back here we are adding the two digits together not ordering it and that's why it gave us the first list because if you do something or this it will always give you the first one as long as that is true so now this should work yep it passes down let's submit and it passes so we got 254 milliseconds um which was actually slower than the other one i was expecting this one to be faster uh however we ended up using more memory um this is very inconsistent i noticed like before when i did this solution was much faster than my first solution so this is not 100 reliable i don't think but either way those were the two different ways that we could solve this add two numbers problem so hope you guys like this uh if you guys like this content please like this video to let me know that uh you want more of it and uh when the time comes i will be submitting a part three of this lead code a day keeps the dentist away so please stay subscribed subscribe to my video subscribe to my channel i mean and i will see you guys next time
Add Two Numbers
add-two-numbers
You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in **reverse order**, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. **Example 1:** **Input:** l1 = \[2,4,3\], l2 = \[5,6,4\] **Output:** \[7,0,8\] **Explanation:** 342 + 465 = 807. **Example 2:** **Input:** l1 = \[0\], l2 = \[0\] **Output:** \[0\] **Example 3:** **Input:** l1 = \[9,9,9,9,9,9,9\], l2 = \[9,9,9,9\] **Output:** \[8,9,9,9,0,0,0,1\] **Constraints:** * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` * It is guaranteed that the list represents a number that does not have leading zeros.
null
Linked List,Math,Recursion
Medium
43,67,371,415,445,1031,1774
871
Hello hello guys welcome to another video link syrup yes here all problem minimum number of curing stops work which traveling from starting question tourist destination and gas stations languages ​​parameters for gas station languages ​​parameters for gas station languages ​​parameters for gas station subscribe first parameter location of the point to Years Passed and Subscribe Problem Me Too Play List Number Three Do You Know Very True Love You All the Best Quite Amazed To See An Example To Understand Mystery Approach That Targets 120 Rate And Few Words Starting With Green Color Represents Your First Look Is The Problem Support From It's Okay Subscribe Must Subscribe During Every Age October 10th Smile Notification Gas Station Otherwise 12260 Will Take You Will Not Want From You Love You To You All Subscribe Now To You are the users can still alive Yashwant's this reception also you use list number of gas stations on a pension also you use listed very important part question leaves means Lifestyle can we do with one is it possible Darbhanga station weekend rate demands how will decide Which Gas Station Is That Point Baby So Well It's Very Simple But You Are See Gas Station Between The Evening Dil Se 0.2 Cost You The Evening Dil Se 0.2 Cost You The Evening Dil Se 0.2 Cost You Anything For Any Objection Certificate This Question Is That Was Not Reach Slaughter Of Subscribe Redoo Location Number 6 Flash Light Vyati Options 12131 Image Choose Option Of Station And I Was In The 4th Nov 06 2009 600 To The Number To Get Number Six Gas Ko Subscribe Number Location Ko Play Karo Ho Match You Can Reach To Sun Tan Dark Area 20016 Hair Commission Interesting Picture Love You All The Best Used Use Oil Target But Now You Can Only To You What Is The Problem Of The Great Khali When Time You Did Not Be Used To Give Me Food Subscribe To Maximum Do Tuition Logically Expressions Station Which Give Winners Maximum Accurate Want To Yagya Station Petites Giver Maximum You How Can We Use Oil To That Is Remakes To Forget You Give Access To Value Priority Queue Data Activated Successfully Automatically Store In Descending Order To Dowry Latest To This Problem Will You No Network Problem Share with Your Target We Start With You and Impotent Responsibility Important to the Page if you liked The Video then Shadow Gas Station Location Trusted 1610 Destination Location 2000 Leaders of 820 Questions A Teacher Brings Tears of Fuel and Wee Honey and Gas Station Off But Just You Check Location Number 66 Give Winners For It's OK I Love You To Two Numbers And What Do You Love Me For Years I Have 6 Points 1770 Simple Quarter 100 And Making Box This Side To And Consider Tiffin Gas Station OK 12139 Latest News of the World Leaders Discussed at the Meeting Will Take Off the Subscribe to the Page if you liked The Video A Hero for Its Users to Know Where Can Reach Maximum 10 Chapter 1010 Tay Let Me All the Best 100000000000000 Location Maximum Okay Now School Thank You Can you show me the 33351 OK patient this edition power targets 128 MB center and this below that 02-01-14 use this booster food in the morning below that 02-01-14 use this booster food in the morning below that 02-01-14 use this booster food in the morning use this we have used gas stations the number of process what is the number of like this three Number of Processes in and Gas Station and Location Tan First Use This End User Gas Stations Location On 16th User Gas Station Location Thirty Rights Beach Bajaria Station Reduce Entries for Different Topics Latest Right to Code This Typing Code Simple 131 Test Too Complex Thu or Fri I want to see what is the name of the hussain kilometer 100 initially with 222 but what happens to lead to change with time and again to declare variables or 120 matka prem ko * vinod retail account simple prem ko * vinod retail account simple prem ko * vinod retail account simple condition will be the that no You can check one more thing you can oxide shooting valley and upright events to rename fennel first person declare another in that implement declaring vaccine developed form so instituted of twin boys per important condition introduction so will check point extension of that now so much tension start size secondary Fuel Sun Text Always Been Said Will Get Another And Order For You To Develop It's Okay No Tension Know What Will Be The What Is The Meaning Of The Story Fuel Subsidy Gas In Our Hands Free Latest And Field And How To Store Jiva To Store And Check Clear Left Hand Book Maths You Can Reach Simple Loot Gayi Thi Okareshwar Tiffin To Make Her Way Into Introduce Particular Magic Saunf This To Be Difficult For This Post On To Kab Vishad Parameter Will Give Us Please Us Unwanted Station For Window 10 There Comparing With Gas Parameter Support The Parameter Is Tower Location Therefore Maximum Dictionary - One Who Have Written This Is Maximum Dictionary - One Who Have Written This Is Maximum Dictionary - One Who Have Written This Is One Important Now You Can Definitely Increase The Account Dr To This Award Which Will Take You Top Most Well Equipped With Maximum Volume to maximum alice what like and will 8282 what makes oo can reach with top most significant you is what is the few ladies marketing and drop earing you including father 10.2018 delhi removed from midnight children can give it working tomorrow morning rasam runtime hair soft it will ask Veervansh Sexual 100 Hua Hai Kal Su Failed Kal Su Failed Kal Su Failed Aur Sundar Beta Hai Main Reduced IF Possible Index Plus What Is Happening In Solidworks Incriminating While It's Coming Year Slide Yes I Will Have To Halvis Remix After 10 Line End B5 Vaguely Defined S 500 Gaj Spine of Languages ​​Submit 500 Gaj Spine of Languages ​​Submit 500 Gaj Spine of Languages ​​Submit Incident Working on Hai Sach Walking Dead Thank you for being patient and listening
Minimum Number of Refueling Stops
keys-and-rooms
A car travels from a starting position to a destination which is `target` miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array `stations` where `stations[i] = [positioni, fueli]` indicates that the `ith` gas station is `positioni` miles east of the starting position and has `fueli` liters of gas. The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car. Return _the minimum number of refueling stops the car must make in order to reach its destination_. If it cannot reach the destination, return `-1`. Note that if the car reaches a gas station with `0` fuel left, the car can still refuel there. If the car reaches the destination with `0` fuel left, it is still considered to have arrived. **Example 1:** **Input:** target = 1, startFuel = 1, stations = \[\] **Output:** 0 **Explanation:** We can reach the target without refueling. **Example 2:** **Input:** target = 100, startFuel = 1, stations = \[\[10,100\]\] **Output:** -1 **Explanation:** We can not reach the target (or even the first gas station). **Example 3:** **Input:** target = 100, startFuel = 10, stations = \[\[10,60\],\[20,30\],\[30,30\],\[60,40\]\] **Output:** 2 **Explanation:** We start with 10 liters of fuel. We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas. Then, we drive from position 10 to position 60 (expending 50 liters of fuel), and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target. We made 2 refueling stops along the way, so we return 2. **Constraints:** * `1 <= target, startFuel <= 109` * `0 <= stations.length <= 500` * `1 <= positioni < positioni+1 < target` * `1 <= fueli < 109`
null
Depth-First Search,Breadth-First Search,Graph
Medium
261
474
asalamu alikum ask 474 170 then first example M five n 3 Maxim answer four subset problem DP M 01 con string vector string s Str one 1 0 1 or one Z M five n man three result find Ma Max form maybe find Max form length size then DP for Z One Z integer Z count of s Str begin okay then integer one simple one then Matrix from bottom to right and top to left okay update uh DP Matrix uh from bottom to top bottom right to bottom left sorry bottom right to uh top left okay then similar one then DP of IAL maximum of DP J minus one on uh plus then DP of n m DP of m confused H keep problem sorry c contr p oh alhamdulillah submit accepted submit so done thanks for watching
Ones and Zeroes
ones-and-zeroes
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3 **Output:** 4 **Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4. Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}. { "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3. **Example 2:** **Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1 **Output:** 2 **Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2. **Constraints:** * `1 <= strs.length <= 600` * `1 <= strs[i].length <= 100` * `strs[i]` consists only of digits `'0'` and `'1'`. * `1 <= m, n <= 100`
null
Array,String,Dynamic Programming
Medium
510,600,2261
235
hi and welcome to prototype we will be solving the problem for lead code 235 lowest common ancestor of a buy-in lowest common ancestor of a buy-in lowest common ancestor of a buy-in research tree this is another problem in the lead code 75 study plan let's get to it so given a buy and research tree BST find the lowest common ancestor LCA node of two given nodes in the PST according to the definition of LCA on Wikipedia the lowest common ancestor is defined between two nodes p and Q as the lowest node in the tree T that has both p and Q as descendants and they also allow a node to be a descendant of itself okay and so we're given an example with the tree with the root note 6 having children 2 and 8 with child two having children 0 and 4 and with child four having children three and five and with child eight having children seven and nine and if we're given P equal to and Q equal to eight so two and eight then it wants us to return six the root node and in this case there's only one ancestor but let's just look at some other uh potential examples with this particular tree so if we were given P0 and q9 then the lowest common ancestor again there's only one it would be the root node right couldn't be two and it couldn't be eight because two and eight are not ancestors of both zero and nine now if we were given three and five have three ancestors four two and six but it wants us to return four because it's the lowest common ancestor or if it's easier for you think of this way the closest uh ancestor 2 3 and 5. okay so the trick in this question is to leverage the fact that this is a binary search tree in a binary search tree every child to the left of the node must be smaller than the current node's value and every node on the right side or the whole sub Tree on the right side has to be larger than the current node as well and both the left sub tree and the right subtree must also be binary search trees okay there's a couple other things that we should keep in mind so all node values are unique P will not equal to q and both p and Q are guaranteed to exist in the binary search tree so things to keep in mind as well all right let's do a recursive solution first so let's create another function let's call it recursive it's going to take a note and it's going to take p and Q and so again the fact that this is a binary search tree means that everything to the left of the current nodes every child on the left is going to be smaller and every child on the right will be larger okay how do we find the closest or lowest common ancestor well let's think about it without just looking at the problem okay we're given the root notes we're given six again let's say that we're given P3 and Q5 well both three and five how do they relate to the current node or the root node six both three and five are smaller than six what does that mean that means that both three and five are on the left side of six they exist in the left subtree of six and because both values exist in the left subtree there must exist some other node that would be closer to the children three and five right so if both of the values p and Q are smaller than six then we Traverse the binary search tree to the left and then we can compare the next node again with p and Q all right then child node of six is two how does three and five compare to two well both three and five are larger than two and therefore they must exist in the right sub tree of two and therefore there must exist a closer or a lower ancestor two three and five so because three and five are both larger than two we Traverse again to the right child finally we get to four and we compare three and five to four three is smaller than four and five is larger than four and in fact this means that or must be the closest ancestor or the lowest common ancestor to P3 and Q5 okay let's think of um let's say five and seven okay just one more example here five and seven five is less than six so it exists on the left sub tree and seven is greater than six so it exists in the right sub tree again because both children exist in different sub trees so again a five in the left subtree and seven in the right subtree there cannot be any lower or closer ancestors six is the closest ancestor so that's what we're going to leverage okay let's get to it so if the node value is let's say let's compare P so if the value of p is less than the current node's value and Q's value is less than the nodes value then what are we doing we're going to Traverse to the left so called node.left and then we just pass through node.left and then we just pass through node.left and then we just pass through p and Q and we'll return that otherwise if P dot value is greater than no dot value and Q dot value is greater than node.value is greater than node.value is greater than node.value then we will Traverse to the right and again pass through p and Q otherwise we must be at the lowest common ancestor so we return the current node and finally we can just return recursive and we call recursive on or the root p and Q all right let's run it and submit okay so beats 45.58 percent okay so beats 45.58 percent okay so beats 45.58 percent and just as a check let's just submit one more time see if it can be any better 99.5 percent there you go that's leap 99.5 percent there you go that's leap 99.5 percent there you go that's leap code from 45 to 99. okay so now we can leverage something very similar to do this iteratively and uh why don't we just do that so let's get rid of this and iteratively let's use a trusty while loop okay we'll need a variable for the current node that we're at and here we can just say well the current node is not null and then otherwise we're going to be doing more or less this exact same thing so if the Q value and the p-value is less than the Q value and the p-value is less than the Q value and the p-value is less than the current nodes value what are we doing we're going to Traverse to the left so Cur is going to be assigned curve.lap is going to be signed occur curve.lap is going to be signed occur curve.lap is going to be signed occur and then similarly on the right side car dot right will be assigned to Cur okay and um to save some space we can just say else we return the node because again if both values p and Q are smaller than the current node then we Traverse left if both values are larger than or another introverse right otherwise we have found the closest ancestor now this is the most concise way to write this I probably wouldn't write this in production um but this does work because and we don't even need to say return curve here because we know that there will always be an answer but otherwise I would probably say wrap this and wrap this in the Boolean expression right and then once neither of these are uh pass then we know that we can break out of the loop and return curve but anyway this is more concise so let's go with that submit okay 90.2 percent okay 90.2 percent okay 90.2 percent okay so that is the recursive and iterative solution to lead code 235 lowest common ancestor of a bind research tree subscribe to see more we'll be following up with the rest of the lead code 75 study plan questions in short order thank you and see you next time
Lowest Common Ancestor of a Binary Search Tree
lowest-common-ancestor-of-a-binary-search-tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8 **Output:** 6 **Explanation:** The LCA of nodes 2 and 8 is 6. **Example 2:** **Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4 **Output:** 2 **Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[2,1\], p = 2, q = 1 **Output:** 2 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the BST.
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
236,1190,1780,1790,1816
7
lead code problem number seven reverse integer so this problem gives us a sign 32bit integer X and we have to return x with its digits reversed and if reversing X causes the value to go outside the sin 32bit inte range basically in minan or in Max right here I Jed down the values what is in mean then we have to return zero and here is the important part we have to assume the environment does not allow us to store 64bit integers sign one side meaning that we can't just use long and basically that's it right that those are the rules so here you examples one two three we get three one so let's use that as an example let's say x is 1 2 3 so in this case result would be zero first thing I do is I check if X is not zero then we are good to go we can keep on dividing X by three right so basically the idea is to cut off the number from the back and then add the number to the front right I show you what I mean so now uh this me right now because result is obviously not more than INX by 10 and is lesser than mean 10 for now just ignore this we'll get back to this later we'll just uh look through this with the example with a simple example such as this first okay 1 two three equals to results time 10 so now results * now results * now results * 10 which is basically still zero plus X modulus 10 so X modulus 10 1 2 3 modulus 10 will give us three right so result is now three for it will uh this x will divide by 10 so in integer since we can't have floats right we can't have pointers or we can't have decimals not pointers so what this three will just disappear right so now we are left with one and two so we do the same thing result time 10 this * 10 is 30 + x modulus 10 is 10 this * 10 is 30 + x modulus 10 is 10 this * 10 is 30 + x modulus 10 is 2 so 30 + 2 is 2 so 30 + 2 is 2 so 30 + 2 is 32 divide by 10 Again 1 * 10 + 1 right X 32 divide by 10 Again 1 * 10 + 1 right X 32 divide by 10 Again 1 * 10 + 1 right X modulus 10 will just give us one and result will be 51 after which if we were to divide it again X is now zero right and since X is zero this for will end and we will return our result which is 321 right which will match the result given in the example okay so let's say so what is this if statement for so let's say we have a very big number let's go with something like this right PR is outside of INX it's good to check okay it's not so we'll add another nine here okay after which let's say we have this number right so we know what happens in the for Loop right so basically we will divide by 10 9 by 10 again nine and 8 88 this seven 6 5 4 3 two okay right at this point if we were to run with this each statement right result is it more than inex divided by 10 okay let's see so inex is this number divided by 10 again we remove the last number right so let's remove it like this you can see our result is actually bigger than INX so what will happen is if we were to continue times 10 to this 32bit integer it will overflow right and we don't want that to happen instead we want to return zero so that's how we check right basically divide INX by 10 if it's going to go above the integer Max or we compare it against the inmin see whether or not it's smaller than inmin ID by 10 right so if either of these condition is true we will want to return zero instead so for this case the result of this would be zero okay so yeah this question even though it's medium it's actually pretty simple not sure whether that's because it's cross pass but yeah to me it's pretty straightforward anyways that's all I have to show thanks
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
295
Hello hello guys welcome back to tech division in this video you will see media and in no data stream problem something from the list number to 9 500 latest reader problem statement no problem medium size maintain value and order in to-do list size maintain value and order in to-do list size maintain value and order in to-do list play list In the middle name is the mean of solid example element two three and the number of elements in the middle of elements have to the mid point mintu number from 2018 will be written in the media and of the elements which they have seen shopper stop this problem Statement Latest Example Media Can Only For All Elements In This Is The Number Of Elements Which Will Be Plus One Element The Number Of Elements Of Obscuritism Plus Two Elements And Will Be Divided Into Two I Know This Is Not Order In This Way Will Just after attending or morning to three four after doing now will take the middle element which is the number of elements in this elements of villages in ascending order will be The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing spider -man Will subscribe to The Amazing spider -man Will subscribe to The Amazing spider -man Will Give Elements Are Not Give The Giver Element Quizzes Number Five Know What is the Meaning of the Singh Elements In Charge Jaswinder Singh Element Brand Value Will Be One and Some Indian Will Win This Element Services From Pet Knowledge You Are Singer Element Witch 323 294 323 subscribe The Video then subscribe to the Page Ki no will be singh hai na der element which is this point fennel and this coming no this is not order will just after intelligence service three 500 to 1000 number of elements of which will be added subscribe to the Page if you liked The Video then subscribe to the Remind Me Indian Give Any Stream OK So You Can Be Easy Aaj To Find The Media And Any Given Freedom At Any Given Point OK And You Will Be Considering All Elements That You Will Be Keeping Elements In Order To Be Able To Understand This Simple Solution In Order To Solve This Problem Will Be The First Most Important Veer The Element Servi Elements In Order To Give You Can Absorb Ki Element Servi Please instructions for this really use no weir wedding you element to give the interstate 1659 and streams having three elements 2.5 entertainment industry ministry 2.5 entertainment industry ministry 2.5 entertainment industry ministry less will be using instructions for insulting three and the current position latest that we can infer from the right and where moving objects can Find the Proposition for Elementary Level Been Sorted in Between Two 400g The Element Subscribe 12345 subscribe to the Page if you liked The Video then subscribe to the Number Operation Your Sorting Element Not Finding Media Is Nothing But Using Formula That Is It Is Having A Number Of elements and a plus one element Dravid number two plus one element subscribe this Video Total time complexity of way the solution Total time is it possible to improve the solution David possible to reduce 209 congress you must be now serving sea of ​​things which are given congress you must be now serving sea of ​​things which are given congress you must be now serving sea of ​​things which are given In the problem solve india server only interested in finding them with the limit of dashrath ok and media ne revenue expenditure shoulder tanning god are using them in this is the time to know more number of elements and take of the question which comes to mind e Really Need All Elements In The Answer Is The Element Which Is The Number Of Elements Lord Who Will Just Be Having A Single Man Element Otherwise The Number Of Elements Of One Who Will Win Every Single Thing Which Element Is In Maintaining The Complexity And Elements Which Element in search operation and subscribe and no one in this world can just reduce ho but is time taken to maintain doctorate you can reduce the number of soldiers where is it possible to reduce the time in this order will not be ready for balance Balance Tree Will Be Very Highly Compressed 100 Gram Melt Paris Are Balance Binary Rate So They Can Make You Laugh And Just Give One Example If You Think About Using He And Use This Is The Question How To Use This Problem Example2 6 Media In This Case which element filter element with just a few such elements in to the it's your pocket and between number of elements and you will get the middle element shopping obtained by two number of elements getting the middle element and again In putting all the day in the two elements with consumers huge amount of time and so will consume one by two to log in time Sudhir Vinati button log in time for each element in social forum will give one example of obscurism subscribe elements citizen more solution which will Bay Boys Problem Maximum and Minimum Element but Will Need a Number of Elements This Video Not Required to Maximum and Gum Investment of the Center Roy Ok and You Soe Important Observation in This Is It Say You Have Been Given Number of Elements You Can Divide Element in Between you can create first half and sacrifice no effective want to find the meaning that you are doing this you will take maximum difficult absolutely minimum of the lambs maximum subscribe 2.5 this is the first half will be having one subscribe 2.5 this is the first half will be having one subscribe 2.5 this is the first half will be having one element extra divide elements in the first of All subscribe to quick with you want to find the media in the Indian and number of elements will only be single element and will be the maximum element in the first rate in the morning Maximum age limit for the first half This is the way to find The Mean That In Order To Avoid Cold Water Will Be Difficult For Media And Subscribe Divided Into Two Elements In The First Phase Of Poles Were Divided Into To Take Medicine For The First Time Apni For The Second You Read So This Attractive Solution You Might Not Getting The first time you can understand you can play in the problem in order to understand and subscribe our country the size of the subscribe and subscribe the difference between a ko suli charda points to remember no you can also azim directory element which state in Thum In His Words For Simplicity Is Taken For The Shape Of You Can Do It Is The Way Will Be As Well As Will Not See The Subscribe subscribe and subscribe this Video Website Is One Greater Than Thum In His Eyes Additional Not Directly Been Sorted Into The Maximum Will Be Getting Selected Navodaya Multiple Condition Of Insulting Istri You Will Have To Compare Doosri With The Top Of The Seat Debit The Series Who In The Forest Of Elements Of Women Are Divided Between The Maximum Element In The First Is The Element Middle Order In This Element At The Rate Of The Three Layer Pendant Three To The Other Is This Element Which Will Be The In The Robert Count 3152 Gather Cannot Be Present In Maximum Vitamin Hips Having Zero Number Of Elements So They Want To Equally Distributed Elements Between Maximum Minute Notification More Divided Between Them Will Be Coming To The First He Will Be Coming Subscribe To The Number To The Self Plus 382 34 That's Nine Let's Go To The Next Element Is Add 400 Want To Insert 499 Ine Bluetooth Of The Same 499 Ine Bluetooth Of The Same 499 Ine Bluetooth Of The Same Size Arvind 409 Subscribe Element Subscribe Top Of The Subscribe Elements Present A Number Of Elements See All Quick Containing 18000 Verses And The President Will Be No Want To See The Element Only After Two Elements And Distribution 12345 Will Be Divided Into Three Four And A That Know How Do You Rearrange Desi So You Can See The Two So On This Day The Root Of The Match David Will Be Fall Into The Fans Don't Miss The First And Subscribe One Element Extra The Video then subscribe to the Page if you liked The Video then subscribe to the Page Ka Birthday Sex Can Go To India the maximum in have reached its an order soegi friends this is the root of the subscribe to the Video then subscribe to the 4606 know the number of the root Of the giving elements and absolutely media remedies love because in the voice of printing element you can we are tourist inside medium ok sorry time complexity and justice vr insulting and number of insulting element in two that is nothing but pushed into the best android login In this video you will just total time complexity of time which is very simple but as we know you will find the sun dot co dot in quest train fare will be given no constructor which is medium finder here you can influence your data structures but it is not required Wishes Servi Avoid Doing So Will Be Having Difficulty subscribe and subscribe the Channel Will Be Quote Get Into R Maximum Otherwise Maxi Fee No Top 10 Days Maximum In For The Simpsons Day Obviously Mexico Will Give One This Is It Maximum Per Of The Same Size for all elements which will be having one element extra but due to which element which is the one which will be the top of the in voting to declare the match and again insulting this new element which is number Into them in his work Sudhir vich will recommend you to solve this problem in subscribe and Share subscribe and subscribe the minutes ago Jai Hind is third case of minute size aerobics exercise equal to one for office after adding this element maximum size Dhawan and minutes Will also be given but this unexpected this number will be sent to withdraw the value of elements in the top left for this is the mean of the top element which can increase the other is not through this element which will push the number * Subscribe to element which will push the number * Subscribe to element which will push the number * Subscribe to your Only Maximizes One Medium Size Phone Know What Happens When There's No Rule subscribe and subscirbe In That's The Meaning Of This Number To The We'll Keep Watching This Is The Meaning Of This Is that you solve this problem will be able to figure out which you need to eat cases will take some time it takes some extra time but while food and fuel and soul within you can just watch this video in order to figure out all the cases No This Is The Indian Case Hair Dravidian Formula Will Only Depend On What Will Be The Number Of Element And Rate So Busy These Days Subscribe To Subscribe The Channel And Subscribe The One That Will Be The Rebel To Do Help You Whenever Possible IF YOU LOVE Waqt Din please try to donate which will help us bring more free quality content in future for everyone see you in next video thank you
Find Median from Data Stream
find-median-from-data-stream
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values. * For example, for `arr = [2,3,4]`, the median is `3`. * For example, for `arr = [2,3]`, the median is `(2 + 3) / 2 = 2.5`. Implement the MedianFinder class: * `MedianFinder()` initializes the `MedianFinder` object. * `void addNum(int num)` adds the integer `num` from the data stream to the data structure. * `double findMedian()` returns the median of all elements so far. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input** \[ "MedianFinder ", "addNum ", "addNum ", "findMedian ", "addNum ", "findMedian "\] \[\[\], \[1\], \[2\], \[\], \[3\], \[\]\] **Output** \[null, null, null, 1.5, null, 2.0\] **Explanation** MedianFinder medianFinder = new MedianFinder(); medianFinder.addNum(1); // arr = \[1\] medianFinder.addNum(2); // arr = \[1, 2\] medianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr\[1, 2, 3\] medianFinder.findMedian(); // return 2.0 **Constraints:** * `-105 <= num <= 105` * There will be at least one element in the data structure before calling `findMedian`. * At most `5 * 104` calls will be made to `addNum` and `findMedian`. **Follow up:** * If all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution? * If `99%` of all integer numbers from the stream are in the range `[0, 100]`, how would you optimize your solution?
null
Two Pointers,Design,Sorting,Heap (Priority Queue),Data Stream
Hard
480,1953,2207
606
foreign this is Larry this is day seven of the liko day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's fun construction train from binary tree I'm just oh yes so sometimes I click I don't know if there are other Pages let me know in the comments if you know of the other pages but I sometimes check this not because I'm I don't know obsessed or something maybe I am but not be only because of that but because of this button on the upper left LC easy plus 10 you click on it and it doesn't show up every day but you got 10 Bitcoin uh yeah 10 Bitcoins so and you know you can always have more lead coins for a t-shirt or something I don't know right t-shirt or something I don't know right t-shirt or something I don't know right so anyway that's just something and also uh hope you like the intro I'm actually in London right now um so maybe some of this would be a little bit uh you know uh from a couple of whatever it goes so hope you enjoy it uh when I was in Italia and there's some beautiful stuff so I want to show it off a little bit uh so indulge me in it even if you may not care about it I do need to make the music a little bit lower I keep on editing the script but I don't know let me know if you think about the volume or whatever um okay it uh it's 7 A.M in London so that's why it uh it's 7 A.M in London so that's why it uh it's 7 A.M in London so that's why I'm like doing the waking up routine um cool anyway today's Farm is construction from binary tree okay what does that mean we're given a root of binary tree construct string friends pre-order okay construct string friends pre-order okay construct string friends pre-order okay so just pre-order and so just pre-order and so just pre-order and uh yeah okay what does the prevent action mean so okay oh so basically left so okay so it's just pre-order and then every time you just pre-order and then every time you just pre-order and then every time you do a recursion you add friends right so let's get started um I think the thing that you might have to think about is to string can cat but we'll go for it um so pre-order so we'll just write you um so pre-order so we'll just write you um so pre-order so we'll just write you know pre-order right now and then we'll know pre-order right now and then we'll know pre-order right now and then we'll write out the sketch and then figure out how it is that we want to uh you know finish it or whatever so then pre-order is just you know you then pre-order is just you know you then pre-order is just you know you would process no and then we pre-order you know that left and then we pre-order you know that left and then we pre-order you know that left no that way right okay so that's the skeleton uh how do we want to do it um because the thing is that you do a lot of string concatenations it may be a little bit messy so or like it could divulge in N Square which I guess for a thousand no way ten to the fourth I don't know but I rather not having to think about whether that barely times out especially on lead code where the platform is a little bit um uh for python it's a little bit you know like where the time's out or not at least for me I have a lot of uncertainty and that's kind of partially why I've been doing that as well lately is because I think I second guess myself a lot anyway this is an easy I'm not saying it's easy but it is an easy level problem uh is what they say so um so we should just let this you know see like so for the current number we want to uh something like this right and then for the left um so if I also have to do like if notice none but um and then here we go with the load examples not none then we pre-order I'm examples not none then we pre-order I'm examples not none then we pre-order I'm usually I don't need to do it because this one will get it but we want to wrap it around that's why I'm doing it this way um and you can do it in a fancier for Loop so let's maybe do that uh well let's write this first and then we write the open fluent oops and then we do the course parents and I think that's pretty much it and then now we can do maybe some funky for Loop where like for a child and no dot left go that way something like this right child is not none that will pre-order on child is not none that will pre-order on child is not none that will pre-order on it uh and then at the end we can return to do and of course we want to pre-order the and of course we want to pre-order the and of course we want to pre-order the root I forgot it the other day that was a silly debugging but yeah um okay so that's a little bit sad oh because huh okay so I got the first one right but the second oh you cannot omit the first parenthesis because then now you have to do it left um foreign that's fair um let me think about I mean to be honest this is just like an if statement but uh and if I was in the contest I would just think I would just do the if statement but I mean I'm just trying to think um it's still a cleaner way of doing it because you know look at this code right now it's very clean but that said clean code that is wrong is not useful right um messy code that is working is still more useful than clean code that is uh that doesn't work so but um okay I think the way that you can do it is have just like a Maybe but then this also May um was extend is like not very great because then now you have the same issue with um actually I think we could fix it but you might have the same issue with the n-square type thing which is maybe I the n-square type thing which is maybe I the n-square type thing which is maybe I shouldn't do it this way then maybe we should just do if statement okay fine because I think I'm trying too hard to be uh clever and cute um but sometimes you just have to do it um yeah okay foreign case I'm trying very hard to save my for Loop but I think maybe I just need to smash I don't think that I can do it um so yeah so okay let's write it out back out again uh sorry friends um let's unload the loop because they're not this is not the same as I thought they would be so yeah thanks I mean this isn't that bad it's just that I was really trying hard to do it and then here we go and then maybe we could just do if no dot left is none then we do I hope this is right let's try the empty note I've been missing that oh I guess we have at least one note but uh let's just do something like that some basic trees at least to show that I tested small ones let's give it a submit have I not solved this before well yeah a new problem for me solved uh 890 day Street yay um so yeah this is gonna be linear time linear space I mean the real tricky thing about this one is that it is easy and possible to do genuine and square if you keep track of like um a string concatenation thing you can definitely if you keep on concatting because of immutable strings and stuff like this um it's going to create more instances and then you're gonna have that like one plus two plus three plus four dot which sums to n square right um or o of N squared I know it's not exactly n square but um and that's what you do not want to do so that's why I kind of do it in a funky way with this answer and uh and yeah and each um each character of the string will only be wizarded twice right once to append to the answer and then the second time by joining so that poops out all of n uh time and space um and time is just because we look at each node once but uh yeah uh that's pretty much all I have for this one let me know what you think uh I know this is a very um last minute paying but if you're in London and uh you like to grab a drink um I think one of our uh Discord buddies uh what about fans are trying to uh we're grabbing a drink somewhere Friday night I know this is in like two days maybe depending on where you're watching it uh well we'll be in London then uh and you know hit me up we'll go with Discord and we're organizing something I mean if not it's fine too um and if you're watching it from the future sorry you miss it but uh anyway that's all I have to I'll see y'all later stay good stay healthy take good mental health take care and hope to see you soon huh bye
Construct String from Binary Tree
construct-string-from-binary-tree
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it. Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. **Example 1:** **Input:** root = \[1,2,3,4\] **Output:** "1(2(4))(3) " **Explanation:** Originally, it needs to be "1(2(4)())(3()()) ", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3) " **Example 2:** **Input:** root = \[1,2,3,null,4\] **Output:** "1(2()(4))(3) " **Explanation:** Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-1000 <= Node.val <= 1000`
null
String,Tree,Depth-First Search,Binary Tree
Easy
536,652
744
Hello Gas, today we are back again with Gyan Portal and Gas, now we are going to challenge the lead to solve the daily problems I come across and the problem you are seeing today is The target of 744 is to find the smallest letter. So basically, first of all we have to read the big part of this problem, what is the problem? The problem is to tell what is there in the problem. We have given one letter named 'Hey'. Which means We have given one letter named 'Hey'. Which means We have given one letter named 'Hey'. Which means in non-decreasing order, non-decreasing in non-decreasing order, non-decreasing in non-decreasing order, non-decreasing order means in increasing order and one character has been given to us which is our target character. There are two different characters which are mentioned in the letter. To return means that lexicographically we have our ABC. The meaning of increasing order is that it gives anything lexicographically for serography, like if we say that C is the lassi of C, graphically greater, if we talk, then C is greater for lexicography, what can happen if we talk. May be A may be but if Di and A we need two then C K lexicographically will be our Di [ lexicographically will be our Di [ lexicographically will be our Di So in this way we have to tell the things as they are, we have also been given two examples in this, first our example is letter error. I'm given we've got C, we've got F, N, G, and the target we've been given equals, yours, we've been given equals, so what could that be Now we're on to that. Let's talk, first of all, if we talk about it, firstly, what can we do with a simple approach, what can we do by traversing all the letters given to us and traveling through it, what can we do? Take the story and store what we have and then we compare what we have with the target to see whether that is present or not and if it is present then we input what is next to it and if not then We will put whatever we have on this index, so let's see when the solution will work or not, so let's start solution one and what will we make in it We made him travel till the length of the letter and Driver Singh, we have the letter. What have we done to it and taken its input, what will happen from it, whatever characters are there in our alpha, that student means in a way we have made a frequency, its name is let's go, okay, so this is what we have named this whatever is alpha. Our frequency of Hey, made it at but we have idea which is our idea, we have seen it with zero, is it our alphabet, is it our present, is it not our present, if it is not present then what will we do, we will ID it X with just one. We will simply increase it okay and then after we have done this we will return it okay once what happens then you can see how all the tests have been done solution because sometimes binary If you want to understand the approach, whether binary search approach will be used in this or not, then its basic is that one target will be given to you and one will be done from Ara, then whenever something like this is seen, then there is no story or story and you can get the idea that Binary search can be done there. Okay, so what is the benefit of binary search? You also know like till now I have told you what happens in search. In binary search, what we lose becomes more, then we balance it. First we have a We have taken this L and then our and we have first put the condition that letter else if then else if the target is ours, what will happen to us, the target should be bigger or equal, the letter else -1 has letter else -1 has letter else -1 has traveled through all the letters, but the target Still, if we can't do anything big then what will we do, we will simply return So what will we do, letter What will we do, let's meet ours one by one Who knows, if something bigger than this is already present, because we have to extract it lexicographically, so if not, if we come to know that this is ours, which is later, mid, which is smaller than the target, then what do we have to do, we have to travel further. If we have to do it then we will go till there, what will we do, simply do mid plus one and what will we do in return, we will do our return and let's see, not only by doing gas, but something like this is okay So okay, then this way Our problem has been submitted. I hope you have understood how we have solved it. Find out, subscribe, share your
Find Smallest Letter Greater Than Target
network-delay-time
You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`. Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`. **Example 1:** **Input:** letters = \[ "c ", "f ", "j "\], target = "a " **Output:** "c " **Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'. **Example 2:** **Input:** letters = \[ "c ", "f ", "j "\], target = "c " **Output:** "f " **Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'. **Example 3:** **Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z " **Output:** "x " **Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\]. **Constraints:** * `2 <= letters.length <= 104` * `letters[i]` is a lowercase English letter. * `letters` is sorted in **non-decreasing** order. * `letters` contains at least two different characters. * `target` is a lowercase English letter.
We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm.
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
Medium
2151,2171
113
hey everybody this is larry this is day fourth of the august nicole dairy challenge hit the like button to subscribe and join my discord let me know what you think about taste problem have some too um so i usually solve this live so if it's a little bit slow just fast forward move ahead whatever you need to do uh okay so given a rule and talking somebody don't would to leave with some each half sum is equal to target some aliens okay this should be straightforward in that uh the key difference between this and maybe a similar problem that i was looking for is that each path is from root to leave right and that means that you can kind of um implement things in the stack because yeah uh at an implicit stack where um a different search or an auto traversal type thing or an explicit stack because the idea is that every time you see a node you push it you check and then you um pop it right so this is going to be linear time and knowing that this is linear time because it is essentially an order traversal or a choice of the tree um you know that i don't have to really look at the constraints because linear time is probably gonna be fast enough uh the only thing that may like a variation that may change that is for example if there are a number of target sums then you might have to play around with some ideas but at least in this case because of those two things you can do it in linear time relatively straightforward and it becomes uh an implementation problem uh and here there are a couple of kind of pitfalls but in general i think this should be pretty um pretty good there are a couple of ways you can think about this problem but oh and in this case it's actually root to leave i think that was the other thing that i was actually double checking was whether for example intermediate nodes is good for example if it's five if the target sum is nine it's five plus four you know it's not a rounded path in this case this is actually not because you have to go all the way to the leaf so that's you know with that let's go all together um and in this case even though i said it's an all traversal um it is kind of a variation of proof force uh and on that end because you're trying every route to leave paths um it just turns out that they're at most end paths because um because they are most n leaves right which is not even possible but now that in some you could do some math around that um but anyway okay um okay so n is at most five thousand so like i said it doesn't even matter so let's go around it so here naming things is hard but i'm going to go let's just call it recurse now you just call things go as my default value want to be a little bit better here so let's just call it partial half sum or something like that um and then you keep track of the node the current path and the current target sum well i just you can do it either way you could either return the current somewhere the targets or the current targets some left by keep on subtracting it right so it doesn't really matter um yeah and then here if node is none we just return i don't know you shouldn't get through that if no it's not none in this case and we won't check it where there's a leaf one thing that i tried to be too clever in the past is um but now i'm trying i just be explicit about it uh because it's just do it's you know it's a symbol and anyway if this is a leaf then if current sum is you go to target sum then we do some magic with the path right so current path let's just say we have a list of answers or paths then we just do path start append current path and one thing that's got a caveat here especially for python users might depend on other you depend on your language um and you'll go into this a little bit but depending how you construct this current path um you may be copying the pointer instead of the actual list content so the thing that i would do here is just do this and what this does is that it creates a new slice of a list in python anyway a new slice of list that starts from the beginning to the end essentially making a copy of the list anyway and then we uh well we return in both cases and then now if it is not a leave then we just do a recursion on the left and the right um yeah so partial path sum in this case you have node.left sum in this case you have node.left sum in this case you have node.left current path plus um let's see oh yeah right or that value i suppose there's a couple you can do it in two different ways and you could for example do something like this uh where is it know that value and then you do current path or you could just do current path and this i think this actually creates a new list anyway so i don't know how you feel about that per se it does create a lot more space so let's just do it the responsible way and then here we have current sum plus note that value and then here we have to pop off the thing that we just added um and now we go to the right oh actually well you could do it i guess they're actually you can prematurely optimize a little bit which is the same except for it's this right so in this case obviously these things canceled out so let's just do this um yeah i think we're good here so now we just have to kick it off with power sum of uh root target sum oh no this is zero and then we return paths so there are actually also a couple of alternate ways to do it as well you can make it so that this actually returns a list and but then you have to go through it every time to um but as you go up to kind of reconstruct the path maybe that's better i don't know you let me know how you feel about it but they're just different ways of doing it uh okay well that's not promising perhaps some mistakes were made now i can't imagine this well i mean this actually would be right because it doesn't have any answers but this is discerning hmm did i miss something weird that's weird trying to do this maybe so you i would imagine it complains if it doesn't but uh but if you have a silly some minus silly thing here but okay i mean i don't think i spot anything obvious in my silliness so yeah let's print our current path here let's see if we at least get to the end um okay so we don't do that at all do i early terminate by accident try at least get two leaves okay so i do get two leaves for x oh i'm just being silly basically if i get to the leaf i do not consider the current node value right so actually okay i this is a an edge case but on the tree variety where i actually start from zero instead of the root note you can actually do this in a couple of ways i think i did it this way for whatever reason and yeah um oh yeah just being very silly uh because then here because we added the sum so now it's good but then now we also want to add to the current path as well uh so if this is good then let's just say on path dot append and then currentpath.pop okay so this should be good a lot of a little bit sloppy here maybe we could have done it in a way that has better base cases but um but let's give us a minute i'm well totally confident about it every time i say that you should get one but this time it is accepted um as we said this is going to be linear time because roughly speaking linear time the actual expensive part of this and i don't know that there's any easy way to avoid it is actually like we said this is the number of current paths um i think in a given a full yeah given a full binary tree you can imagine this log no that means that there's n over two leaves and we reconstruct n over two leaves and each path is locked and i suppose in that case five thousand like out of five thousand is uh like what twenty no not twenty uh 12 guys so 12 times 2500 i guess that so that's the only thing that i worry about uh and i'm trying to kind of be a little bit tighter about it i mean i already got accepted but if you want to consider because this is the expensive part um and that's also the space as well it's that in the worst case in a full tree then you have n over two leaves is anal beliefs the worst case yeah i think so i'm also trying to think about the other one where it is not binary but and in that case you can have a weird amount of space issue in that case it'll be five dollars i think you can actually get it to a case where memories actually end square ish um you know the time i think should still be no i think the answer is n square and the case that i have here maybe just visualize it will help a little bit is that in the worst case i don't have a full binary tree maybe the worst case but actually i think the worst case is actually something like um let's see if this works i don't know if this is the right format but yeah so you have something like this except for oops i don't know if i'm doing it right let's see okay so something like this um i don't know i'm gonna do it this way okay well uh so now one two nope uh and then now okay so something like this right so the idea behind this input set uh okay is that well they're gonna be n over two leaves but the space is gonna be um and you can actually do this in a i actually think i messed up with the target um actually well if you put it always zero i think that would because i think this is yeah so if this is all zero then this can actually happen right where then now your path is gonna be n over two and then n over two minus two n over two minus four and dot and it becomes n squared essentially right so in that case the worst case scenario for this is actually n squared um and n and um n squared time and square space so the nuance here is that the current path matters if you did not have to care about current pattern let's say you're trying to return only the num the count of the number of um paths then it actually is linear time but because you have to do this copy to kind of copy into extra space and you cannot be do better than n square space in this case because that is the number of like you have to allocate the space for n squared space anyway because that's the size of your solution so that is the lower bound for this problem in that case right so yeah so it's linear time plus the output sensitivity which is um average and square quadratic anyway um yeah that's all i have for this one let me know what you think hit the like button to subscribe and join me in discord happy wednesday or whatever stay good stay healthy to good mental health i'll see you later bye
Path Sum II
path-sum-ii
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_. A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** \[\[5,4,11,2\],\[5,8,4,5\]\] **Explanation:** There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** \[\] **Example 3:** **Input:** root = \[1,2\], targetSum = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Backtracking,Tree,Depth-First Search,Binary Tree
Medium
112,257,437,666,2217
147
okay kids we're here for insertion sort lists now first of all before beginning whenever you want to deal with linked lists or sorry when you want to learn about them i recommend going here at this particular address link list problems and linked list basics over here as well and this is from stanford as well as all the associated lessons on binary trees and pointers you start off with pointers then you move on to linked lists and then you move on to binary trees and you're golden this tells you everything you need to know in so far as linked lists and binary trees and it's actually explained in english okay let's get going so given the head of a singly linked list sort the list using insertion short insertion sort and returned the sorted list as head the steps over of an insertion sort algorithm are so the insertion sort iterates consuming one input element each repetition and growing a sorted output list well let's just see what it does here okay so they have the little image um which is moving at a stale snail's pace but essentially you take an unsorted list and you create a new one that's sorted that's it okay let's uh let's do that so that's what it tells you to do you return the node pointing to the head of the new list that's all you want to do so how do we get started here first thing we do is um we create we want to iterate through and they actually tell you what to do so you iterate through the current list which is what they give you and at each iteration you remove one element from the list and then you just insert into the new list in its sorted order so okay so we'll come up with a current pointer that points to so we don't lose the head pointer that's one thing we don't want to lose over here um we don't lose the head pointer but actually that wasn't necessary here but in most cases it is we also want to create a new list and set it to null right now that new list has nothing um now while current not equal null and this is kind of standard nomenclature to iterate this is your format this is how you move from one node to the next each time you iterate you just go to the next one and if it's ever null it gets out of this loop that's it um so we want to identify the list node what do we're going to call it my insert node and this is the current node that we're going to remove from the all list and place into the news list so that's going to be equal to current then current um then current will already be equal to current.next um we actually don't need our current.next over here since current.next over here since current.next over here since we just went there okay so we just went there and that's how we do it now we're dealing with we want to know how to deal with this my insert node over here so we want to take this my insert note that we removed and put in the new list well the first thing we want to do is make it kind of uh um we want its next pointer to point to nothing so far we don't know where that next pointer is going to oh sorry it's my insert node and then we're going to have to create some sort of magic function here which is going to take the new list as a parameter and the node that we want to insert and that's it as we iterate through the list we identify the current node we remove it so we set its next pointer equal to nothing so at this point this is an individual node and nothing's pointing to it uh and then we insert into the new list okay so let's come up with that insert node method which we said would take a list node star and it's important to put this ampersand y because we might modify the head of the new list not only might we will so we're going to call this new list and we want to pass in the um the insert node by uh by value actually so that's my insert node over here um yeah or yeah we could just stay phone ringing i'll just interrupt good lord where were we oh yeah well that call was actually from facebook go figure um let's get on with this we're doing this insert node type of function which works with this thing over here as we're iterating through all of the nodes from our original list we're going to split them from that list and insert them into the new one so the first thing that you might want to this is well if the new list is null then you um then new list equals um equals inst my insert node that's it because if there's nothing then the first element will be that first insert node um now let's see now else if now if you want to check well where to insert this before the head or after the head somewhere down else if my insert node val smaller or equal to new list dot val so remember that when you talk about the new list it's always the first element if that's the case then you just want to take your my insert node and have it point to uh to the new list then you want your due list to become my insert node again all of this is made much easier if you read those stanford problems which will grill you with this type of you could say this type of nomenclature um else so if it doesn't come before it necessarily comes after the first node in the new list at which point you have to iterate uh you have to iterate within the new list and um and see where exactly you want to place this thing so we use our little model while current not equal to null and we immediately write our current equals current.next again this is our model for current.next again this is our model for current.next again this is our model for how to iterate down a list we say well we say okay so what we're checking for is um okay we want to check whether there's a pointer after meaning if is there a node after the one we're currently on within the new list and if so uh if so or actually let's check if it's null and if it's not null then necessarily our insert node would be bigger than the current one so if that's true then we send the next node of the current one that we're on to the insert node and then we just return so let's just write that down if current dot next equals null so if there's nothing after and our my insert node bigger or equal to current.val if that's the case current.val if that's the case current.val if that's the case then we could just how would we do this oh yeah we sent current dot next equals my insert node so there's nothing after so we don't need to worry about the one that comes next and then we just return so we didn't affect the head pointer we could just return if we could put an elsif but since we have the return here it would never hit this if in any case so we could just do another if here so if insert i'm sorry if my insert node val bigger equal to current the val and so now we do have a next pointer and my insert node.val and my insert node.val and my insert node.val smaller or equal to current.next.val current.next.val current.next.val okay don't try this at home kids then you set my insert node dot next equals current dot next okay so you're saying we want to place this in between your cur in between our current node and our next node suddenly it's the new node that's going to be pointing to the next node and our current node will be pointing to my insert node so that's all we do we set our current one to point to the one that we want to insert and the insert node pointing to what's our current next node and then we could return um i think we're all set let's see what happens if we run the code error expected and qualified id what's its problem here 50. well current uh line 50 oh while current not equal null what am i doing okay non-void function okay non-void function okay non-void function line 57 oh yeah well we just created a new list so we want to return the new list and we okay looks like it worked here what if we do submit and we have a winner thanks a lot everyone
Insertion Sort List
insertion-sort-list
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. 3. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. **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\] **Constraints:** * The number of nodes in the list is in the range `[1, 5000]`. * `-5000 <= Node.val <= 5000`
null
Linked List,Sorting
Medium
148,850
1,406
all right let's take a look at leak code 1406 stone game three i think this is an incredibly good problem it's a dp problem and i think it's uh it's a golden standard of dp problems to be honest with you know you can start with a naive backtracking approach and then you can create a cache to cache your results and then you can turn it into you know a dp memorization you know still top down and then from the recursive top down you can optimize that even more and turn it into a iterative bottom-up dp so this is just a iterative bottom-up dp so this is just a iterative bottom-up dp so this is just a great full application of dp and yeah i want to walk you through the english algorithm and help you understand how to uh see the recurrence relation and be able to understand the dp aspect i have both the answers to the recursive solution and the iterative solution you can see that later and you can check my github for that as well in the description but um yeah so the problem is as follows so we're given a list of values you know stones and so there's two players alice and bob alice goes first always and then it's bob and then it's alice and they just keep alternating after that so we want to see who is the winner here and so uh so they tell us how the scoring works so at each turn you know alice or bob's turn that player can has three choices they can either take one stone they can take two stones or they can take three stones and the score of that turn is just the sum of the stones that they take right so if they take just one stone they have one point if they take these two stones then they'll have three points if they take all three if they take three stones then they'll have six points right so we want to um at the end we want to see who is going to win and it tells us that both players are going to play optimally so um basically what that means is each players is you know going to try to maximize their possible score at each turn yeah so i guess it's pretty straightforward if all the numbers are positive um because then we can just greedily you know the best choice at each turn is always just to take all three stones you know take as many stones as there are possible right let's just do this first example here and see um how this plays out so alice goes first so you know her best choice is to take all three stones here and she'll get a total score of six and then bob will be left with just this one stone here and he'll take that and get seven so bob wins in that situation what are the other choices that alice has alice could have also just taken one stone and then bob probably would have just taken the rest of them and won by a crushing margin or alice could have started off by taking these two and then bob would probably just end up you know taking these two as well and then winning by a crushing margin so um in all these situations bob is the winner so um but it does tell us that alice and bob play optimally right so out of these three options that alice has she's going to choose the option which um you know benefits her the most right so she's going to we know for a fact that she's going to take three stones and then bob will be left with just the seven so even when alice plays optimally by taking these first three stones she still loses um yeah so let's also let's look at another example with negative so this is a case where we can't just do a greedy approach and take the first three stones um right because let's see what happens if alice takes the first all three stones right if she takes all three stones at once then she'll have negative six and bob will be left with zero bob's score will have not changed bob will be at zero and alice will be at negative six so bob wins let's see how alice can optimize this first turn she can actually just take the first two stones and be left with a negative three score and then bob will also pick up the last stone which is negative three so in this scenario when alice takes just the first two stones then they have a tie let's check the last option if alice takes um the negative one then bob will just take the negative two and then alice will be forced to take the negative three in the last turn so this situation alice loses because alice has negative four and bob has negative two so the optimal turn for alice is to take the two stones right so that's how we end up with the answer of a tie so we can see that greedy won't work because you can't just you know blindly take you know all three stones at every given turn right because there's negative values and it could be worse for you um and yeah so and also you can't necessarily just take the least amount if it's all negatives right because the best option here it looks like it would be negative one but then bob could also just only take one stone and then force alice to take the last stone right so we have to explore every path to the end so that's why dynamic programming is the approach here we can't just greedily you know compare these stones and say oh we're going to take the stone piles that add up to the most the max value that doesn't work because we have to alternate turns and we have to yeah i mean there's too many paths to explore and dynamic programming is the only way to do this so let's uh yeah so okay let me think about where to even start with this so let's first um kind of visualize this as a tree right so basically at any given um at any given turn that player has three choices like i said they can take just the first stone um they can take just the second they can take the first two stones or they can take the first three stones and um the reason you see this minus you know this minus f of 237 what this is expressing is basically the sub problem of 237 so pretty much if alice were to just take the first stone then the way that you would account for what bob is going to take is by subtracting the sub problem at 237 and um yeah okay so let's first kind of define the dp um table and it's just going to be an array it's not a table but let's define what dp of i represents so at each dp index dp of i is going to store the best difference aka alice minus bob and uh the reason we do alice minus bob is because alice always goes first and um yeah it's uh yeah i guess that's the only reason you would store alice versus minus bomb as opposed to the other way around and if you did the other way around i don't there's no way it would work so um yeah and what the i stands for is if the list of stones were to start at that index um so if we started that index uh let's say this is an x3 right so the answer to dp of three um dpf3 is representing the list of stones from three until the end of the list so it would just be seven so dp of two would represent the list of stones from three to the end and then you know yada like dp of one would represent the best answer for um the stone two three and seven okay so let's take a look at um let's take a look at an example here and then i think i'll try to um kind of revisit this recursive tree and show you uh you'll have a better understanding of this tree once i go through this quick example here so um right so like i said dp of 2 is going to represent the best answer if the list of stones was just 7 to the end right and that's just the stone seven so um let's write this out right so what's the best score that alice can get you know the best difference between alice and bob's score if the list of stones was just seven right alice only has one choice in this situation she has to take this one stone right you know her three options at every turn are either take one stone take two stones or take three stones and if there's only one stone then she has to take it so alice has a score of alice has seven and bob has zero um yeah if bob doesn't take anything then his score is just zero so the difference is so the best difference between them is seven and um that's why for this dp at two we're going to write seven here and um yeah so now let's move on to um if the list of stones was six seven so let's see the uh different choices so alice can either take the first stone and then bob takes the seven or alice can take both stones at the same time and then bob has zero so let's write these two options out so alice can take so alice takes six and then bob takes seven so that difference is negative one right because alice has a score of six bob has a score of seven so alice minus bob is negative one let's see the other situation alice takes six plus seven so alice has 16 or 13 and then bob has zero so then the difference is 13 right 13 minus 0 is 13. so at each given turn right we want to play optimally so alice is going to choose the option that gives her the best difference the maximum difference so she's going to choose this second option so she's going to take these two stones at the same time and her difference is 13. so the answer to this sub problem is 13. so dp of 1 is 13. and then let's see if the list of stones was five six seven then how would we express this so alice can take just the first stone so alice has a score of five and then um so then bob is left with six seven right so what is bob's best choice here well we actually just calculated the best you know answer for um if the list of stones was six seven right that was our previous sub problem that we just solved so we already know from the previous sub problem that the best answer the back the max score for a list of six seven is 13 so bob is going to have 13 and so the difference between these two is negative eight so 5 minus 13 is negative 8. so let's look at the other option alice can take 2 stones so 5 plus 6 is 11 so she has 11 and then bob is left with just this 7 so bob is going to take that so then bob has 7 and the difference between them is four right so then let's look at the third option so alice can take all three and if alice takes all three she has 18 and then bob has zero so then the difference is 18. so you can see here that out of these three choices alice is going to choose the best one for her and that's the one which gives her the difference of 18. so she's going to choose that and her answer at gp of 0 is 18. so you can kind of see now going back to this tree why we have to do one minus the sub problem here right because uh um like i said earlier like in this example when alice takes just the five then um the best option for bob is uh you know the best option for the list of just six seven is uh the is stored in the dp that we just calculated before that so yeah so that's what this expression here is basically uh you know it's going to return the answer of the best possible difference if the list of stones is two three seven and then same here if alice takes one and two the first two stones then she has to subtract the best answer at three and seven and the same here if she takes the first three stones that's just to subtract the best answer for the sub problem of just seven and um yeah so you can kind of see how this recursive branching happens um there's three different options at each turn and then we can follow this path down so then um for the sub problem of two three seven the three different options are we can take just the two and then we have to subtract the sub problem of three seven or we can take the first two and then subtract the sub problem of seven and then we can take or we can take the first three stones and then subtract um nothing um yeah so as you can see we're doing a lot of repetitive work here like we have f of 7 here then we have f of 3 7 here so that's why we need to cache our answers and at each recursive call we can just store our answer in a cache and then check later if we've already come across that so basically you know in a dfs you know this call would get hit before um this call here so once we find the answer to this three seven sub problem then later on once we hit it again we can just find it in our cache instead of having to you know do another recursive call and keep going down so yeah that is uh the recursive um structure and uh pretty much the recurrent relation here and um yeah i guess like um it's pretty straightforward if you know there's pretty much like you can kind of categorize the situations into three different situations right if list of stones if there's only one stone then obviously the answer to that sub problem is just that stone's value right like if we just have seven then obviously the best difference is just seven um so then the second situation is if there's two stones actually wait i have all this written out up here so um yeah when there's one stone alice's scourge is just that stone um it doesn't matter whose it is it's just the best score is just that stone so when there's two stones alice's score is either um take both stones or it's stone one minus stone two um right when we had the uh when we had the six seven it was either we take just one and subtract um the seven right like we showed earlier so it's either six minus seven or it's six plus seven um yeah so if there's two stones those are your two options that you have to consider if you have three or more stones then you consider either you know either taking one stone which is just the five and then you minus the sub problem of six seven or you can do five plus six and then subtract the sub problem of um seven or you can take five plus six plus seven and subtract an empty sub problem right so hopefully you can kind of see the recurrence relation now and i hope that explanation is um helping you and then um yeah so i guess a couple of things you might need to note are that when you create the dp you will have to allocate one extra space at the end um and that way you know when you're at an empty um so let's say you have six seven um you're looking at six seven and then you can either okay forget that i don't know how to explain that but just know that you'll have to allocate one extra spot for the dp i can't really think of how to explain that on the spot now but um yeah play around with that play around the dp um let me think is there anything i'm missing this is a pretty heavy problem and yeah so at the end you will have to actually right so dp of zero is going to store our best answer you know the best difference if the list of stones started at index zero which it does right so then if our dp if our gp of zero is greater than zero then that means alice minus bob was you know a positive number so that means alice had more points than bob if dp of zero is less than zero then that means you know bob won if dp of zero is equal to zero then it's a time so yeah hopefully uh hopefully you can understand that um yeah i think i did as best i can as best i could to explain that hopefully you guys understood that hope you guys learned something from that all right um i guess um yeah so also the with dp the uh the um run time will be o n you'll just be looking at uh each number once i believe i mean it's just a single for loop and then you're reference referencing your gp table each time um yeah so of n runtime and space also of n because you just have a dp allocated yeah that was a that wasn't a half decent explanation hopefully it was good please give me some feedback i really appreciate all feedback um yeah all right thanks for watching
Stone Game III
subtract-the-product-and-sum-of-digits-of-an-integer
Alice and Bob continue their games with piles of stones. There are several stones **arranged in a row**, and each stone has an associated value which is an integer given in the array `stoneValue`. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take `1`, `2`, or `3` stones from the **first** remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is `0` initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob **play optimally**. Return `"Alice "` _if Alice will win,_ `"Bob "` _if Bob will win, or_ `"Tie "` _if they will end the game with the same score_. **Example 1:** **Input:** values = \[1,2,3,7\] **Output:** "Bob " **Explanation:** Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. **Example 2:** **Input:** values = \[1,2,3,-9\] **Output:** "Alice " **Explanation:** Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. **Example 3:** **Input:** values = \[1,2,3,6\] **Output:** "Tie " **Explanation:** Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. **Constraints:** * `1 <= stoneValue.length <= 5 * 104` * `-1000 <= stoneValue[i] <= 1000`
How to compute all digits of the number ? Use modulus operator (%) to compute the last digit. Generalise modulus operator idea to compute all digits.
Math
Easy
null
653
hey everybody this is larry this is day 23 of the august leco daily challenge hit the like button to subscribe and join me on discord how was your weekend let me know how everything went and come join me on discord chat about it anyway today's problem is two sum four input is a binary search tree given the root of a binary search tree and a target k returns true if there exists two elements in a binary search tree such that the sum is equal to the given target um okay and i was just checking to see if there any fun constraints because you know uh just because um this is a little bit awkward um because there's a couple of ways you can do it you can basically what you ideally what you want to do is implement like two pointers and then kind of slowly merge toward the middle to see kind of thing um yeah and then you can do that in a linear time um and you can and depend on how ambit uh how um yeah it depends on how you want to do it you can definitely do it that way um but because i think i mean i know that there are other ways to do it as well for example you could traverse the tree and then put everything in the hash table or something like that right but that really i feel like that doesn't um i feel like that isn't in the spirit of things but you know uh and me using python maybe the most popular way is to use two iterators to be uh to kind of keep it kind of cool but and you can kind of do two that first search with um with two stacks instead to kind of pop one another but a lot of that is just so contrived and so like weird and so tough i don't know if i'm gonna go around and do that today uh it is sunday or monday so i'm a little bit tired it's not a weekend anymore for me to kind of do that kind of involved but i would recommend maybe i think for up solving what i would recommend you do especially if you're not using python um just implementing two stacks and then implement that first search that way um and then kind of just you know migrate toward the middle uh to get the target uh but yeah because the reason why you can do that it is a binary search tree so you know where to search for the other one but and if you do it like in a smart way you can do a linear time if you do it in a more naive way of doing a depth research and then search for the other number in a tree that's going to be n log um yeah so it's kind of weird in that way i'm gonna do it the lazy way today to be frank i'm sorry to disappoint viewers i'm usually starting this live i'm a little bit slow but today i'm just a little bit tired and uh maybe that's my excuse but definitely what i would recommend is try to do it uh with two different searches uh in a very kind of tricky kind of way but yeah um okay so let yeah i'm just gonna do or i'm just gonna do one definite search to an away and then do it to someone in a way i know that this is a binary search tree and doesn't take advantage of that but it does have over end complexity so that's my story i'm sticking to it uh cool uh let's do that then uh was it inorder no the other one in order now i know this right yeah why did that so this is just typical in order i set up an array here and then we can do this i mean i'm just gonna run it real quick four one three yeah and then now of course when you do it in order everything is going to be in order but yeah and now okay so then now you have a pointer to the left pointer to the right and then you just do the two sum that way um yeah you could do two pointers back and forth or you could do a hash table it doesn't really matter i think i'm well you know what i'm feeling a little bit lazy so i am gonna go lazy the entire way and yeah just use another hash table so maybe i'm doing a very competitive programming way where i just ignore all the parameters and do it but for an interview i would definitely at least talk about these things uh and do it wherever you can but yeah this is already sorted by i'm a little bit lazy if k minus x and c return true oops uh i mean this should be good but i do feel like i'm cheating today maybe i am cheating today i maybe i need a day off mentally a little bit i mean i think this is my like 500 and something day streak so i'm a little bit tired today i think i just didn't sleep well to be honest i have a lot of excuses but yeah so i think that's all i have i think i talked about it already uh this is linear time linear space so it is optimal-ish so it is optimal-ish so it is optimal-ish um like i said you can i don't i think you could reduce this of h space where h is the height of the tree so that would be more optimal but this is roughly optimal so that's um you know yeah that's all i have for this one sorry to keep it short quick i hope y'all have a great day have a great week i will see you later i'm gonna try to get some sleep bye
Two Sum IV - Input is a BST
two-sum-iv-input-is-a-bst
Given the `root` of a binary search tree and an integer `k`, return `true` _if there exist two elements in the BST such that their sum is equal to_ `k`, _or_ `false` _otherwise_. **Example 1:** **Input:** root = \[5,3,6,2,4,null,7\], k = 9 **Output:** true **Example 2:** **Input:** root = \[5,3,6,2,4,null,7\], k = 28 **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-104 <= Node.val <= 104` * `root` is guaranteed to be a **valid** binary search tree. * `-105 <= k <= 105`
null
Hash Table,Two Pointers,Tree,Depth-First Search,Breadth-First Search,Binary Search Tree,Binary Tree
Easy
1,167,170,1150
1,979
hello friends so today in this video we'll go through the first two problems from the latest lead code weekly contest to 55 so let's start the first problem is not too difficult it states that you're given and you have to find out the greatest common divisor of an array so the problem is asking you that you are given an array nums okay and you have to find out the gcd of the smallest number and the largest number in that edit so you just have to what you can do that you have to first find out the smallest number and the largest number in that area and just find out the gcd using c plus s2 so that's what i've done here uh first find out the maximum number and the minimum number using these functions and then just do a gcd of the maximum and minimum number so it's not too difficult it's just a very simple problem the next problem is find unique binary strings it states that you are given an array of strings nums and it contain n unique binary strings of length n so all the strings are of length n and they are binary strings now return a binary string of length n as well that does not appears in that numbers area okay then there can be multiple answers then you have to return the answer uh any of them now what you can see here is that there are two strings this zero one and one zero and you have to again find out a binary string which is not here but it is also of length two now what you can simply see here is that n length is only 16 so if you just do 2 to the power 16 because how many total number of binary strings are there so if you just find out that 2 to the power 16 is around 65 000 and it can be easily done in a brute force way also so what you can simply do here is just try to generate all the possible strings of length n and then just check that whether that particular string s is in this particular area or not so before that what you can do here is uh you just store all these strings in some set because then to find out any string it becomes easier it will become o of log n instead of log n like log n instead of n and then what you can simply do here is just try to form all the binary strings of length n now how you can do that they can have multiple ways uh you can but the simplest way is like using some sort of dfs sort of thing so in which means that i have an empty string and maybe i want a string of length two in which binary strings of length two because it's empty now so i have two option i can fill the first position with zero and the first position with one so it's like a string with only zero and i want that the total end should be two it's like a function call and the string is of length one only or like the string is having only one character one and we want actually the length two then we again call this and it will become like zero one and one zero here actually for every string till that string becomes equal to n the length of that you keep on iterating or like keep on adding 0 1 and calling that function again forming like a binary tree just like 1 0 and 1 now as you can see here is that the string length has become equal to 2 okay now at this point what you will see you will just match that whether this particular string is in that set or not if it is not just stored that particular answer and you just return on that answer so that's the logic for this problem as well i'll show the code part now so the code is yeah here so we'll first insert all the particular nums actually all the strings into some set this is some global set and then what we'll do we'll iterate over and find out the length of one of the strings which is n then do a dfs call with an empty string and total length of the string finally should be n and return out the answer which is a global uh string also in this gfs call we'll stop when our actual my call or my total string becomes length n at that case what we'll do here is we'll check that whether that string is not in the set and also that whether that string is not empty what we'll do here is we'll check that whether that global string should not be empty if it is already holding some string why to insert one more string i just want one answer because they can be multiple answers i just want one answer so the string which is answer variable if that is empty and also that particular string which we have found out is actually not in the set just make your answer equal to that particular string of length n and return out else call that dfs function again adding 0 and adding 1 and that's the logic for this problem uh it's just a recursive problem uh brute force requires a problem i hope you understand the logic and the good part for this problem if you still have any doubts you can mention now i will say this one and they keep coding and bye
Find Greatest Common Divisor of Array
maximum-number-of-people-that-can-be-caught-in-tag
Given an integer array `nums`, return _the **greatest common divisor** of the smallest number and largest number in_ `nums`. The **greatest common divisor** of two numbers is the largest positive integer that evenly divides both numbers. **Example 1:** **Input:** nums = \[2,5,6,9,10\] **Output:** 2 **Explanation:** The smallest number in nums is 2. The largest number in nums is 10. The greatest common divisor of 2 and 10 is 2. **Example 2:** **Input:** nums = \[7,5,6,8,3\] **Output:** 1 **Explanation:** The smallest number in nums is 3. The largest number in nums is 8. The greatest common divisor of 3 and 8 is 1. **Example 3:** **Input:** nums = \[3,3\] **Output:** 3 **Explanation:** The smallest number in nums is 3. The largest number in nums is 3. The greatest common divisor of 3 and 3 is 3. **Constraints:** * `2 <= nums.length <= 1000` * `1 <= nums[i] <= 1000`
Try to use as much of the range of a person who is "it" as possible. Find the leftmost person who is "it" that has not caught anyone yet, and the leftmost person who is not "it" that has not been caught yet. If the person who is not "it" can be caught, pair them together and repeat the process. If the person who is not "it" cannot be caught, and the person who is not "it" is on the left of the person who is "it", find the next leftmost person who is not "it". If the person who is not "it" cannot be caught, and the person who is "it" is on the left of the person who is not "it", find the next leftmost person who is "it".
Array,Greedy
Medium
2191
1,872
hey everybody this is larry this is me going over q4 of the uh weekly contest 242 stone game eight so hit the like button hit the subscribe button join me on discord let me know what you think about this problem so this one i actually spent way too long on the greedy solution and the greedy was that i always just take the maximum score and the prefix sum um and that was just wrong so it doesn't you know you don't have to worry about that one uh or what that means but you should note um the prefix sum for this one and there's a really weird uh this is the first observation you need to make about this problem which is that and don't look at solution to oops don't peek at the solution quite yet i'm just using this as scratch pad but the idea is that okay you know let's say i make a move and i make take the first four numbers right and in this case four numbers is going to be 7 5 10 and negative 6 which is what 16 say so let's say you know going up to here the numbers are 16 right the sum as a 16 and then the next time the um and then now you put 16 in the list instead and then the next person when they go um they will get to put in you know 16 so their new list is this right but and they have to take at least two numbers and so forth so for example they could take these three numbers and now they have you know 16 plus 5 minus 2 which is 19 uh and negative 6 right but so the key observation here is using prefix sum because you notice that the sum of these three numbers is just the sum of the first seven numbers right so that's the key observation for me on this one um and it took me a little bit of mental thinking to prove myself that this is right you know if you're good in these kind of um manipulations then this is actually relatively straightforward but i'm not so it took a while um but yeah so now that you have this now you know how you can use prefix sum which is um you know i'm not gonna go over prefix some uh properties that detail in this one because there's a lot of problems on it but you know this is how i did the prefix sum i just calculated the what it does is that um the index of um yeah the index i is equal to the sum of the numbers from zero to i minus one or something like that maybe it's off by one but you get the idea and i actually had an off buy one during this contest so that was probably why but yeah um so then now we construct um a dynamic programming solution where i do it top down and here i name it terribly go but it's just okay what is the maximum score which is the delta uh starting on this index and that's basically how you would solve this problem um and okay and i'm going to kick it off by you know the first person atlas has to always take the first two piles um and then on the third pile she has a decision right um and this is kind of um like instead of writing a for if you do it naively you may say okay i'll try taking two stones i tried taking three stones and so forth but that's going to run in n squared and n in this case is 10 to the uh fifth and 10 to the 10 is really big so we try to do this in linear time and instead you do this thing where you cache the loops and the idea is that okay you know um let's say you already took the first two stones right and then what happens what are your decisions your decision here is now either to take the dirt stone and then keep going and then maybe keep going or let the opponent take uh you know you end your turn here and let your opponent take starting from index and in this case what happens right well your score is now your current score minus your opponent score and your opponent score is just gonna be you know this recursive thing plus the entire prefix because this is basically um this is basically you know taking all the numbers including this one and the next one right um yeah so basically this is taking the prefix which is um because this is basically like i know i said the same thing a couple times sorry i'm trying to figure out a cool way to say this but this is the pile that you created by ending at index so that's basically what this represent and this is what you're forcing your opponent to take right and then now they have a you know recursive decision to make in the future whether they take you know this is at least two piles um so this is you know your combined pile and one more pile at least and then they could take either two piles or three piles by doing this or they n or you know more powers and so forth so that's basically the idea behind this one um it's i know that i say very you know that's the thing with these dynamic programming problems uh and i use lru cash to cache this um because for every uh for every same index you get the same answer um and in this case this is just a decorator in python that'll let us uh cache the input and the output for that answer so that we see the same input it'll give the same output um but yeah so this code is like you know 10 lines of code or this particular chunk with comments or whatever and spaces um so it looks easy and my explanation maybe depending how you want to go about it like it could be easy or not but it's a really hard problem i spent about half an hour on this i spend a lot of time debugging and getting uh the wrong index and also just uh what's my card also just like messing up uh with a greedy solution but it's really hard so take your time to really understand it and really draw it out um i think the this part is okay i think the hard part is this part and really draw out what it means to take to end taking a pile and try to figure that out um because this is just combining two piles and then forcing the opponent to take um that those piles plus one more pile and then they get that decision right so because the actual decision is whether you keep on going piles or you stop going to powers and then pass the turn um cool that's all i have for this problem uh you could watch me stop it live in the contest and kind of see where i kind of struggle and yeah um cool see ya dumb i'm dumb today okay let's see catching up hmm hell am i doing this might take the entire time probably wow people solved this very quickly so i gotta do it i mean huh this one was just a silly problem though do i also took a long time to cute way i don't know why okay oh x has to be greater than one that's where problem 10 to the fifth so you can't really iterate testing it except for that this has always been prefix sum so you can do the math on that but what i mean is that your sum is also going to be some of the thing so the delta is a little bit so the doubter is going to be one of the numbers on the list they don't tell you that but is it i mean not necessarily one of the numbers on this but something like as a function it's going to be some prefix chunk maybe yikes let's start to prefix some i guess okay so greedy took the most and then what happens let's say this force all positive numbers what happens then you just take all the numbers let's say there's a negative number at the end you stick them with it or if there's a positive number in the end let's see well it was something like 12 negative 105 then and you know what whatever then we take this thing and then so please say you took the biggest number the prefix so your turn will always start with the big swing okay so greatly you always take the biggest number in the prefix array so you just have to keep on going from the right okay so that's a youtube query some good greedy so you take the biggest number into the thing and then there's just a heap done right let's try it out so we want the biggest number let's just use this again what happens if we have thai burger do we want more numbers or that is a tricky one and that depends on the parody of it doesn't it positive if they're all zeros what do you take all of them to go can't be convinced that's the right answer now you take all of it because the invariant is that if otherwise the next person would just take the or the same value and your delta is zero where if it's because of the monotonic uh yeah you could do this with monotonic arrays but i don't want to so okay so then in that case we want to sort it by the max index okay that's fine um okay so okay maybe that doesn't matter maybe i'll fix it hmm until you take the largest value we should use the heap actually hmm fine no just keep it cheap with don't keep it simple if i is less do you need to take at least two so we've come plus two is huh what i don't even know what i'm thinking about anymore let's just do this problem just ahead and i'm blanking it sort of continuous okay fine just see if it terminates that's fine oh yeah okay that's good too okay continue otherwise is equal to i and then oh delta time times value something like that what is that down yeah it's gonna be messy but and for the first one you what that's to two and that's why that puts a little bit off so the last person has to take no i mean that's it then right so i took let's see i mean it's just really well but so zero and one so club currently start at zero so you want to go at least one so one is fine maybe i don't know that's right i mean it's better but i don't know if it's right so for number two how did i get 15 taking so this one takes 221 which see what because they're not greedy oh i see no that's not um is that really the best is just one 16 i don't get it though isn't that optimal if um alice and i take is this one right because that's 21 and then so that's two oh no maybe not it's 21 and then 19. now this is right oh then oh i see because then bob would actually take all of it and get 13 points so then the delta is actually 6. okay so my greedy isn't right hmm agree isn't right which is good that we resolve it here but then how do you do it how do you do that is an n square you hmm is it just tp maybe it's just tp and i made it too hard but then it's also like a really messy dp that so basically so it's my turn i if it's my turn i might have to change this to bottoms up but okay if it's my turn then i either keep taking one more number so my score is oh there you go test number plus because that's just me taking this stone or oh we go from to now we end our turn here so our score is set and then the prefix of index so this is the score for the opponent so we subtract this it's a little bit off i think but let's see you have to take at least one number oh yeah so so that's just wrong in general that's the score that's the scored opponent what's my score to get the delta i'm not doing the delta right i'm just getting the score well the contribution would be to so this is the delta maybe not i'm just being silly so it can't so we take and we add to the delta otherwise we minus i just have the science one nope the opponent takes it hmm this entire prefix now okay i think we're good here except for this why is it where do you even get 12 so we have to take at least one number so that hmm okay if so this is at least two so this should be good maybe but not worry about performance okay go so just try something like it's slow but not that it seems okay with respect to the time so okay let's just give it a try okay oh this is hard hey uh yeah thanks for watching hit the like button hit the subscribe button join me in discord let me know how you did on this contest i did okay but uh yeah and also on this problem what do you feel about resolution um yeah uh you know stay good stay healthy to good mental health and i will see you later bye
Stone Game VIII
can-you-eat-your-favorite-candy-on-your-favorite-day
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of the **removed** stones' values to the player's score. 3. Place a **new stone**, whose value is equal to that sum, on the left side of the row. The game stops when **only** **one** stone is left in the row. The **score difference** between Alice and Bob is `(Alice's score - Bob's score)`. Alice's goal is to **maximize** the score difference, and Bob's goal is the **minimize** the score difference. Given an integer array `stones` of length `n` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **score difference** between Alice and Bob if they both play **optimally**._ **Example 1:** **Input:** stones = \[-1,2,-3,4,-5\] **Output:** 5 **Explanation:** - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of value 2 on the left. stones = \[2,-5\]. - Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on the left. stones = \[-3\]. The difference between their scores is 2 - (-3) = 5. **Example 2:** **Input:** stones = \[7,-6,5,10,5,-2,-6\] **Output:** 13 **Explanation:** - Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a stone of value 13 on the left. stones = \[13\]. The difference between their scores is 13 - 0 = 13. **Example 3:** **Input:** stones = \[-10,-12\] **Output:** -22 **Explanation:** - Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her score and places a stone of value -22 on the left. stones = \[-22\]. The difference between their scores is (-22) - 0 = -22. **Constraints:** * `n == stones.length` * `2 <= n <= 105` * `-104 <= stones[i] <= 104`
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a smaller type plus the number of your favorite candy minus 1. The earliest possible day that you can eat your favorite candy is the total number of candies with a smaller type divided by dailyCap.
Array,Prefix Sum
Medium
null
491
welcome to algo simplified let's solve today's lead code challenge that is non-decreasing subsequences non-decreasing subsequences non-decreasing subsequences let's start with the problem statement in this problem we are given an array of nums return all different possible known decreasing subsequences of the given array with at least two elements so in this problem we are given an integer array nums and we have to return all the possible non decreasing subsequences that have at least two elements basically this is asking us to return all the possible subsequences with at least two elements and all the subsequences are in non-decreasing order subsequences are in non-decreasing order subsequences are in non-decreasing order it means we just need to find the subsequences it's a backtracking problem you can say it's kind of a DFS like we choose this four then we can choose any of the number which is either equal or greater than this number and then if we choose that number then we can choose like if we let me just explain you this problem we have an array like this and now we are supposed to choose like make a subsequence so if we choose this element at index I okay like index 0. then we can choose any other number from this index I equal to 1 to I equal to n minus 1. we are free to choose and then from up from 1 to n minus 1 after we choose a number then again we are free to choose a number and while we are choosing the moment we reach and choose a number or we can say that like if it's 1 5 2 1 8 1 3 1 let's see now we are choosing this one okay and we just okay after choosing from out of all these numbers we see we will choose next will be 2 like from I equal to 1 to n minus 1 we choose two so before choosing to we can put consider this as a subsequence like yeah this is also a subsequence of this array now after coming at 2 what we can do we will just choose these two and we can say okay this is also a subsequence now at 2 now we have to move ahead as we have made the subsequences with these numbers till here now we will move ahead and we will choose another number let's say it's three so we'll choose three and now one two three will be a subsequence after three we don't have any element so we will just return so in this way like we will be using we will be iterating through the like index icon index I to n minus 1 and we will choose a number after that choosing that number we will put this in a sub in our array result array and we will move ahead like if we have chosen a number at index I then we will again choose from index I plus 1 to n minus 1. so to get all the possible subsequences we have to choose every number that's simple like just to get a single subsequence like I just wanted to get one two three or any random subsequence then I could have chosen but in this way but we have to deal with all the subsequences so we will basically generate all the subsequences between these numbers and since we are generating all the possible subsequences the time complexity of the solution will be big of 2 raised to the power n where n is the size of the array why because in subsequence either we will be choosing one or we will not be choosing one for every subsequence if we choose one okay otherwise we don't choose this one and move ahead for all these numbers so we are not choosing this one then moving ahead if maybe we choose 5 or we don't choose 5 oh we choose any other number so there are two possibility of choosing five that is either choose 5 or either neglect five so in this way the number of subsequence is made will be 2 raised to the power n and similarly the space complexity we will be storing all the subsequences in a array of array so we will be requiring a space of Big O 2 raised to the power n okay and let's code it up like this is a simple backtracking problem so first I will generate all the subsequences let's take a vector it will store a particular subsequence and this will store the result now we will just go through it like this call a function and deal everything in the function and return the result now everything is on this function now as we want to generate all the subsequences what we will do we will iterate from this index till the last index end we will put this subsequent we will put this number into the subsequence and then again like either we will choose this number or not choose not to choose this number so like when we come at index I equal to IND so we will choose this particular number and otherwise if we don't choose it means like we have moved to index I equal to I and D plus 1 like as we are iterating this for Loop so basically we are choosing that number instead of this number for the very first element of the subsequence for that particular subsequence and now we are again calling that function now we are calling this function for like since we have chosen this I index so we can call this function for the next element that is I plus 1 so that we can choose from the I plus 1 element to the last element of the array and now since we will be iterating through this for Loop so if I we are at particular index I then if we move ahead to index I plus 1 then we can't keep this nums I in that subsequence so we have to pop that one like we have to pop it out from the array like this and since whenever we call this function we will move ahead so like we have taken 4 and we move ahead to consider all the remaining numbers so we can say that this 4 is also a subsequence so when whenever we call and whenever we check for the next possible numbers to be considered for the subsequence we will put this thing into our result and if we reach at the end element so this for Loop will won't be working since I should be less than the size of the array so we don't need to add any condition so this code is basically to generate all the possible subsequences and if I just run the test cases you will find that we have generated all the possible subsequences like you can see here even empty set single element all the elements are here so this is the code to generate all the possible subsequences but now we have just two condition the first one is that it should be non-decreasing and the it should be non-decreasing and the it should be non-decreasing and the second one is that at least two elements should be there so for at least two element we can just put a condition over here like if the sub dot size is greater than one if the size is greater than one only then we will put this in our result and for the second condition uh it's saying that at least and it should be non-decreasing least and it should be non-decreasing least and it should be non-decreasing means the previous element should not be greater than means non decreasing it should be non-decreasing so if we find a condition where this sub Dot like this thing is not empty and the last element is greater than the particle of this element then we will continue we won't go in and add this number to our subsequence because it's smaller than the previous number which is basically not going according to the condition if we just don't add this condition then it would be decreasing array it's decreasing subsequence so now basically we have deal with everything we have deal with the condition known decreasing subsequence and the size should be greater than 2 but now the you can also see that in this what will happen is we are generating all the possible subsequences so you can see in this example like Force four six seven now you can see that we they are considering like all the subsequences is unique like they are not considering four seven and four seven as different subsequences like this particular seven that is let this 7 be 0 and the 7v1 so if this is z this one this is different seven then these two will be considered as the same subsequence but in our code what we are doing we are considering four and then we consider 7. out of all these we consider all the numbers so we are considering six then four six okay then we are considering four seven and then we are again considering four seven that's why we can if there are like the number of sevens are four then we are the count of four seven will be four so we are having duplicate subsequences in our result in order to avoid that since we are at this particular element at this particular index now we are going to call the function for all for the rest of the elements like we are at this particular element and now we are iterating through the rest of the elements which are ahead of this element now while iterating if we just encounter 7. and we just if we just encounter 7f and if it's just greater than 4 or equal to 4 then we will add it in a set so that if we again encounter 7 while I trading 4 in that for Loop then we won't call this the DFS function and won't insert the subsequence into our result so this is the one thing we are going to do we will add one more condition here like if we find this number in the set then we will continue we want and we will put this number into the set let's create a set I haven't defined it yet so now in this way what we are doing like we have four and six or I mean we have a 4 then for this particular 4 we are going to iterate from I equal to 1 2 till the last element like 1 2 3 so 1 2 till 3 so 1 2 3 will be called so if we get go to one then we will put this 6 into our set and then we will call this function and we will put we have just put the six into our set now we come at seven we will see okay 7 is not present we will insert the 7 into the subsequence and then call it for further adding the subsequences and then we will add that 7 into our set then we again come at 7 so we have a subsequence 4 comma 7 as we have 4 comma 7 as a subsequence till now but when we again come at 7 we see oh it's already present in the set so we won't just go into the these core the these line of codes and we will just continue and move ahead so in this way we will save from save us from getting duplicate subsequences let us run the code it's accepted so basically it's accepted yeah so this was the code thanks for watching I'll go simplified do like share comment and I hope you enjoyed the video thank you
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
354
hello everyone welcome to another episode of coding decoded my name is ancha rodeja i'm working as technical architect sd4 at adobe and here i present russian doll envelopes problem and apologies i couldn't solve it in the morning and provide you with the solution as i was quite occupied with my professional commitments i just got some buffer time and now let's shoot for solving this question or to your surprise we have already solved this question in the month of march 2021 this problem is based on the concept of longest increasing subsequence problems can be solved using two approaches one in time complexity of order of n square one in time complexity of order n log n using patient sort for all those who are not aware of these two techniques don't worry we already have another tutorial wherein i have explained both these approaches in detail and in the past solution of russian dolls i talked about order of n square approach which is no more accepted on lead code so if you go and check this code up you will see that out of 87 test cases only 85 pass so let me just comment that up and show it to you guys and then we will go on improving it using the patient sort approach so let's submit this up and it will fail with the error of time limit exceeded if you go and check the details then 85 test case passed out of 87 and if you go and check this video uh it here the solution passed an year back they added two more test cases in order to make sure that all the solutions are of time complexity order of n log n now comes the question how can you actually solve this up first and the foremost thing is to check out the longest increasing subsequence video where i have explained and taught patient sort once you get good hold of the concept of patient sort then move back to the rusty and all envelopes problem because most of the test cases are still getting solved by this approach and it's very important how long is increasing subsequence algorithm is getting applied over here once these two things are done now come back to this solution where we will try to improvise it in time complexity of order of n log n so a few things remain the same the first and the foremost thing is that we are sorting the envelopes on the basis of width then followed by height so width in increasing order and then height in decreasing order so remember this point this is very important uh why we are doing this i'll talk about it later in the solution so here i've created a db array and this dpra will actually store the maximum height seen so far we have initialized this dpra with maximum value of integer and by default dp of zero is initialized to zero so let's consider the case where the first envelope comes is of height seven so what we will do we'll apply binary search over a dp array where in all the elements so far are maximum and we are basically keeping track of the maximum height of envelopes that we have seen so far so the first one comes our seven what do we apply binary search algorithm and look out for the appropriate position for seven what is the appropriate position for seven it comes out as zero so we go ahead and add seven at the zeroth index so it gets added so how many envelopes have we added so far we have added only one envelope so the answer becomes one now consider two cases in the first one three comes and in the second one eight comes so let's assume that we treat the second envelope as three and what do we check what is the appropriate position for this three so we get again zero so in this case it will be replaced the zeroth index will be replaced by three we will simply go ahead and replace this seven by three and the answer still remains one so this is exactly same what i taught in the patient sort algorithm if you have not gone through it you will not be able to get it otherwise in case in the second case if we get an eight so we'll look out for the upper update position for eight it will come as the first index and the envelope width dpra will get updated to seven comma eight and the rest of them will set remain as maximum so far how many envelopes have we added we have added two envelopes and the answer becomes two let's treat another case where from seven comma eight we get the next height of the envelope that we get is of one unit so what do we check it's after great position the appropriate composition comes at the zeroth index so in case one comes up uh the envelopes will be updated in the dp array as one comma eight this is exactly same as i taught in the patient sort so guys i urge you guys to go through it first and uh the dpr is updated to this however the total number of envelopes added still remains the same that is true so the answer still remains two in the other case let's assume 10 came instead of one so what is the appropriate position for 10 it is the second index therefore the dpra gets updated to 7 comma 8 comma 10 and the rest of the fields remains the same the answer gets updated to 3 because here we have added three envelopes so far and this is what has been done over here using the binary search technique so here we iterate over the envelopes array and remember the envelopes are already sorted in increasing width so we are not concerned about the weights of the envelopes but the area of concern is only height and in order to provide unnecessary manipulation we have sorted them in decreasing order of height whenever there is a conflict so that the one with the higher height and same width gets precedence uh so what do we search for the appropriate position for the current envelopes height in the dpra we when we get its index we update dp of that particular index to the height of that envelope and we keep track of the length variable as we are progressing in the dpra so this is pretty much it and this corner case that they have written is because when the binaries in while searching in the binary search that element is not present so if you go and check the documentation for binary search you will see that whenever the element is not present it returns the insertion point -1 -1 -1 so this method returns the index of the search key if it is contained in the array else it returns insertion point -1 array else it returns insertion point -1 array else it returns insertion point -1 so in order to counter this up we have added negative signs over here so that's pretty much it in the end we simply return the length that we have computed so far the time complexity as i initially told is order of n log n same as that of the patient sort with this let's wrap up today's session and i hope you got some idea on how to apply patients or patient sort on to a russian doll envelope problem thank you
Russian Doll Envelopes
russian-doll-envelopes
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_. **Note:** You cannot rotate an envelope. **Example 1:** **Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\] **Output:** 3 **Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]). **Example 2:** **Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\] **Output:** 1 **Constraints:** * `1 <= envelopes.length <= 105` * `envelopes[i].length == 2` * `1 <= wi, hi <= 105`
null
Array,Binary Search,Dynamic Programming,Sorting
Hard
300,2123
1,658
Hello everyone welcome to my channel codestoryWithMIK are going to do the medium mark but will keep the explanation quite easy and simple but there is a lot to learn and this approach is very similar we have done the previous message questions ok liquid number 1658 medium mark Have minimum operations you reduce These are the last elements you have picked up like mother let's take what is one comma 1 comma four comma you comma three, right ? If I did three then it became two, then what is the child now? Is this a child? There is one in the left most, there is you in the right most, so in this we have picked up you. Okay, how many elements have we picked up, only two elements, so our operation is two. This is our minimum answer. Okay, if we take this minimum, this is the minimum. You will not be able to get a smaller answer than this. Look, pay attention here, if you had picked this, you would have picked 3 from here, then from here and one from here, then in three times you would have got it. Five comes but here A came in only two times. Okay, so you have to do the electrical thing. Is it left most or right mass elements? Okay, so the first question is, do you know what came in my mother, the tech and note tech approach? That brother, will I take this Salman this time or will I not take it like mother takes here you can take any one of these two, once you thought that people, you explored it further and then you thought that no, this too. You can take it, okay, so this is what I thought, first of all, it is okay, but I will show you the example of its recognition code. If you go to the link of getup, you will find it in the description, I have written the recognition code, that arrow will definitely give it. I did not memorize it because even if you memorize it, Ali will still give it. This is the problem. Someone else is looking for a better approach, but first let me tell you this. Okay, so you take it like mother, till now you have the option, you either come. Either okay so if you took i okay then what are you left with 1423 yes here is what is here and how many elements of yours have you taken you have taken the value of count one okay and subtract two from x 5 - 1 4 It will happen that if you had taken the number three then the value of the count would be one, that means you have raised your 1st element, this time the value of If I took two on Ratna, then two, I two became zero, so as soon as it became zero, see what is the value of your count, then the value of your count is two, right, so I will keep a variable named Minimum Account, starting infinity was kept in it. Now I have updated the value of the account, it is okay, maybe from here, if I exceed this, the value of the count would be different, then as soon as I get the count, it is a relief, I keep updating the minimum when I get it, okay? This would have been a very simple code of Rickson, now I did it and I also tried to memorize it but it is giving time limit seat but you definitely try, it is okay Rickson, we have learned so much and what do you have to do in a simple way. Look , it's okay to see I lake once, then you will send the name, whom will you mine in What can happen is that you have taken the Jeth element, if Jai is taken then you will remove the name of all from Because you have taken one element, it is okay then it is okay to call Krishna twice and what is put in the above base, in the calculation, brother, as soon as my I will try to update Minimum Quantity = Minimum of Minimum which is the already value and the value of the account which has come now when The gate is in the link, it is given in the description, the link is given in the description, sorry, the link is given in the description of this video, go and watch it from there, I have written plus in both, it is okay, so friend, I am giving it, so what is better now. The approach is searching for one, we try to see it. Okay, so look, to understand the butter approach, I will take this example. Okay, on this example, we will Will come and before that, some things should be compromised so that your engine can be built. Okay, like, let's take our mother, this was ours, right, this was ours, we should take our mother, we might have picked up some elements from the left, okay, this might have picked up some of our elements from the left and You must have picked up some of your elements from the right, okay, this is what you have to do, the number of your elements picked up from the left and right should be minimum, meaning you have to pick at least elements from the left and right and you have to bring all of them equal to X. Okay , at least you have to pick up elements from the left and right and you have to bring it equal to There are elements, its sum is on the right, so both of them should be equal, so now because of mother, whatever elements you picked up on the left, whatever elements you picked up on the right, have sum on the right, so just now I had written left. Plus Right Bill B will be equal, you will be You will have to hit whether it is left or right or left right. Now the elements that you will pick should be minimum number of filaments so that in minimum operations you get I am looking for the longest sum, what happened that you are right, the relation is equal to this, then the children who are hiss in the left boundary and Rawat are in the right boundary, what will be their sum? Look, pay attention , take the sum of the elements which are in the left boundary. Left is right. Let's take the sum of the elements in the boundary. Right is okay plus this is the sum of the middle part. If you understand how much is the middle part then I have said that I have taken the value of all the accesses and taken the sum of all these. So it will not be equal to even, meaning the sum of this whole is fine, till now it is clear, now solve it, even sum will be canceled, D is the minimum element, this is what I am saying, don't make it as big as you can, but everything. I have sex, its value should be as big as possible, all I sex should be even value, but the bigger it is, the less space will be left on the right side, less space will be left on the left side, less elements will be left, what will be the minimum number of operations in A? The value of _ Okay , now I didn't have to pay attention to these two, DK, I tried to solve it, he gave it because there are two things each, don't you, pay attention to this too, Dog, sometimes you will choose the left, sometimes you will choose the right, okay So it is obvious that if you have the option, then you will have to go to the DP's side review, you will have to write, sometimes take this, then you will pay attention to reading two things. I am paying attention to one thing, brother, whatever is in between. If the sum of the elements you are picking on the left side and the right side is Its variety should be equal, that is, the longest should be equal to the longest. This means that we take its length, how much I took out L, whose total number of elements was what were the elements on the left and the elements on the right. Okay, so N minus L will be my answer. Then okay, you understand why I am saying this because the length of the longest one in the middle is L, the total number of elements is L, okay if the length is L, then how many children are there N - L and where will those elements be. Here and here there are children, that's what we have to find out, not how many elements we can pick, the minimum whose value should be equal to We have done such a question on easy map and by doing it, they will also understand it by instinct, I will not tell it directly, it is okay but it should be understood because it was necessary how I reached here, now let us solve it. Then let's find out the sum, see how much is 3 2 5 6 7 8 9 10 3 13 1 14. Okay, we have taken out everything, the total is 14 and we have given the value of x. Okay, so what will be the value of sum minus target and store it I am late to that , how much will be submins D Longest Sabri Having Value This is also a separate question, so this is the special thing about this question, see another separate question embedded in it, this one is a separate question in itself, so not this question but the video. Maybe I might not have made it but you will learn this question and this question has also been asked separately many times. It is okay that it is the longest. Look, its proposal is very simple. See what is there in it. We do that, we take out the prefix because You have to take out the patience, don't you take out the sabre, whose sum is equal to man sex, then you should have the sum for the whole morning, right, you should have less all the morning, then you know what you do, you take out everything all the morning, even we There are three till now, there are five swear words, I am taking out all the prefixes, you take out these prefixes, so if I ask you to tell me the sum of any sabri, then now you can tell me, if I tell you, brother, you want the sum of this sabri, then see, you are very You will be able to tell easily, look, we don't need an oath till here, where is the time from till here, it's all nine, but we only need this much, we need this much oath, right, if we want this much, then minise this much, it means minise this much. Manage the kasam till zero, okay then till 9 - 0, how much kasam is reduced to three. Look at its sum which is equal to six. Here is 2 3 4 5 6. That's why I am saying that the prefix 'hum' is reduced for this reason. There is such a problem that we take out the prefix, you can take out any oath very easily, even in constant time, it is clear, it is good, so we have taken out this, so this brother, where will you steal, you can store it in the map, so what did I do? You have created a map, okay, store it in the map, what is the problem, and it will be even till the date index, okay, so how much has come till index number zero, how much has come till index number one, even till five has come, even six has come 7 8 9 10 13 14 We have stored in our map how much is the prefix till which index. Now you can easily find out. If I tell you brother, tell me the sum from index number one to five. Okay, sum from one to five. If you want then see what you will do, you will see how much time is not there till index number five, here is what you have taken out from the map, okay index number tu se just pehle tak kasam, how much is that, look at induction number tu se just pehle tak kasam, how much is there Till the oath is five, okay now how do we get the longest sum by giving this information, see that now keep the whole fox here for the next two minutes, walk carefully mother that you have come till here, okay mother let you go this much Do you know the index number till date? Do you know the index number? If the sum here is 10, then how much did you have to bring, the target was seen, so sub minus Tell me one thing, on the story, what on the story, there must have been an even three, after which 7 must have been added and this 10 must have come, I am repeating again, now I am standing at 10, okay, you have to find this target, 7 is right, so mine both of them, mines . Do 3, so I ask, is there any Sabri like this? Okay, after that , that means the time till the index number zero was three, which means that it must have been equal to that much, only then 3 plus 7 became 10, reached 10, only then here Till understand the index number till zero I swear it is 3, how did we find it from the map, we went right till here, what will I know and where was the last time which was three found, the index number was found at zero, we will have to store the index number here . Even and index here will have to be done so that you can find out the index. Right, here sum and index here will have to be done, so I will update it. Look once, now I have updated the map that the value is even and In which index that sum was found, that sum is also found here, it is fine in the index, so remember now in which index my sum of 10 is found, it is fine, it came at six, and last time, where was the sum of 3, right? Here's the value , okay, so I'll write it down, okay, what does it mean? The saber between six and zero means okay, so how much is the length, let's see, look, this is equal, you are six, that means it has come here. Na I - K will get this length, extract it from the index and mine it. So I have come to the mother 's advice that this is the biggest saber whose sum is equal to Let's reduce one, now let's move ahead, let's take I, go ahead, okay, now here A is okay, look at its sum, how much is it till the seventh index, the sum till here will be 13, here I will keep coming out all together as I keep increasing the sum. Yours is mine. Okay , so what was the point of bringing us? Respected sex. Neither did seven. Its value is 7 out of 13. Do 6 A. So it means that if the last time on the story, I must have seen six. Let's see where you saw the index number. I saw this is the index number, okay, understand its meaning till this point, and the sum till this point is 13, which means for sure till 20, 13 will be 3 4 5 6 7, right, if it is even, then it is okay, I will find out its length again. Right now I am standing on some index where the saint is yours and mine is not where the even is 13 index number is seven ok if you did 13 - 7 then 6 came then where was the last time I saw six even, I saw till here the index number on this index is you But where did I get it from the map here? If I did 7 - 2 then I got 5, that is, the length will fill 5 parts. Look, one, two, three, five, okay, so friend, this time I got five last, so I have to get the biggest one. I will not update, okay, so this is what I am saying, I will take the length of the longest sabri as 6 m, you will not be able to get it bigger than this, now you will dry iron further also, otherwise you will not get bigger than this is clear, okay, so its What does it mean that there is 6 length, who is that? Look, two-three, four-five-six-seven, this one is equal to seven. Okay , the time was - It will happen, see, by putting three, six together, we will get it , then we will be ready to code, here is a small question about how and even if you are not able to catch it, then there is no problem, mine also failed, only then I was able to catch it. First time I had solved this question, how is the smallest? Look, here the value of Its balance is all I have sex all I have here how much is 6 so we have to find the longest whose value is equal to six okay so let me pay attention to the even sum here right now I am here ma let's take the sum is one okay Then here is the even, you came here, then you came here, took the mother, reached here, then what will you do, whatever was the even, you used to mine in it, all I did was value of sex, whatever is six, okay, what did you do for 6 months, so what would you do? Where have I seen this zero is the last, this is what I used to do, above I told you this, yes mother, here it was even thirteen, here it was 30 - this was seven, then you used to find 6, whatever six i value Where did you see six last time, so I am doing the same thing here, it is okay when the sum till here is six, it is okay and why do I have to bring 6, so I am looking at the minuses and zero, last time I made zero, so it is in my sum. Not only, it is not there in my map and why is it so because brother, it is considered to be the entire element from the left side. Okay, so now here it is not there in my map, its value is zero, I will add one entry, okay till here . I swear there was 6 till here, I swear there was 6 till now, zero will be equal to -1, see what is the benefit of doing it, pay attention, I have got two , what is the value of i, it is two, ok -1, how much will there be three, rest will be now we are ready to code. You must have understood the instructions as well. Time complexity is of N because we only did the driver once. The gesture is fine and space complexity is of And let's finish it, so let's code it with the exact approach that was told and you will find the required code in my link, I have put it on the description. Okay, which sum came at which index, the right, what is its less, that too. You had come to know I and where I got all this index number I but look here I have stored the string in the map okay and to solve this one corner what I told you is that MP of sum zero is that. It will be on index number -1, I have given it here, okay, I have told you all this, now let us see what will be the remaining time remaining sum, okay, so what will I see, come inter find sum, remember what I said. It was said that in what is equal now, let's mince whom in the remaining time. Then after this we used to see whether we have seen this remaining sum nearby and MP on the story and find this remaining sum. If we have seen the notification then we would have taken out its index. In Idea Okay, now let's update the length of the longest surgery. Now, where am I standing now? I am standing on - Will do the last time ? It was my time to do so many operations. We will read the minimum. This is clear. Let's run and see the late example. So look here, I came to know about this only after I made a mistake, this is a check, we can enter OnePlus One and our target is 3, brother, it is impossible that you will ever be able to get it right, so now here already. You can check that the total time taken is less than
Minimum Operations to Reduce X to Zero
minimum-swaps-to-arrange-a-binary-grid
You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations. Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`. **Example 1:** **Input:** nums = \[1,1,4,2,3\], x = 5 **Output:** 2 **Explanation:** The optimal solution is to remove the last two elements to reduce x to zero. **Example 2:** **Input:** nums = \[5,6,7,8,9\], x = 4 **Output:** -1 **Example 3:** **Input:** nums = \[3,2,20,1,1,3\], x = 10 **Output:** 5 **Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104` * `1 <= x <= 109`
For each row of the grid calculate the most right 1 in the grid in the array maxRight. To check if there exist answer, sort maxRight and check if maxRight[i] ≤ i for all possible i's. If there exist an answer, simulate the swaps.
Array,Greedy,Matrix
Medium
null
226
hello guys welcome to deep codes and in today's video we will discuss lead code question 226 that says invert binary tree so here you are given one binary tray uh you are given the root of the binary tree and you need to invert the tree and return its root okay so here what does the invert word mean invert the binary what does that mean so let us understand that with this first example so here you are given this binary tree and you need to invert it so yeah as you see that this ah root note 4 has left Child 2 and right L7 so in inverted binary you just Swap this child that means that the right child become the left becomes right simple as it is see if the 7 becomes the left chair and Two Become the right chain now again for the node 7 it's left elbow six NHL was nine but we swipe it we swap so that the left shell of 7 becomes 9 and right shall become six similarly the left child become 3 and right should become 1 after inverting or you can swapping we're simply swapping the left child as well as the right side for each node as you can see here from this example got it now here 2 is our root node and one is the left shell 3 is the right chain so what does invert mean to swap the left and right chair thus unswapping the left side became three and the right side becomes one the third example we have nothing in the root so we written null or empty correct now let's take a look at this example so suppose you have this type of example and you need to invert it so tell me the root be the root remain as it is correct now what we do not in order to invert this tree what we are doing we are simply doing ah swapping off the left chair with the writer correct so here comes two and here comes one okay we just swap them now internally for two also we are swiping the left and right here so the two is left here big will become six and each side will become Phi and once left child will become 4 and here it will be three okay now for three also we need to swap so here it would become h and here it would be 7 first four uh its left side was nine but it's now its right side will become nine okay everything here would be null this would be also null so yeah this is how we invert the binary tree okay this is how the inverted binary tree looks like so now uh I hope you guys understood the question it is simple as it is but now in order to invert this how much you can do see as you can see here that we are just traversing all the nodes and doing some operation okay for each root node or each parent node we are outperforming some operation on the child node here we are swiping that so ah in order to Traverse all the nodes what do we need to do something like BFS or DFS Towers okay simple like we need to do some type of flowers in order to invert this string okay and what another thing we are doing is for each root node like that for each root what we do swap left and right child this is the only thing that we are doing to invert the binary we are swapping the left child with the right child and the right childhood we're just swapping them left and right side okay yeah this is all this is our approach we will either do PFS or DFS traversal and we will swap each side correct now let's move on to the coding part where we will look that how we are actually performing this so first let me show you the DFS approach so yes this is the DFS approach see guys as you can see here that here uh these two lines uh these three lines actually here what we are doing we are performing so we have swap of left child with the right shell and right shell with the left chain correct and then we are again doing DFS on the left shell and then DFS on the right track similarly it means uh similarly to perform the swaps honest children Okay so ah so yeah let me show you by drawing these that uh if you have a show three four if you have something like this okay so initially it will check if the root is empty no it is not empty for the root zero so for the root zero what we are doing we are swapping is LifeWay right so it will be two and one here okay this would be your answer now what we are doing we are traveling for its left so our left is two okay so now we are traveling again now what is the root is to for this and then again uh we are checking if the rule is not no root is not null then we are swapping left and right so yeah but both is now left and right so it doesn't make sense okay now your travels again so this is second time traversal uh for with what here the root is now like this is not and this is also known so either you do both of this it is none so in that case we return and Traverse its right child okay right child of node zero so this right side of the node zero has two children three and four so we will swap them okay four and three when whenever we travel so the solve function whenever the solve function uh will call for one at that time we will Traverse the node 3 and node 4 as per this correct so yeah this is how DFS traversal works that each time we are traveling traversing for some non not null root then we are just swapping its nodes correct left and child nodes left hand side child nodes and in the end we are simply returning no root node so I hope you guys understood the DFS approach now let me let us also discuss the BFS approach BFS approaches also similarly similar as to DFS so here in as we know in the BFS we use one Cube and initially we push the root right and the and then for every root with ah that is present in the front of the queue we just store it in the current and yeah we swap the left child in the right shell of the current as you can see here and we check that if the current Uh current left is not empty then we push to the queue and if the current right is not empty then we push to the queue correct so yeah and in the nvd term so we are not talking about the time and space complexity so the time complexity here would be big open right as we are traversing all the nodes present in the tree so the time complexity here it would be big of N and for the space complexity uh it would be also almost too big of a in the worst cases uh and this is for both the approach DFS as well as BFS regardless of approach it would be the same yeah the time competition is bigger fan is very traversing all the nodes in the space complexities bigger friend see it is somewhere bigger of H is the height of the tree but in the worst situation when all the nodes are present in the queue or in the recursive stack of DFS then in that case our space complexity would be because so yeah in the worst case it is big of an ins is the time complexity is also bigger so I hope you guys understood the question the approach part as well as the coding for both the approaches and if you have still doubles then do let me know in the comment section also do check the community section of this channel uh where you will found the job posting so I am regularly uh updating the section as well so yeah that's all from this for this video from my site today make sure you like this video And subscribe to our Channel thank you
Invert Binary Tree
invert-binary-tree
Given the `root` of a binary tree, invert the tree, and return _its root_. **Example 1:** **Input:** root = \[4,2,7,1,3,6,9\] **Output:** \[4,7,2,9,6,3,1\] **Example 2:** **Input:** root = \[2,1,3\] **Output:** \[2,3,1\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
84
Jhal Hello Hi Guys, this question in this video we will discuss our largest this is this grinder solution so see I told you that you have got a bar chart of Lal Singh, this is the chart inside which you have these six heights that you have once. Two brothers' that you have once. Two brothers' that you have once. Two brothers' promotion of light on the fifth of a child 's telling you that the biggest rectangle 's telling you that the biggest rectangle 's telling you that the biggest rectangle inside it which has the most area, then I had wiped only one of you, it should have cried that you look at six sites like a alarms and of their presence. If every one is a one-time scholar, then just consider one side as is a one-time scholar, then just consider one side as is a one-time scholar, then just consider one side as your base, then this time will not be available in the office, if it is of boot lights, then it will be considered as flirting, otherwise by making six as the base, I will make you the title of Sector-21 by making you in me, I will make you the title of Sector-21 by making you in me, I will make you the title of Sector-21 by making you in me, I will make wide speculation. How big can this be made, how much should I find, how much is the 15 minute tarpan 510 by making 25 comments 521 There is not enough time to prevent the war from spreading, the sight will bear fruit, the hydraulic triangle of four will go here till here, either the point of the first, two, three, well, my If you take this triangle rectangle from war to Nandvansh, then it will take 5215 vitamins. If you look carefully, then from here to here, the olive oil will spread till here. If you take Hazare's made elements along with it, then it will give 127 or six and the tiger will not fall, okay then? What we are saying is that you should consider each and every bar as height and spread it on both sides and see it can spread as far as it can spread, then it will increase till that height and width. Korea will be found, it's okay, but what I am asking is, if we did this on the element, then think once and see what the first limit was, I will show you in full, if on the element, we decided how far it can spread, then you will see. Will you decide for doing it, how far can it spread, here can spread till here, after this it cannot be changed by the hands of this place, then at least one person will start to find out how far can it spread, then it will be limited, then every one of us If we try to spread the base value, then it is okay, then our century will become more possible. If you want to do that then it is very important to think carefully about the birthday, you will understand that when it spreads, the goalless draw takes care of it till the next smaller element. Next model is mutton kofta Next9 element As long as he keeps getting elements bigger than that, he is like the one gets in Chota, then it was that yes mummy, I will not be able to come in the boundary and Sahib, the maximum limit is under-right, his maximum limit is under-right, his maximum limit is under-right, his height is the country Next9 limit inside Left is becoming his left. Okay, if you are not happy seeing this thing, then let me take another example like this, I don't take values, I just make ranoli like this, okay, like we are like this brother. If we talk or can talk about getting married to someone, then see how far will this person on the right side play, this brother on the right side will be able to get a cell, will be able to play this game, will be able to walk till this point, this will also spread in this year itself. No, we will not do this because beyond this, it is a small element, so till there it is going to look like a festival and the website will not be able to proof that the element is headed by me, it is small, okay, so if I change the court a little, change it to the picture times. Let me do this so that you will see that your style will change, then you will be able to play it here on the website, you will be able to play it from inside also, for this they will come here and stop where they stopped because now there is element, so the next model is based on the left, for that Americanism. And the Italian right is able to spread towards his height. Okay, so for this you need his Next9 Element All Dual app for every element and want college without height. After getting that, now you will be able to get rid of anyone who was our son with him. I control dad I think you are six 5451 that sex is fine PM Noida sec-62 5216 that sex is fine PM Noida sec-62 5216 that sex is fine PM Noida sec-62 5216 element Kaliyug smaller element inside I want to remove left and next flight mode now I will explain a lot to him no I will write that wicket quickly so you will see That I am making a right boundary, now I am not talking about this big thing, so listen carefully A Right Boundaries Basically next 9 elements on the right and one is always to be made like this after a while we will write play list boundary that will take some logic and fill it If both are filled then do you know what I am not going to keep family values, I am not going to maintain that the next 9 element of four is one, I am going to be among those keeping this, Pooja, what is the index of Next 9 Judgment and I am going to excavate the left side of Tinder. If I contact Messenger, what will I see? If I contact Intex Ultra, I will see an increase. 6254 5160 12345 6 If you want to know with more keys, keep in mind Pooja, the index of the next9 element on the right is f5 and the index of the next9 element on the left is 15054. Scrimmid three so right dongri m re dongri minus one his increase will be that from this I am going to do this next to you MSC maths model Mr. Right 100 index inside right an essay in this product okay so if I have both of these then see the maths area so Then we know a lot, then we just have to loot, the road length is I plus, okay, then how will it come, the right boundary will come - the left boundary will come - 110, and come - the left boundary will come - 110, and come - the left boundary will come - 110, and how will it come, as per his height, he is like Bigg Boss * and if this More then A, Okay, and after coming out, we will send you a message. Okay, now we have removed the war rider definitive, which is a small problem of its own. Next 9 And it's on the right. Okay, inside for you drive right to left, inside left. Left to right will work, this is absolutely ours, that's why we did it, Next Great Element, right from right to left clock, so I will do the same, stock monitor, festival to new Kabir, now this should not be that drink, start, happy, not loose - 151, put it in this It's okay, loose - 151, put it in this It's okay, loose - 151, put it in this It's okay, so I will give that also to the person with tears, Torch Light Dongri, the last one, what is the maximum volume Tubelight of yours, whose next 9 judgments should be on the right side of water, take these, I am saying this so that you can understand. If there is any element like caffeine and Sainik School Admit or Grade is very small or zero, its maximum limit is not there then there is no malware on its right side, that point is the next 9 judgment eye which you get on the left side connect channel bhandar. So here you hit that Anshul, I talk to you twice in the morning. If you have n't understood, then if an element does not get the next 9 elements on the right, like it is zero instead of throw, then it has a maximum limit and the type is not there. In this edit this post, consider it as the smallest element in Muskarah and same for left minus one as the smallest element, Patna. Okay, but consider that there is a very big gap on this side of this whole, there is a very small one, there was some voice. You will be able to expand everyone's boundary only between here and here, the boundary of which is to be said that it is not mixed in this oil, as if the forest will not come on this side, then the forest will be considered external and there will be little from the deprived side. If not, then the answer body will not come, then their horoscope will be considered as this, then it will be given brightness and youth, all of them will be found in it, like the side of the bun too, think, we are going to get offspring from you, two friends, there is a friend, think of the clitoris, we are going to get it and Seven - - Verb - By making get it and Seven - - Verb - By making get it and Seven - - Verb - By making I will either I will get along with Jogi All of them together get along with Okay so my deposits are kept like this Right Side Effects Academy for Lips Keep your report - If it happens then right for the last ODI If it is Keep your report - If it happens then right for the last ODI If it is Keep your report - If it happens then right for the last ODI If it is not small then its right side and left hand side will be considered as your length. Now I run it reverse edit link - second run I reverse edit link - second run I reverse edit link - second run I move it towards zero, I run it for the fans, now it is not like this. Used to wild stock dot size grade vacancy phone and that as long as they are closed in stock and there are five is small so that in the research related to arv specific them infidelity small will pause all the elders he will his home then we him smaller than our You will get a guy who is of some small guru because he is a small guy because of his body, it is okay, he started the pick in the neighborhood and he took the answers on the small ones, but it happens that the distance came out, both can be, the size of this type has become zero. Or I am a younger person than you. If you are a younger person then the answer is the same and if the stock is empty then ra.ng Ankit Kushwaha will go. Do then ra.ng Ankit Kushwaha will go. Do then ra.ng Ankit Kushwaha will go. Do n't forget to post the Pizza Bread entry that you have got in the last place. It will be a very beautiful code. Got this entry, very beautiful, it is for Roka or electronic but it will start from here, it will be like this, you do 200 and zero's leg boundary 2013 - I will get it is not for anyone only, 2013 - I will get it is not for anyone only, 2013 - I will get it is not for anyone only, okay, so deposit New Delhi - Mark loop will work, son, it has become 204 calm from the forest, - Mark loop will work, son, it has become 204 calm from the forest, you will walk in the forest, this plus from Red Lips, so don't worry, I will do it in schools and show you in some time, if you top it, you will get the water on the left, which you - closed You will do it, which you - closed You will do it, which you - closed You will do it, today I am going to rub for 2 minutes from school, so there is no need to explain to her, there is a huge possibility of explaining pregnancy to her, okay, so when I brought it and started it said something like not finding symbol is coming, it was not found because I have named it. If it has been named, if it has been done then it is being accepted and I run the website because I am clever so it has worked. Bring it once, I am drawing you how it was done this year so that you can see. Brother, first everyone's left side lottery was drawn, then the right side was drawn from here to here. What did I say that keep this 6 inductance outside, show its value, I put this one. Okay, whatever you have put and called it yours. Seven is searching for this diet, one you are the one saying, the next big one returns to the small one and is not able to make it pop, then the one lying on 125 index became happy, 1958 became happy, okay and he could not get it to pop, okay So we did not get that pop, we have that arrow where there is app and then there is answer, then there is Pushya. Okay, so try to wrap it, we could not get it to pop, the name here is the index, so we will show it like this, here we click. Let's just do something, his height boundary was seventh, I could not make it to the top, the same right side effect happened, so I am excited, list more here and five has come and the younger ones have been put to a standstill, the elders have time, sorry mistake. We have to keep in mind that they come after pausing the elders. As long as the elders keep meeting you and the topic is you are small and soft, he is the elder, till then we salute the grandchildren and the elders, we leave the younger ones and leave the younger ones. I am again saying this is a mistake in the universe, the first element is 6, its recovery has been made strict, it will appoint the elders, it will shift, the stock will be empty till then the intake is considered to be your right to the airlines, it has been completed. Via, the younger one will not get much done, his customer will come and answer that he has one, his mobile number is right, collect this true value fund of Rs 120, let's start friends and something has happened and he has cooked the elders and he is stuck on cannon selection. Brother, you have done exactly the right thing, one has been unleashed, Anvi has been released, its next 9 element has come inside, no, but here we will take its index, we are mixing it even in SMS time, but there is difficulty in explaining it, so I am showing you the value of the gift. Meaning 120 that something else happened here, five came, but the neighbor does the small one, you do not pipe, you could not do it, and if you could not do it, then that time is next9, this model Bank of the Light accepted, viewers welcome inch neck and limit for He is the same and was asked, you came to the elders, Bakayan to Bakayan, you could not tube, did not understand, huge inequality, paused it and turned it off, could not talk to the band, Whisker Actress 154 Bakayan, it is small, you became the answer. If it is then I will give one or 165 in front of two and then it will be asked, if six comes then it is the morning for the younger ones supporting the elders, but stop doing it, you will be the answer to this conduct dynasty, then subscribe points, see its sides, including governments. Do because reminder is phoenix topic 5.33 because reminder is phoenix topic 5.33 because reminder is phoenix topic 5.33 Decrease flight mode is going friend mix cider is there message again that shutdown is recovery samsung is a strange express border do seventh measure now will make play list powder similarly deposit in it - will make play list powder similarly deposit in it - will make play list powder similarly deposit in it - tied from here If you make it while walking, then there is a doctor for it on this platform - slaughter and it has been paused. 6 to come in the stock, the - slaughter and it has been paused. 6 to come in the stock, the - slaughter and it has been paused. 6 to come in the stock, the elders do the lesson, they have shrunk, if the tea is over, has it become empty, then it will be considered on this platform and the to has been crushed. If you are not able to pop the pipe and that then you became his co-mix model whose index is 54 and became his co-mix model whose index is 54 and became his co-mix model whose index is 54 and then left him complete or handing him over to the elders, the younger one was yours, you paused the pot, the younger one became his model, if the capital pipeline breaks. I took note of the fact that you will break down and when asked, if you are not able to get the younger one to talk, then only you and he had become his left country, now that there is a garden, it will be a problem for the elders, if the vote has become vacant, April has become vacant, then on that side. On his platform - Minister Baban Kushwaha On his platform - Minister Baban Kushwaha On his platform - Minister Baban Kushwaha Six, if you are not able to do this, then his height will increase, all white and your work is over, in the end he will be a teacher, on whom it does not matter, now you fight on this platform, there is also a border, first try making it, six. The side of Dongri is one platform - but means from here till here on platform - but means from here till here on platform - but means from here till here on Friday it is the same bed as the pot - which pot minus one is in this - if its one minus - which pot minus one is in this - if its one minus - which pot minus one is in this - if its one minus one is two then it is two rains way 2162 in the forest area. Alarm is for 6a how to Congress party leaders minus one circle how many 5 - - one means left minus one circle how many 5 - - one means left minus one circle how many 5 - - one means left is our sea increases right - select - one to 5 - - 16 - 215 right - select - one to 5 - - 16 - 215 right - select - one to 5 - - 16 - 215 2125 05 only host is grease laptop green 1 is also second - laptop green 1 is also second - laptop green 1 is also second - 12615 so Basically, for the former, for four, that face is on this side and one is on that side, so for 514 finance ministry laptop, this one is on this side, 5353 2101, this one is on this side for them - 08 this one is on this side for them - 08 this one is on this side for them - 08 2012 276, this way along the level is 5752 - That 2012 276, this way along the level is 5752 - That 2012 276, this way along the level is 5752 - That this weight has become now Monday do 62162 * this weight has become now Monday do 62162 * this weight has become now Monday do 62162 * 50 515 points 12512 Balance 512 7766 Biggest Railways Basically you took out the lift of the high school and replied its height at the right time. Right one to the life management man, you had got the weight. All these areas on the side are yours. Don't take it out, he is the biggest one who has become yours. I hope you have understood this. Okay, so we will get questions from the sites, that too on that topic. Define question-01 There will be question-01 There will be question-01 There will be no tricks in dance choreography. Once it is easily gone, the stocks are able to be kept there only for a year because the Next 9 limit has been used, if it happens then all the 9 is written, the second correction has been made within time but in the largest area Instagram question, so what we have done in this- What was the dried dongri and used to take what we have done in this- What was the dried dongri and used to take what we have done in this- What was the dried dongri and used to take out the left and to take out the right we were the next small element and to take out the right we did not do next 9 limit and laddus which used to pop, we were all yellow when the big one was big in the stock. Here the equals will also have to chop and come to see that you are actually present in the tree. If you are not looking for maximum and oil, then the equals will also have to pause if there is a big value in the tag or the platform for the sacrificial ritual and Kayan Tower. China also got Pure Correction Ride Made in the Question Vidyapeeth and It Means and Ability Test Case Solved Was Appointed New Destinations Thank You Very Much See You in Next Video Bye-Bye
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
409
hey everyone welcome back and today we'll be doing another lead code 409 longest palindrome and easy one given a string gas which consists of a lowercase and uppercase letter written the length of the longest palindrome that can be built with those latter letters are case sensitive for example a is not considered a palindrome here so they want us to just return the palindrome length you can say and but they do not want us to return the palindrome itself so it is easy but we can do if account of a certain character is positive we are definitely adding it to our palindrome why because we can put it at one at the very end one at the very first so but it all boils down to is the middle character like if we can add one odd character or not or bus stop just uh one so we will be adding one character which is a single in its uh string to the middle and that's it so we can carry b uh b single and four C's and D that will make the seven so at the first time you'll be carrying DD and then we will be carrying CC and we have a one space for our middle element so we'll be carrying B and if we make a palindrome by this we are not going to make a palindrome but for just understanding like this the palindrome will be like this uh reading from the left it is the same reading from the right is it is the same so let's get started with we can do it from a hashmap but we can also use in the python at least a counter which will count the values for us the yes the count values for us how many times it is being repeated so and also our output will be 0 for I in so for not I in rent but for every character in you can say you can count let's call it count so every count in C dot values which will give us the values so output we are going to append it to our output like this and what we'll be doing in this case is just dividing our count by 2 and then multiplying by 2 so we can get rid of you can say the neck the odd ones you can say like if it is clear so now we'll be checking if output is equal if output is divisible by 2 okay and at the same time our count should be this is for the middle character all of this if condition is so count at 2 if it is equal to 1 which means it is an odd character what we will be doing in this case is just appending our output adding one to our output because it is a single character or an odd character we do not want to take if it is a three we do not know we will be taking the three but if it is uh you can say a single graduate yes A Single Character but uh yes if it is a single character like B will be appending it our output and after doing all of this we can just return our output and this should work fine let's see if this works or not yeah this works and that's it yeah that's it
Longest Palindrome
longest-palindrome
Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters. Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome here. **Example 1:** **Input:** s = "abccccdd " **Output:** 7 **Explanation:** One longest palindrome that can be built is "dccaccd ", whose length is 7. **Example 2:** **Input:** s = "a " **Output:** 1 **Explanation:** The longest palindrome that can be built is "a ", whose length is 1. **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase **and/or** uppercase English letters only.
null
Hash Table,String,Greedy
Easy
266,2237
1
That the country's most important question recording interview is in this point in a lot of this interview solution I want to see what fiber skin coat 19 grower of solution but today the tell you about this method you for watching and using Hello friends welcome back to The place were simply programming with that today problem is the weight was however she already had asked the but tried to simplify the problem statement for you to give in the role of a teacher name and target value2 that intern sexual is Half a minute on the rumor number that in when you are giving and derivatives called them at market value now second has committee of light and give in this question is that can be finger to do the return of subscribe 602 and slowly 217 one day them 229 love you Can feed in there element dec29 in oneplus 1526 711 good also 80 211 1431 and font in this answer buddhi viron ka 12780 and tight number to three do for you to give the volume to give good gifts on 100 you can see but you will only one Stop In Tears Into And Four Days After Adding Up To Give The River Target 69 Way History Winters Like 0210 Hai Winters 120 Answer To In This Case One To During S That In This Case Which Can Define APS University Ne Bhatk Imli To In Teachers And staff at least 60 unit certificate to in this case Agnewesh indexing and once again this answer 200 ka mobile a special yadav problem statement looks like you refuse in the role of a teacher and at market value and its guarantee daughter of interior donkeys now in its Written in defense of elements that now left for this video and tribes problem on so for the solution Liquid developer problem solution first now to-do list developer problem solution first now to-do list developer problem solution first now to-do list problem how to find the phone the walking into a AC you can try to find out the sum of all The Elements One by One Co What Do You Can Start Weather for Element 16.81 1623 Length 64 16.81 1623 Length 64 16.81 1623 Length 64 Ki Entrance 1615 Light and Swear Food Be Co Mute Behave Entries Co Target Volume Mute Find It Anywhere Light Co England Voted Against the Number 8 Try Twenty Three Layer 840 And in this point out some water food also hello viewers penal code na target shanidev what does not write down the mission impossible rukh something like oo hai to ashwin scene shoot down all the some possible of all the combination ultimately to find the value and good night Fall in the industry and of course to MP3 for this solution is very well at bottom problem which is my is very large no key side is that mini element and would have made combination over her tight combination silk calculate distance notification approach to law and approach in About that in problems Jhantu basically search for two number light win the race for watching in built for this beneficial and come to mind to think what is the guide channel thank you can find something for searching for its elements meaning water tis its original volume That a original added 8 elements and dark stretch is not but previous report and right down the you are so now up my is potter and the first elements play list element and the last element style object element nine to find the number black list number 126 Number One And Slept For 2nd Are The Number Three Larger Than Life In A How To Draw A Number Smiled And One Night But You Number Set Up Small Wooden Floor Three In This Approach Drove The Motor Try to your last Point One Step Back And Resort And Right The Avengers Model Number 23 Is So I Last For Entering In The Twentieth Reel 101 Shades Co Spun More 09 2012 Ine More Number This Time I Tried To 6 And Leave One Step Back To One And 600099 Inter College Alava Over All Name Attracted 2016 2019 MP3 Yakin Existen Target Was Not Show My Point 824 This Time 809 Some Come To Be Edited 500 Target Value To What We Do This Who Reduced Last Point A I Last Point 98 What Happens IF E Give element no that and yes matches after get married that now value is 82.80 app and this is value is 82.80 app and this is value is 82.80 app and this is 15212 is you can look up in the original affidavit for 108 number 4 inches that answer is B-1 and B-2 coach number s- 10 that answer is B-1 and B-2 coach number s- 10 that answer is B-1 and B-2 coach number s- 10 Not The First Time Complexity After Log In Do Subscribe And Difficult Time Complexity Interview Lokp Hello Viewers Pointing Problem You Think Multiple Base Light Off Shifting Problem In Reverse Direction What Is The Mean 2.2 In Reverse Direction What Is The Mean 2.2 In Reverse Direction What Is The Mean 2.2 Elements Straight Light this Video not support 6 Time Target Value 90 123 Lo Solution of Chapter Number 9 0 Answers In Every Time You Work Harder Time Right To Improve The Time Of Not Even You Temple Them At A Place For Elements 600 800 Implement Food 9 - For Elements 600 800 Implement Food 9 - For Elements 600 800 Implement Food 9 - 60 2223 Lut Pati Table You Can Find The Right To you two and six number index in the festival 6 and going ahead number 493 494 3215 again play list number 2 3 that complement of 2319 dubai a pun skin same note point - for annual a pun skin same note point - for annual a pun skin same note point - for annual festival you simply quantity 3 and varied units index in the Struggle A Moving Ahead High Court Number 8 A Complement Of 819 Dubai 1111 Also Did Not Accept Hindu Festival To Adapt Eleventh And Its Index Na Now Why Bed Mute The Number 15th Complaint 1519 Guddi That Former Tried To Look For In The Is Stable You Can Find over here right down there uses for notification you have an index for this during Sarovar Hair and other index in Indian History Bal So in this case 101 Answer Comfort to be given news on this very much similar to the answer is yes Pandey and these Previous case not the time complexity of this refer chilli powder of in that is pair finger scan dark once on the right side this solution you piece complexity of order of benefit these table date maximum clear number of elements nine today latest to the river that Understand this code allot limitless examples paste to left side of the court to implement right to edu is this your name target person has parameter in a big way Shri Govind head start allu ki agri hydration what does not confident volume hai so from now till roots quite Confident In Difficulty Target - Number Set In Difficulty Target - Number Set In Difficulty Target - Number Set Identification Loot Ko Dali Complement 19603 Is Next That Time To Complement To Find It Means Quarter Solution But You Can Find The Right To Avoid Simply Put This Value Along With Index In The Huntsman Ko Mahatma Half Inch 60 K Jis loot hydrate once again and each time were appointing ad number 410 also appoint compliment time till medium to be 9 - on time till medium to be 9 - on time till medium to be 9 - on date this thing pain phase map swift volume civil defense loot's cutting and you have no value 23.28 waist three layer is later value 23.28 waist three layer is later value 23.28 waist three layer is later compliment time Limit for b 9045 york and thus will return to contacts and induction time crop jai hind is case weight come office canceled to i hope life is the problem and solution for u left early years of famous problem benefits of lord of 10th prime minister of the interview On What They Think Tank Printer Subscribe My Channel Subscribe Can Improve The Way Give Some Thoughts In This Problem In To-Do List Channel Thoughts In This Problem In To-Do List Channel Thoughts In This Problem In To-Do List Channel Subscribe To That Man Criminal Intimidation Milo In Case You Want To Share That Might Interest You This Code With All The Elements And It's available free profile subscribe my channel friends motivational videos and
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
706
Share Guys Welcome To Your Comments In This Video You Will See The Question Designing Subscribe Now To Receive New Updates And To The Giver And - Note Content For The Giver Not To The Giver And - Note Content For The Giver Not To The Giver And - Note Content For The Giver Not Give The Name Of The Question Is The Beginning Library Simple Solution Used Oil The Ko Ek To Instructor Beating Up Map And Instructor Vilas Length 10.30 am Instructor Vilas Length 10.30 am Instructor Vilas Length 10.30 am Validator And Civil Line - 1090 Value Currently Validator And Civil Line - 1090 Value Currently Validator And Civil Line - 1090 Value Currently Working On That And Forget Wick In The Street Vendor Index That In Remove Method Which Can Just Set The Volume To Minus One Pour Reference No Value Currency Presents Who Is The President Work Pura Network Test Cases Where To Give Not Difficult Do That Use Jitendra Sweater 205 Waqt The Self Respecting And Submit The Values Into This Channel Must Subscribe Button Which Will Work Aadhaar Link List because in this situation different key entry in class entry combination decide what is the number of the day ki asli shirt dress code and creator entry class 9 ki jis class monitor akki and wali hai ki and constructive and setting its volume so let's make a public Rally in up happened to return home entry class work will be making this mean that nothing but a to improve marriage are off list content pendry in and construct new to take off that even today discuss 2769 and now you can just say map equal to a That penis left side open president mike sudhir vibration of knowledge and see the value of is so they do others will get number canteen and junior research in the and but at least to the giver is 16000 for sister calculator but oh yes babu singh ki motorcycle na To-do list yes babu singh ki motorcycle na To-do list yes babu singh ki motorcycle na To-do list Play list A key in the entries Neetu Search for the giver's needle extract is over the entries And here this entry Nautanki Hu is equal to my key name I love you to effigy specified Iss Point Mintu Returns The Association Volume Otherwise - Subscribe - 2 Mein Subscribe - 2 Mein Subscribe - 2 Mein Knowledge To Hide And Seek Another Method Input Method Its Value And Dissenty Insider Map Online News Current Entry Be That Hanuman Sihag And Bucket A Need To Check Weather Pressed Creativity And Handsome List Tweet A Aap Is Tawa Katnal-1 To Create New Link Aap Is Tawa Katnal-1 To Create New Link Aap Is Tawa Katnal-1 To Create New Link List And The Current Entry Antonyms Hai To 10:00 Buzz Take Care Tips Number To 10:00 Buzz Take Care Tips Number To 10:00 Buzz Take Care Tips Number Twenty Knowledge C Is But Not A Tomorrow Morning Need To Attract Over Each And Every Day At Present But U Ajay Ko 200M setting this mic that is equal to the key drama present president updating divine current but I am safe about method knowledge to remove this is going to remove the new white horse. Creativity and field on who is that was a team which can simply retail price presents you need to remove is otherwise Vineet to straight and reddy entries how to where is that these are equity linked to remove that I will take the particular entry in A Temporary Variable Hello Friends Defined Serial Usage 210 Will Help In Removing From Pearl Necklace List Remove One Object Flu And This Channel Otherwise Remove From The Meaning That Surdas All About Remove Method Sunao Let's Go Ahead And Scored And Its Getting All School Color Knowledge And Remove All the numbers of the day that a
Design HashMap
design-hashmap
Design a HashMap without using any built-in hash table libraries. Implement the `MyHashMap` class: * `MyHashMap()` initializes the object with an empty map. * `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`. * `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`. * `void remove(key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`. **Example 1:** **Input** \[ "MyHashMap ", "put ", "put ", "get ", "get ", "put ", "get ", "remove ", "get "\] \[\[\], \[1, 1\], \[2, 2\], \[1\], \[3\], \[2, 1\], \[2\], \[2\], \[2\]\] **Output** \[null, null, null, 1, -1, null, 1, null, -1\] **Explanation** MyHashMap myHashMap = new MyHashMap(); myHashMap.put(1, 1); // The map is now \[\[1,1\]\] myHashMap.put(2, 2); // The map is now \[\[1,1\], \[2,2\]\] myHashMap.get(1); // return 1, The map is now \[\[1,1\], \[2,2\]\] myHashMap.get(3); // return -1 (i.e., not found), The map is now \[\[1,1\], \[2,2\]\] myHashMap.put(2, 1); // The map is now \[\[1,1\], \[2,1\]\] (i.e., update the existing value) myHashMap.get(2); // return 1, The map is now \[\[1,1\], \[2,1\]\] myHashMap.remove(2); // remove the mapping for 2, The map is now \[\[1,1\]\] myHashMap.get(2); // return -1 (i.e., not found), The map is now \[\[1,1\]\] **Constraints:** * `0 <= key, value <= 106` * At most `104` calls will be made to `put`, `get`, and `remove`.
null
null
Easy
null
617
welcome ladies and gentlemen boys and girls today we are going to solve unschooled problem which is must do binary tree so this is the binary problem see as simple like you get from the title idea okay so ladies and gentlemen let's just see like what the question is in the questions having been given a 2 by 3 is root 1 and root 2 and we have to written their sum so you know simple like root 1 plus root 2 you have to give root 3 like that the complete value okay so what did i mean by saying this if you see over here then you're saying add 1 plus 2 give us 3 plus 1 give us 4 2 plus 3 give us 5 and 5 plus no give us 5 no plus 4 give us 4 empty plus 7 give us 7 that's impressive so that's how we have to uh tackle this problem so ladies and gentlemen uh now you will ask like okay how we gonna do this then i will say like we will traverse recursively in this one okay so we will there was a recursive way all right and what else we can do so what i'm thinking is like as you're developing vehicles then i will add the tree value in one tree let's say like i will use root uh this root one tree t1 then let's go to t1 so i will add my all the values of the t2 into t1 and i finally written my t1 that's what i'm thinking about so if you still don't understand don't worry as you write because the code is very simple as you write the code you'll definitely want to understand so ladies and gentlemen without any further ado let's just start writing this problem and here we go so my first job is i will just simply say okay do one thing check if my root one is null then what you have to do if my root one is completely null then simply just written root two now you are like why not root one because like might be root 2 as well value present we don't know so i will simply say written root 2 as simple as that if the another condition will say if my root 2 is null then i will written my root 1 value if let's say if something 8k has something present there is important by root 1 complete tree the simply returned it okay now you can say like okay dude we have what uh root one tree and the root two three as well then what we're gonna do i'll just simply say okay do one thing add root one root value into my add root one value with root two value okay and finally return rule one that's what i'm thinking to do but before that i have to traverse in the complete tree so for that one i will just simply uh use mercury function to traverse in that one so i will say root one dot left so i will go for the next one using my mastery uh pole okay guys so i will go for my root one dot left similarly to the root two dot left okay as we are using root one tree so i will simply enter over here as well root one don't write nodes to two okay with my merge please function called it will go for its right now i hopefully rejected the sixth floor like what i'm doing over here so that's all the core is ladies and gentlemen so yeah that's what the code is let me just give a quick run it and i will take you a quick walk to the code like what we did over here and here we go gentlemen is accepting very well so let's talk about like what we are doing so these are our two base conditions the base condition is saying like let's say if one is present it is not present then written the root two three if the two is not written then simply return the root one tree over here what i'm doing i'm adding the value of one plus two which will give us three like this one i'm doing over here and over here what i'm doing i'm trying to traversing uh first time it's left side then second time i'm traversing the t root one three right side okay so stable thing and it's uh putting the value over here and we are finally entering our root one either you can go for the root two three so what do you have to do you just have to simply change over here like okay we are going for the root two but if you want to go for the root two okay if you are going for the root one then go like the similar like i did okay ladies and gentlemen without any further let me just submit this code to see anytime complexity like i will talk about time complexity and all over here so let me just sum in this code to see all the test cases are passing or not so here we go ladies and gentlemen the code is accepting very well okay now let's talk about the time complexity in this one we are dealing with big o of n and for that as we are traversing n numbers of nodes that in the worst case the time was the big of n okay and what this phase complexity in this one we are dealing with leading generator space complexity in this one we are dealing with this big of n for the worst case and you know like we are putting the value so kind of like is using the stack but let's say for the like average case the tank conversity we will gonna deal with low of n so this is for the worse let me just write it clearly for the verse and this for the average okay so houston legion when this score is very clear like what we are doing over here so ladies and gentlemen if you still have any doubt just do let me know in the comment section i will definitely release to you and thank you very much ladies and gentlemen for watching this video i will see you in the next one till then take care bye and i love you guys believe me i love you take care bye-bye
Merge Two Binary Trees
merge-two-binary-trees
You are given two binary trees `root1` and `root2`. Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree. Return _the merged tree_. **Note:** The merging process must start from the root nodes of both trees. **Example 1:** **Input:** root1 = \[1,3,2,5\], root2 = \[2,1,3,null,4,null,7\] **Output:** \[3,4,5,5,4,null,7\] **Example 2:** **Input:** root1 = \[1\], root2 = \[1,2\] **Output:** \[2,2\] **Constraints:** * The number of nodes in both trees is in the range `[0, 2000]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
931
in December uh time is 12:24 a.m. uh the in December uh time is 12:24 a.m. uh the in December uh time is 12:24 a.m. uh the match is about to start and the motivation for solving this lead code problem is the first one is we haven't solved it in the past it's a fresh question so after a very long time I got a fresh question I thought let's do it the second motivation is actually the main motivation I met rajat today rajat is one of the subscriber of coding decoded he has been following coding decoded channel from quite some time now and he just joined Adobe today so in the morning he messaged me personally on the telegram group stating that he has joined adob and would like to meet me in office I clicked a photograph with him I'll be sharing the entire details of the incident on LinkedIn very soon so stay tuned and I was super excited to see that even in this time of lay off this recession time where everyone is struggling with their jobs quoting decoded could contribute to others life and I'm super pleased about it now let's get back to the question given an array of size n cross n wherein uh all the numbers are of type integers what do you need to return the minimum sum of any falling path to the Matrix so the path starts from the top row goes up to the bottom row and at each cell there are three options to take either you can go in the immediate lower Direction immediate left Direction immediate right direction so out of the three possibilities you want to select the one that gives you the least cost so I'll be talking more about the solution by the presentation so let's Qui hop on to it here in this question you given a matrix size n cross n and what you need to do you need to move from the topmost row to the bottommost row which is this one and while moving from the topmost row to the bottommost row you need to keep in mind that you have to always select the minimum path minimum weighted path so you given weight for each cell and as per the question while moving onto the next cell for example if you are over here if you want to move over here then there are three parts possible you can come from this route and you can come from this route which one are you going to select you will select the one that gives you least weight so for reaching this particular node the cost would be 1 + 5 which is six so let's write six over + 5 which is six so let's write six over + 5 which is six so let's write six over here the cost for reaching this particular node would be equal to a minimum of 2 and one so because one route is this other route is this so minimum of two and one gives you 1 plus 6 gives 7 so let's write 7 over here the cost for reaching this particular cell would be minimum of 1 and 3 which is 1 + 4 which gives you and 3 which is 1 + 4 which gives you and 3 which is 1 + 4 which gives you five so let's write five over here and let's repeat the same thing for these three cells as well so here let's write seven over here let's write 8 over here let's write 9 over here these are not the actual minimum path these are the current values for these particular nodes so the actual minimum paths would be equal to minimum of 7A 6 which is 6 + 7 gives you 13 so the answer here + 7 gives you 13 so the answer here + 7 gives you 13 so the answer here would be 13 for reaching this particular cell three parts are possible 1 2 and three the minimum of these three values five six and 5 6 and 7 would be five 5 + 8 six and 5 6 and 7 would be five 5 + 8 six and 5 6 and 7 would be five 5 + 8 gives you 13 so the answer here would be 13 let's proceed ahead the next cell that we have happens to be this one so uh there are two parts possible one is this one other one is this one minimum of 5 and 6 is 5 + 9 gives you 14 so of 5 and 6 is 5 + 9 gives you 14 so of 5 and 6 is 5 + 9 gives you 14 so the answer here would becomes 14 now you have successfully reached the last row and the final answer would be equal to the minimum of the value that is set in this entire row because you can reach any cell in the last row so the minimum value that exists in this last row happens to be 13 so the answer becomes 13 this isn't sync with our expectation this is what we are going to do in the coding section as well the time complexity of this approach is order of n Square the space complexity of this approach if you're creating a new array new DP array then the space complexity would be order of n square if you're updating the original array which is not a good practice then the space complexity would be order of one to conclude it further let's quickly walk through the coding section and get a good hold of the entire algo here in the solution uh I have used and updated the same Matrix which is not a good practice ideally I would have created a different dprf for this however one of the subscribers submitted the solution the same solution in Java so I thought you guys would be able to correlate to it the most so here basically he has created a helper method wherein he's identifying the minimum path possible out of the three paths and he does that depending upon the conditions of the column index if we are at the first uh column if we are at the last column then these conditions should be checked and then we return the minimum one out of the three possibilities uh and basically we are doing it for each cell therefore uh we have written two Loops over here our index starts from I equals to 1 why because we are doing it from the first row till the last one and this is pretty simple and straightforward once we have identified this up what do we basically identify the minimum value in the last row so whatever the minimum value exists in the last row that becomes our answer and this algorithm correspond to that so let's try and submit this up accepted awesome this is approximately uh 95% faster which beats a lot of good uh 95% faster which beats a lot of good uh 95% faster which beats a lot of good developers in terms of time complexity and this seems like a good solution ition with this let's wrap up today's session I hope you thoroughly enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and sa you for more updates from coding decoded I'll see you tomorrow with another fresh question but till then goodbye
Minimum Falling Path Sum
maximum-frequency-stack
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(row, col)` will be `(row + 1, col - 1)`, `(row + 1, col)`, or `(row + 1, col + 1)`. **Example 1:** **Input:** matrix = \[\[2,1,3\],\[6,5,4\],\[7,8,9\]\] **Output:** 13 **Explanation:** There are two falling paths with a minimum sum as shown. **Example 2:** **Input:** matrix = \[\[-19,57\],\[-40,-5\]\] **Output:** -59 **Explanation:** The falling path with a minimum sum is shown. **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 100` * `-100 <= matrix[i][j] <= 100`
null
Hash Table,Stack,Design,Ordered Set
Hard
null
747
Dream II car, when I know I'm in this row, I'll wear it and solve a math problem to know better. For more detailed information, please go to the available books. okay how we work this number Ok hello everyone came here 2 years of d up to Nikko play times Today we will continue with you this one song already before coming to the next of the responses water response and today Can Tho has anyone going to work 747 Lucky number of English day of Death Ok to present us like me given a life of five and there is only 1 largest number find this piece which largest number has the least Is it twice as big as all the molecules of re? For example, we have a network of 36, the largest number is 6, then compared to all the retry, the number 6 must be at least twice as big in the molecules. The remaining product For example, here we have 6 times double three and 6 times 1 and not counting zero. This 6 level is at least 2 times the remaining words, this is the largest number that in the remaining molecules, I just maybe it's three, 6 divided by two is three, but 1234 is the largest number, but four is double or not just 1, how many times is that? command and we Return not one but if interesting then we go name the Index of this number Ok the idea of this article is also for the audience because we need to check whether this largest number is the least large 2 times more than the other molecules, then we just need to find the second largest molecule and we will compare the largest molecules into the second order, but it is greater than or equal to 2 times the second largest molecule. The second largest number after it, then I'm this combined and we write down the name Index of the largest number. Okay, so this lady will be similar to finding the third largest number that we did before. In the all right section Ok now let's start with the exercise Ok first we will need 2 canes which are Les Tab and Jessica number to céleste shore then we will save the largest number of the dirty sackcloth Lumpur then We will save it for Monday. Ok we can see that the problem for all the elements is greater than zero so we will initialize these two variables the first number Serial number with negative alligator ok because that will ensure that in time we can find If but not find the largest number two is the largest number then the value and remains about - 1 then the value and remains about - 1 then the value and remains about - 1 if we achieve zero then if the piece We wo n't know what kind of scene it is again, we won't be able to distinguish between the first number and the normal number here, we will have a case that is if As expected, it is equal to one. This means that this thing has only one element, then this is the asuka of this coin. If there is only one Buddhist, it is of course larger than all the remaining elements. The remaining molecules are considered okay, but we will always have the Index of the first molecule. We will go through that from beginning to end. Ok if there is anything to lose. Whose number is greater than that? first dream, we will reassign it to the good one. How is it? The number a. But before re-labeling the But before re-labeling the But before re-labeling the first number as number a, we will save the previous value of the removed one because of the The first is the shore now it will become the second largest number when searching with the first largest numbers, the old first largest number becomes the second largest number at the 2nd hour if that number is not greater than the second number. If the first number happens to be larger than the second number, then we just assign it to the second number. What does that mean? That is, if the example was like before, what happened from the beginning to the end and now? First of all, these two numbers are both taken. Then we start with the number 3. The number 3 will be larger than the number. The first number is like that. Both of them will be sent back with my old text. I will do it for me. million one I am the value of two people does not change only the value of the first number will be replaced by 3 That means the biggest value is here i from now on Lara's first mind will be three and will grasp the beginning for a moment this time the second element the second week that it is two that is two it is still small The First number the flight number Well it will jump down this is two still bigger than the car this will claustrum just be Why is that because at this time the remaining car will need this number it is currently not One So that two will be added here to become the second largest city in Yeah ok Now we come to my name and this one we We already have that the first number is the second largest number and according to the observation we just made, if the first largest number is twice as large as the second number, it is a form of agreement. Ok the first amor is greater than or equal to the same Number 2 times greater than equal to twice then we will return the Index of the brilliant treb speaker like so Here we need to print more of that, please type again. Every time we update and find the largest number, we will update this modification. Yes, let's leanmax Max. If that's okay, then we'll go. Name - 1 ok shirt then we'll go. Name - 1 ok shirt then we'll go. Name - 1 ok shirt See base for women Smith Yes ok xserve Yes Ok But when it comes to muscle numbers and related fields will be placed below the description from some articles here. It will be simple for us to relax after some sessions that we working overtime Dat with lisp the next days we will come back to Kris Ok Now you have one left remember to like and subcrise and notify so you can know when I do it
Largest Number At Least Twice of Others
min-cost-climbing-stairs
You are given an integer array `nums` where the largest integer is **unique**. Determine whether the largest element in the array is **at least twice** as much as every other number in the array. If it is, return _the **index** of the largest element, or return_ `-1` _otherwise_. **Example 1:** **Input:** nums = \[3,6,1,0\] **Output:** 1 **Explanation:** 6 is the largest integer. For every other number in the array x, 6 is at least twice as big as x. The index of value 6 is 1, so we return 1. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** -1 **Explanation:** 4 is less than twice the value of 3, so we return -1. **Constraints:** * `2 <= nums.length <= 50` * `0 <= nums[i] <= 100` * The largest element in `nums` is unique.
Say f[i] is the final cost to climb to the top from step i. Then f[i] = cost[i] + min(f[i+1], f[i+2]).
Array,Dynamic Programming
Easy
70
76
200 Hello friends, welcome to the new video of Tech and today we have problem number 22 Edison, today is Banswara day, our minimum is Window 7 Singh, it is okay, so I have made the work easy in this, it shows you that this problem is a high level problem. There is not so much ad in it will take some time to explain to you, so we have a string as you can see, whether there is soil or dust in it or not, where ABC is visible then you have to enter my mobile number, so look at my ads here. The training is looking patient, it could have been transferred but it is not the minimum. After visiting the minimum, we came to know that the BANC is the minimum and even though there are pomegranates in between, but if you definitely see my ABC, then this will be our output, okay. And he is not saying anything that according to Idris, please return the screen, we will make a case for the peace friend, a little bit that this is a unique answer, you know it and the highest quantity is fine from the sequence of the country, first of all my Listen to the explanation, okay, after that we will talk about coding and it is very easy, so let us keep it as SDO and today I have a pencil so that when I want to highlight, I can do this whenever I want, so in this case, this We have given that our ABC is and you have given our NC, I told that ABCD, we don't like this also where we are getting C and we are getting this shortest length, we have taken the end unmukt, so now what will we do in it. Okay, now it looks like a jar of installation, what do we do, actually we are checking the green first, we will wash the small one, then we will go, we will take one nando here and we will take these days, then we will take all four, then we will check. These four are also having an affair. If you want to know directly and it is definitely there are only three, it is okay to collide with two. I will update it first. For whom do I do it? It is okay for the window. Whatever the point is, we will take part in it. Message, Text, Message. Is it right and in the second season, account and three thugs, this is to comment, we should know the account, the fame in the team, tell us how much is the ABC benefit, there are three, at the moment we know that what you have is ABC, the content has to be made, okay. So friends, the same is true for the hair which I have taken, there is a cafe like account in its window right now, 0 as we move ahead, our value update will come down on this house map that we have two things because these which are already fine and these were Required Already, how much is required, how much is the requirement, it gives the latest information, wait, this is the team, 10 written separately, or who knows, it is drinking, here one character account will be increased, so what do we have to do, we will do the typing from here. And we will put a point that by electrolyzing it will also increase the aslam. Let's get angry when who am I will tell you that you know we have it okay, so we have aircraft from here, it is a, now I showed a yes, which was coded by removing it from zero. Okay, now I see that the bank account has not been fixed here, the identity of the person has not changed, so that you do not have to check again and again, that is why I have made it ready here, okay, so I will check till then, if I remember you in Already, only then. I will check whether those three nooses are mine or not, then I am ready now, look, I am definitely like this, so why check every street again and again, time has to be taken care of, now like even after the video, it has just come, so here also. If you updated it and closed it, then it is fine, it has 181 matches, 13, how can we win, if we go again in the middle, then this 2010 will go ahead, nothing happened for this, if we come to the seat, we need C, you have understood one thing. That all three have become one, no, already and the husband is already there, that is equal to two required recording environment, if this is so much then it means that our answer will be two, it was written that the answer will be 1 2 3 4 5 6 inches. That she would like to get you out from her head to toe, OBC actually happened, keep in mind, if you try, tell me the minimum, what will have to be done to reach the minimum and will have to look ahead, then what do we do, we have come so far, what do we do that one step Let's go ahead Shankar, so let's remove one from our team, start one cord each and move ahead, okay, so moving ahead, we saw that one of them is already ready, it has been printed. Start this video and then move ahead, check the SMS. Started thinking that the delivery is not coming, the wife is not coming and a time will come when I too will reach, who knows, even stuck here, this has increased to the point that I will give you very sorry, this is fine, it means it is not so. That in this we will increase the number already, whether it is two minutes or not, if we have to increase it for different people, then neither will it work, it will be greater than equal to two, how much can we play right now, the reason for that is that you are our condition, then the result is It was here also, it was from here, wherever it went again, so I am 20. This must be one time, it is not a request. According to the rules, our next length is taken equal to the already requested. I am telling you that now the length is If it becomes big, then at the moment it seems small compared to such a big line, if you do n't see me, then definitely with such great attention, because that's why we will start doing it, then we came there, after doing this, we have to ring this and go ahead. Ours is like this or that I will tell you and these have been revolved around this again, let us keep updating our answer. Okay, if our answer is not there, then that is why the main has not come, where will the medium come from? 21 It came to pass that as Dharam Singh kept on doing, she would stop after coming to India and here it became a minimum of 8 to 12 people. We found that this also does not happen in this, so our copy. Please give us 25 answers. Okay, table less, subscribe. We cannot progress beyond this, that's why we have shown it by doing it in the end. So, if you want and fashionable condition, please, I have made a code. This is the thing, explain that. If it is very easy then in the first and I will tell in a chapter that you have to keep this picture in your mind, what kind of cigarette am I reaching, why is it already made, that every time I will also check that the festival matrix is ​​a request, it festival matrix is ​​a request, it festival matrix is ​​a request, it is printed, so We will not take it again, we will check all these conditions, let's go to the court here and keep this in mind, it is okay, then you must have seen the explanation in weeks, now see what I have done here, what is the actual result, if we assume that stringer from the team. If you have MT, then make anti in retail, it is okay, he had said this case earlier, then I took whistle and strip and showed you the secret, neither Hindu nor edition, I have anti you for now and I said for the character, see in 2015, it was Tulsi, wasn't it? So the C of CT means what we are seeing now is that we are keeping the value of smart. It is keeping the value of that character, so add one to the rally of the character. If the C does not get, this is the sentence of fashion. C N let us check. That is, if it is only a few then it is fine otherwise by default everything will be deposited starting from zero, otherwise this ultimate function is returning Mr. If you add one to zero then it will go and it will be for every character. Will it go to China or has it become a value pair? Now I have seen it in the team, Team AB is being formed, Given AC is also being formed, so I had one already required, you are already with me, then I am 0n all the others are requested. Now I have understood the length i.e. three, then I did it and Now I have understood the length i.e. three, then I did it and Now I have understood the length i.e. three, then I did it and accepted it as one answer. Now what will be the answer, actually it will be left and right increase, so I asked for both minus one so that the index should be outside. Second, what is the length of this answer. I can tell him. What was our answer in the beginning, Jahangir, you will see, you were coming from ends to five, EMABC and length are so far behind, that is why in the beginning I took length in favor of you, the tumor required minimum nine and we answered. If we assume that S is any electrolyte, initially what will be on our left will be zero and right click will be added. If we run it, we will run the loop on the right and the character will be cut here too. The character will be equal to such off site S. Is our big spring? So what should I do, just increase the value of C in its window, just like we were applying the vaccine here, the time has come with your face, there is a very divine character in the character, the time has become its value pair, now check that in this city. If that is a C request then it turns out to be our team too and also the account of both of them is same Gyani like mine was one in that one in this one too if it is so then increase the already plus equal to one so I was saying. Already if there is three, by covering one cord, already married is three, that is required in our required, then lunch is three, notes's AB, wow, wife's semen, then if all breed is also three, we are like this is our case match of already increment. What is happening is that the character is also in the city and both of them have the same account. Okay, so now we have to check boil already shell required means as much as such thing if both are three then check what is this and - Help Lakshya I have total length. Isn't it, when there - Help Lakshya I have total length. Isn't it, when there - Help Lakshya I have total length. Isn't it, when there is a zero index, then the length is taken like this, so this time I celebrated small earthen lamp shades in phase, it will always be in the starting, so turn off the answer by voice mail. In the five star team of the district like Kumar Saini, from zero to ₹ 5 in this. And zero to ₹ 5 in this. And zero to ₹ 5 in this. And make waves, which is Maryland, Edison, isn't it 5 - 06, so our length has become 6 from the answer key - 06, so our length has become 6 from the answer key - 06, so our length has become 6 from the answer key and minimum balance is required, now what will we do together ASW Anil Joshi's window, it has a window, it has ss7 image Belgium In the school on the left, we will do one of them, we will set the alarm - we will turn it off, set the alarm - we will turn it off, set the alarm - we will turn it off, okay, it does this every time, I will see it as bye during the day, okay, we have been lifted, right, if we put the value, then remove the floating 11. Were we not there, here in this all in city that if we found it like this inside the city and its value is in the window, its value in the window is less than the value of our city, what is this A S Tomar Bhidosa But if the value of left key is light then another character will appear in this LMB in the apps. I am looking for edible in that character. What are we doing in modern account? We are reducing it. At this time the account is reducing it and we are saying that s.l. I found another ad in CT, that s.l. I found another ad in CT, that s.l. I found another ad in CT, this account tells me that if his account is less than our city account, then what will we do now - make it already what will we do now - make it already what will we do now - make it already that we cannot do plus one, no, plus one happens only when his There are specialities, otherwise our left side will move one step ahead, what kind of separation should we tell, this dhamara will keep going on and the last hit that is going to come, hit the mail, there was a fit in the answer, there was a minus one inside the answer, now there should be a rally for the next flight. The value of the Pluto website will go, it will come in our last that BMC is from eight to whatever it is in India, it is okay in nine to twelve eight to 12 whatever and we will return it by taking NOC from the train and plus the difference if Let us keep this thing in mind that if there is no infinity left then who knows, then in such a case our answer will not be anything. This small code has already been included. I am showing it by commenting again that in the hotel in the evening. Yes, and we will keep doing it like this. Edit Question: Actually, it is a new day, Edit Question: Actually, it is a new day, Edit Question: Actually, it is a new day, but sometimes one is left in the night, which means that this is the beginning of a new day, so it has to happen, see you in the next class, friend.
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
231
hello everyone welcome back to my channel so today we are going to discuss another problem is power of two so it's a very easy problem uh in this problem we'll be given an integer and we need to return true if it is a power of two otherwise return false power of 2 means that this number n can be represented as 2 raised to the power x where is x where x is some integer so n can be n is a power of 2 so if we see if n is 1 then output will be true because we can represent 1 as 2 raised to power 0 if n is 16 then it is also the output is true because 16 is 2 raised to power 4 but when we have n3 so n is no 3 is not a power of 2 so we will uh return false so there are many ways of uh there are many approaches for this problem so we'll see few of the approaches so first of all let's say we have n as 16 so a power of 2 will be even always and c 16 can be represented at as 2 raised to power 4 so what we can do is every time we can divide sixteen by two we'll get eight we divide eight by two we get four we divide 4 by 2 we get 2 again and we divide 2 by 2 we get 1 so if the number is a power of 2 whenever we divide like we will divide it by 2 and ultimately we will get 1 so if you try doing this with let's say we have 17 if you divide it by 2 to 2 at the end you will not get 1 so if a number is power of 2 if you divide it by 2 every time we will get 1 at the end so this is one approach let's see the code for this so if you see if the number is 0 obviously it's not a power of 2 so just return false otherwise what we can do is we can run a while loop until n is not equal to 1 and divide it by every time by 2 and at a point of time if the number if the n is not divisible by 2 means it is a odd number hence it will we can return false otherwise just keep on dividing it by 2 and once this loop is finished means n has become equal to 1 so we can return true at the end so this is one approach so time complexity for this approach is o of n log n sorry so of log n uh log to base 2 n because every time we are dividing by 2 so the number is becoming half every time so now let's discuss another approach will be a constant time approach like all the time complexity will be o of 1 let's see how so see like if we have 16 this 16 if we do a log of this 16 like log to base 2 16 so now if we know that the answer for this will be a log 16 divided by log 2 so this will be somewhere log 2 raise to power 4 and this will be log 2 raised to the power 1 hence it will come out to be 4 right so it will be an integer now if we calculate floor of this number which of the result which we get from this that is 4 and if we calculate seal of this number 4 the result these will be equal only when only if this was a complete like it was if this was uh four right if it had been a decimal let's say four point something like four point five then floor will be different floor will be four if the uh if here it's four point five then floor will be four and seal will be five say hence they will not be different so this uh we can use this thing to check whether this 16 is a power of two or not if here it would have been 17 then this answer here will be some something in decimals so if this is in decimals then floor and c will never be same right so this way we can check and this will be o of one time complexity so let's check this also so this is like seal of log to base two and we are doing and checking the floor also so if they are equal means it is a power of two so if we submit this it's getting submitted so this was one approach so if we submit this is one approach and one more approach which we can see is let's say we have let's take 16 only or let's say we have four let's take a smaller number we have four now we know that four will be a power of two only if it has only one in its binary representation like that what does that mean so let's say for uh force binary representation is listener so now uh a number whose power of two will have only one obviously in its binary representation only one so we can check how many set bits are there one is the set bit zero is the inside bit so we can count how many set bits are there in the binary representation of 4 and if the number of set bits if the count of the set bits is equal to 1 hence it's a power of 2 so if you see like if you say 32 is 2 raised to the power five and it all if you re if you see the binary representation of 32 it also has one in its binary representation hence it's a power of two so if you want to count the set bits in a binary representation of a number there is an algorithm called carnegan's algorithm you can so you can first of all learn that algorithm using that you can find out how many count said how many set bits are there and once you know the number of set bits you can check if the account of set bits is one hence this number is a power of two so this is one approach one more approach which we can also use uh on that also we'll be doing bit manipulation so let's say we have four so the binary representation of four is zero one zero and let's say we take this is if this is n we will also take n minus 1 is binary representation so that will be 4 minus 1 3 so 3's binary representation is 0 1 so now if you do and if you do end of these what we will get zero means all zero is we'll get so this is also our approach you can use that if you need to check let's say you need to check 16 is a power of 2 or not you will see the binary representation of 16 and you will see the binary representation of 15 take and of both and if you get 0 as a result it means that 16 is a power of 2 16 is the power of 2 that means if we write it like this let's say n we n and we need to do n minus 1 so if this is if this comes out to be 0 means false so if this is true means what we'll do is see this will get a 0 so if 0 naught of 0 means 1 hence true so if this is true means this 4 is a power of 2 in order to like understand more let's take another example let's say we have 6 so binary representation of 6 is 0 1 0 and if we take a this is n so n minus 1 will be 5 so 5's binary representation will be 0 1 so if you do end of these you will not get 0 you will get this will be 0 this will be 1 and this will be 0. so you are not getting 0 in this case so if you are not getting 0 this means that 6 is not a power of 2 so this approach also we can use so this is also of a 1 a time complexity so see we can use this also so if n is greater than 0 and if this thing is true means n is a power of 2 if you submit this it's also getting accepted so we discussed four approaches in this video so i hope this was helpful please like and subscribe and i'll see in the next video thank you
Power of Two
power-of-two
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** 20 = 1 **Example 2:** **Input:** n = 16 **Output:** true **Explanation:** 24 = 16 **Example 3:** **Input:** n = 3 **Output:** false **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
191,326,342
260
hello guys mike decoder here so i decided to make some neat core problems because i'm running off ideas uh if you have any ideas for future videos leave it in the comments so let us see this problem given integer array numbers in which exactly two elements appear only once and all the other elements appear exactly twice find the two elements that appear only once you can return the answer in order you must write an algorithm that runs in linear runtime capacity and uses only constant extra space so linear complexity this means that i want to loop through uh the list so for i in list in nums for example i'm going to say if nums.count i if nums.count i if nums.count i is equals to 1 this means there is no repetition for this means that's our answer right so i can make here like an output list and i'm going to say here if it's only repeated once this means i want to output it so i'm going to append it to my list called output noms uh noms will count so i'm gonna append i and then here i return the output return output and let me run this code and it should work yeah it works great now another approach can be now this is like a more complex approach if you may say let us loop through the indexes of this list okay so this is 0 1 2 three four five i'm gonna say my first index is zero right so if i'm in index zero i'm gonna say if this index which is one uh is inside this list then it is repeated right so can't i say if nums i in nums i plus 1 till the end of the list if this is inside this then this is repeated isn't that logically correct yes if it's repeated then i'm gonna make a list here called occurrences this list is going to keep track of every occurrence made before so occurrences dot append nums i now i will keep track of all the numbers that are repeated if i don't do this i will run into a problem you see i'm saying here if this number is repeated in the list in front of it right so 1 is repeated here but is this one repeated here it's not so the program will treat this as if it's not repeated if i just do this but now that i'm appending it to occurrences i'm going to say here if this number is not repeated in the list in front of it then make sure that this number is not in occurrences okay if it doesn't occurrences then it's a unique number then append it dotted i'll put it append numsai and here we will return our output write our code we have a problem global name currencies is not defined i closed it incorrectly there we go this should work now run code there we go accept it so this is uh this problem guys hopefully you enjoyed and i'll keep doing some of these videos lit code this was a medium problem i will do heart problems in the next videos so hope you guys enjoyed i'll see you in the next one
Single Number III
single-number-iii
Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. **Example 1:** **Input:** nums = \[1,2,1,3,2,5\] **Output:** \[3,5\] **Explanation: ** \[5, 3\] is also a valid answer. **Example 2:** **Input:** nums = \[-1,0\] **Output:** \[-1,0\] **Example 3:** **Input:** nums = \[0,1\] **Output:** \[1,0\] **Constraints:** * `2 <= nums.length <= 3 * 104` * `-231 <= nums[i] <= 231 - 1` * Each integer in `nums` will appear twice, only two integers will appear once.
null
Array,Bit Manipulation
Medium
136,137
971
welcome to march's leeco challenge today's problem is flip binary tree to match pre-order traversal you're given the pre-order traversal you're given the pre-order traversal you're given the root of a binary tree with n nodes where each node is uniquely assigned a value from one to n you're also given a sequence of n values voyage which is the desired pre-order traversal of the binary tree pre-order traversal of the binary tree pre-order traversal of the binary tree pre-order traversal starts at the node pre-order traversal starts at the node pre-order traversal starts at the node and then goes left right any node in the binary tree can be flipped by swapping its left and right subtrees so for example at node one we can flip two and three to be three and two if we'd like uh see if we can do that to match our path and voyage now we wanna return a list of all the values of flipped nodes and if we can't find one then we'll have to return a list of negative one so we already know that we're going to be doing it that first search or breadth first search depending on whichever one you find more intuitive i'm going to go with def that first search this problem is very difficult to tell the truth and the reason for that is we need to figure out if we can actually do this pre-order we can actually do this pre-order we can actually do this pre-order traversal at every node we're going to have to be going down a single path but it's like we have to figure out if we want to go right left or left right or if that's not even possible so inside of some sort of global variable i'm going to make a list that keeps track of all the nodes that we've traversed if we found that we couldn't find one inside our condition i'm going to put a none inside of that list and that way we can track that and say hey you know in our path we couldn't find a value to match our path so that's going to mean we have to return a negative one we'll also have to keep track of the direction that we can go uh if we can go left right then we don't need to change the direction but if we have to go right left i'm going to put in some sort of variable that says go right left instead and keep track of that inside of our output so the very first thing we want to do is create some self variables i'm going to call this path and i'm going to call this current this one's going to be a list of all the nodes that we had to swap and this one's just going to be an index number of where we are currently in our voyage so now we need our depth first search and we're going to pass in the node the very first thing if not node or let's say our self dot cur like so voyage if self talk cur equals the length of voyage that means our algorithm is over so we can just return okay the second thing we want to check is to see if this node is equal to the voyage inside what we are in current because if it's not then that also means we need to end our algorithm here so let's see if voyage self.cur does not equal node.value then again we'll return but we'll also add to our self.path a none and this will keep our self.path a none and this will keep our self.path a none and this will keep track of later because if this was the case we have to say uh we couldn't find one so we'll have to return negative one now otherwise what we'll do is increase our current pointer by one because we have found that this node matches the one side of voyage and we'll also keep track of the direction that we want to go so i'll call this direction and this will start with just left to right which would be one so the first thing is do we need to swap well if we need to swap we can say check our no if we have a no dot left and no dot left dot value does not equal whatever we on our voyage self dot occur if this is the case then we know we need to swap so in our path we'll say append this no dot value and we will switch our direction to equal negative one i'll show you why we did this here the reason i did this is now we need to continue down our pre-order traversal right but which pre-order traversal right but which pre-order traversal right but which order do we go left or right to left and we'll say for child can make a list no dot left and no dot right if we found that we have to go the other way or we have to at least try the other way then we'll just this direction thing here we'll make sure to tear that and we just call our depth first search again with the node versus the child now we need to call our depth for search at the root and really it really depends here we either return the self.path all the lists the self.path all the lists the self.path all the lists of node values that we've swapped or if there's a none in the self.path or there's a none in the self.path or there's a none in the self.path or return a list of negative one so let's see if this works i believe this should return negative one does and go and submit that and there we go accept it so this actually ends up becoming of n because we only traverse we do traverse every node but we're only going to do it one time depending on which path we can take and it'll stop early if we find that we haven't been able to find one and we'll return negative one if none is inside this path so i'd love to say that i came up with a solution on my own i did not although my approach was very similar it was taking a little bit too long for me to get all the edge cases so i had to look it up but um my approach would have been similar i think i would have eventually got it i wish i had more time to go into like a deep dive here because this actually is a more difficult problem than it kind of initially seems so i hope this helps thanks for watching my channel remember do not trust me i know nothing
Flip Binary Tree To Match Preorder Traversal
shortest-bridge
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect: Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`. Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`. **Example 1:** **Input:** root = \[1,2\], voyage = \[2,1\] **Output:** \[-1\] **Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage. **Example 2:** **Input:** root = \[1,2,3\], voyage = \[1,3,2\] **Output:** \[1\] **Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage. **Example 3:** **Input:** root = \[1,2,3\], voyage = \[1,2,3\] **Output:** \[\] **Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped. **Constraints:** * The number of nodes in the tree is `n`. * `n == voyage.length` * `1 <= n <= 100` * `1 <= Node.val, voyage[i] <= n` * All the values in the tree are **unique**. * All the values in `voyage` are **unique**.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
522
hey everybody this is larry this is august 27th day of the august nicole day challenge congrats to yourself if you've made it this far you're almost to the end just a couple more days uh hit the like button hit the subscribe button join me on discord chat about this farm out of problems okay longest uncommon subsequence too given the way of strings just arrows return the length of the longest uncommon subsequence between them what is the longest uncommon subsequence negative one ever done subsequent an uncommon subsequence between a way of string is a string that is a subsequence of one string but not the others a subsequence of a string s is a string that can be obtained by deleting any number of characters from s abc can be do what does that mean i still have to read this uh longest uncommon subsequence can you give an example okay i guess this is an example but abc this is these are too many words and to know what they're really asking for okay i usually saw this live so it's a little bit slow just watch it on a faster speed let me know what you feel um and apparently this is one of the slower ones because reading is hard and i just woke up okay subsequent the longest uncommon subsequence between them what does that mean it's a string that is the subsequence of one string but not the others isn't that just the longest what is the constraints oh okay so again the strings are very low so we can force it but it seems like it would just be the longest string right as well you can do the long string and then you do a naive check just to see that if the longest string is not identical to another string and then you kind of go down the list that way yeah right i think that's right uh this is such a reading problem that i'm not sure um but given that each string or there are only 50 strings and there's only 10 in the longest string i'm just going to do it in the brute force way the first thing to notice is that we can sort by um the length of the string um reversed and then you can probably do something smarter about this with i don't know anything but like i said each character each string only has 10 characters so i'm just going to do it naively for word so at the very end which are negative one but i mean they have to be identical right for it to be not to return a negative one in this case so let's just say good is equal to true i mean i think in theory you can do something like forward two um hmm maybe i could handle this a little bit better uh let's just call it inj i've been wait i've been calling everything index these days kind of i don't know if that's easier to read um what's it called range of from i plus one to n where n is the length of strings then if word sub i is equal to sub j then good is equal to force and the reason is because if so i by definition has to be longer than or longer or equal to j right because and if the length of word j is smaller than i then obviously it's not going to be inside it um now i think that doesn't i mean it makes sense going that way but i think you still have to check jay with his smaller eyes so i think this is this logic is reasonable but not actually okay bye this is still good if no good no not good no good uh not uncommon if uncommon so our candidate is currently i and we're seeing to see if word i lives within word j uh if this is true then good is equal to false we can break if good then we return the length of word all right then we'll do just do this uncommon thing um what's it going i forget which hmm i guess it's not really a needle in a haysack but let's just call it uh x y uh too lazy naming things is hard and then now we can just do index x zero and x y zero um maybe length uh oh yeah we can just assume that the length of word sub j is greater than or equal to length of oops uh length of word sub i otherwise yeah otherwise just smaller than you can't really fit into it um think of y oh no length of x while i y is less than length of y and hmm this is just a two-pointer thing but i'm this is just a two-pointer thing but i'm this is just a two-pointer thing but i'm just really bad at implementing right now um yeah okay and uh let's see what am i doing i think it's just my in my wearable names are very terrible right now to be honest which is why um i think this is roughly right my coating is very terrible this morning i don't know if this is right though um because this is so awkward now dad get those signs well i think this is one this is true and this is four troops because this is true we're able to get to the end of the other string oh wait no we get to the other string then i think i had to think about how i'm handling this um so if you're getting through both strings that means that they're not in loop so i think this is good this should be i think my logic is just good uh foul let's go to force to go to true if not found okay i think this is good okay maybe not string in text how can this be our folder uh whoops wow how did that happen okay it's because i never used this stir spring how did that even won the first time okay anyway okay still long but let's see if it goes to the end and they don't care that's just true otherwise it's true sorry friends i think i feel like the logic is easy but i'm well i mean easier this is such a weird problem in general but this part i should not have any trouble with oh okay that's just dumb um if i it's not your j and this okay i should yeah because i switched it from i plus one to n and i didn't think about i just didn't think it through uh okay let's give it a go i don't know if this is right because this reading of this problem is just so such a weird problem to be frank but uh okay seems like it's good so i'm happy about that um you can do some optimizations for sure for example i think you can and write this in a way that is much smarter um but given that n is 50 and um l is 10 this is going to be fast enough and you don't even need to sort i think to be honest i just sorted it and the way i sorted you can actually early terminate if the length is smaller but we i didn't actually implement that so yeah um what is the complexity this is o n so this is n square um at least and uncommon is also of l so this is going to be n square l uh o of n squared times l and in terms of space we don't use any extra space i guess we sort so which we don't really use so you can remove this line and pretend this line doesn't exist and then this space is going to be constant um yeah i guess that's all i have i don't know this is a very weird problem i think it's just one of those real logic ones i can imagine a lot of people are not fans of this one um i think it's just the wording is just so i don't know maybe i just woke up too so i don't know but uh but yeah let me know what you think because this is definitely a weird one this is one of those like tricky cutesy silly problems uh i will see you later take care uh stay good stay healthy have a great weekend i'll see you later and degree mental health bye-bye
Longest Uncommon Subsequence II
longest-uncommon-subsequence-ii
Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`. An **uncommon subsequence** between an array of strings is a string that is a **subsequence of one string but not the others**. A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`. * For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string). **Example 1:** **Input:** strs = \["aba","cdc","eae"\] **Output:** 3 **Example 2:** **Input:** strs = \["aaa","aaa","aa"\] **Output:** -1 **Constraints:** * `2 <= strs.length <= 50` * `1 <= strs[i].length <= 10` * `strs[i]` consists of lowercase English letters.
null
Array,Hash Table,Two Pointers,String,Sorting
Medium
521
134
hello everyone welcome back to cooling Champs in today's video we are going to be solving the problem gas station so let us first start by understanding the problem statement given there are n gas stations along a circular route where the amount of gas at the Earth gas station is gas of I you have a car with unlimited gas tank and it costs cost of Eye of gas to travel from ith gas station to its next gas station I plus one the station you begin the journey with an empty tank at one of the gas stations given two integer arrays gas and cost return the starting gas stations index if you can travel along the circuit once in clockwise Direction otherwise return -1 if there exist a solution it is -1 if there exist a solution it is -1 if there exist a solution it is guaranteed to be unique so the Crux of the problem is we are given with two integer arrays gas and cost gas is nothing but the amount of gas is provided to us when we reach a gas station and the cost is nothing but the cost or the gas will be required to move from one gas station to another and we have to find a gas station such that if we start at that gas station we will be able to uh circuit back to that gas station um it is guaranteed there is only one such gas station and if we are not able to find such gas station we have to return minus one so let us understand by looking at the examples so let me share the Whiteboard and now in the example one we are given with the gas one two three four and five cost areas three four five one two so let us start from the zeroth gas station so at zero at gas station we initially fill up one gas point and then we require three gas points to move to the next station uh the total will be minus two uh since there is not enough cash to move to one station from zeroth station so we do not consider zero as our answer and then we move to the first station let us move to the first station initially at first station we fill up two points and then we require Four Points to go to next station since we do not have enough gas we cannot reach from 1 to Second gas station so one cannot be our answer and let us start it second gas station at second gas station initially we fill three gas points and we require 5 gas points to move to the next station so um we are here also we are short in gas so we don't have enough gas to move to third gas station from second gas station so second gas station cannot be our answer now let's come to third gas station in third gas station initially we fill four gas points and we require one gas point to move to the next station so since we have enough gas points to move to the next station we go to Fourth station with three gas points and now we fill up 5 gas points and we require two gas points to move to the next position which means 8 minus to six so here we still have six gas points um so three will be our answer so from 6 here again let's see six from six uh here from uh for 0 to 1 we require three gas points so six minus three will be three and again here for a 6 minus 4 okay uh here it will be 3 minus 4 right sorry so this will be we have uh six points at zero and at zero we require how many gas points three gas point six minus three will be 3 and we fill up one gas point so plus one equal to four we move here with four gas points so 4 minus we require 4 gas points um to reach next gas station and we fill up two so we still have two gas points left so we come here with two gas points and at two we fill up three gas points and we require five gas points to move to next gas station so 5 minus five uh we will have zero when we reach 3 so we are able to Circuit back to three since so that three will be our answer and let us come to the second example here so in second example if You observe we have gas 2 3 4 and cost as cost areas three four three so what is the total gas we have 2 plus 3 plus 4 equal to 9 and what is the total cost we have 3 plus 4 plus 3. so here if we observe total gas and this is total cost total gas is less than total cost so uh the gas we have is less than the gas we need so we will not be able to Circuit back uh from whatever gas station we will start we will not be able to end up at the gas station because we don't have enough gaps in the first place so we return -1 in this case first place so we return -1 in this case first place so we return -1 in this case um so now that we have understood the problem let us see how we can solve the problem so the name or the Brute Force way of solving the problem would be uh what we have did here right I hope we start at each gas station and we started in gas station and check if we can look back or circuit back to the gas station uh what will be the time complexity of this approach we start at each gas station we Loop through all the gas stations so it will be o of n Square so the name or the Brute Force way of solving the problem is to start at each station and check circuit if we can circuit back or not this problem uh this approach will be of N squared but can we optimize this approach let us see uh let us take another example let's say we have five gas stations let's say we can I reach from a gas station to B gas station and big gas station to see gas station but we cannot reach from seed gas station to leave the air station so what we can observe here in the Brute Force way what we do if we fail so a we do not consider a then we move to B and we again check if we can reach we can circuit from B to B but if we observe uh let's say uh we fail at C to D and we again started B uh what is here uh if we go from A to B then we know we are carrying some positive or zero gas to B since we are going from A to B we know we are carrying some positive or zero gas to B so with this positive or zero gas we are not able to reach from B to D so we are saying we cannot go from C to D so we are not going from B to d as well so if we cannot go from a to d we can say that we also cannot go from B to D and C to d as well because we carry some positive or zero gas to go from A to B with this positive or zero gas only we are not able to go from B to C and C to d c to d right c2d we cannot go from this positive or with carrying this positive or zero gas so without this positive or zero gas also we will not be able to go from C to D hence we can say if we cannot go from B to D we cannot go from a sorry we cannot go from a to d then we can say we cannot go from B to D and C to D so this is the catch in this problem so what we can say now if we fail at C to D what we say we start from D we do not consider B and C as well we start from d and we then check if we can go from D to e and if we can go from D to a then D will be our answer if we cannot go from D to e then e will be our answer because here are here also if we can go from D to e we carry some positive or zero value so with this positive or zero value we should be able to Circuit a from E to A to B and B to C if this will if we cannot go from here to here then without this positive or zero value also we cannot go from each way since we know that we will have if the solution is present we will have a unique solution so it will be either D or E so if we can go from D to e it will be D or else it will be e so this is the approach I hope you understood the intuition behind the solution so let us now code it up so firstly we uh so let us first take how many gas stations we have yes dot length and then what we have to check if we can uh so cute we can complete a circuit so for that we have to check total gas let's compute the total gas and total cost so first in time equal to 0 I less than n I plus and total gas plus equal to gas of I and totally cost of course plus equal to cos plus I so now we check this total gas is less than Total Core total cost in this case we know we cannot circuit back so we return -1 now cannot circuit back so we return -1 now cannot circuit back so we return -1 now we know we can so cute we can complete the circuit now what we do we have a runny examine gas value and we also should have the starting position this will be our result as well so now we have been within track you on the gas stations and we now um what we do here we increment the gas so what will be the gas now the gas will be we add the gas and we subtract the cost and now we have to check if running gas of I is sorry the running gas image so the running gas is less than zero X less than zero uh we know we cannot um start from this position so we update the starting position to be I Plus 1. and now we finally return the starting position let us run the code and see if passes all the test cases okay we are getting the output 4 and we want 3. so where do we do wrong yes here we have to reset the gas value whenever we know we have less gas value we have to resort and we have to update the starting position so it got access it got accepted for the sample this let us submit it passes all the test cases let us look at the time and space complexity since we have we are iterating over all the gas stations once the time complexity of the optimized approach will be of an and since we are not using any external space we are only using the constant variables the space complexity will be o of 1. um so in brief first we are checking if we can circuit back or not uh how we are checking that so total we are calculating the total gas and total cost if total gas is less than total cost we cannot circuit back uh so we return minus one and if we can circuit then we are calculating running gas we are keeping track of running gas and starting position we iterate over each cast station and we keep track of the running gas if running gas gets less than zero then we are presetting the running gas and updating the starting position will because we know if we are not able to go from the starting position to certain position we cannot go from the middle positions as well so we update the starting position to bi plus 1 and finally we return the starting position so I hope you have understood today's problem if you did understood make sure you like this video and if you have any doubts feel free to comment down below I will try to answer as many comments as possible and do subscribe to the channel for more daily videos thanks for watching bye
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
1,261
Hello everyone today test the camera list number 1234 problem solved I know the problem is that the account is ripped from the account so the problem was first a brother sister brother that the commission said to make active directory like they loot the person dishoom full feel good condition The second conditioner bala se ke per no dj more domestic tha ke which most tomato follow sapoch unity ke ka intake bala se place nodal left side whatever na ho praise loota hai be tu * rupees praise loota hai be tu * rupees praise loota hai be tu * rupees class 1o Maa Karma removed the market were Detective Lal Mirchi 96 tayori le factory tha ke left notification nodal ministry 299 two in tracks plus one 106 fruit one Sharma ne khoon yeh first hamar rahalu salman ko to hum 10 inches plus one ki condition case from his towel come to show the number in condition Bole jo di thing notice was spread ki aven air right side Chaudhary Nahid Khan right Jyoti ko Sarthak hai tar Hello abe tu in two Ravana's banner and China Bullet - Vande has replaced China Bullet - Vande has replaced Guava from Amazon. I should immediately visit the portal of the temple. Apart from tomatoes, there is energy thing in it. It had noise protector failure - Wankhede tension ban. With the protector failure - Wankhede tension ban. With the protector failure - Wankhede tension ban. With the help of Cheetah Guava, 9600 kilos of electricity was made with yours. Compare with whole 100 compare according to Goregaon, Sita by the way, this is the treat loop, tractor side, neither side, left side, but do not forget the locks, so that the attitude towards movies is class one, okay, so HE file is not android, Shravan is foggy right side, this person's Play list ko bajao ko tawe ke ghar mandawat se to hum raghwani ke aur planets se paise next hamaraaj awadhi translation awadhi a routine sa back hamara balam ke khandwa through to the top o mein taale routine mango to hum paise one ok pehle reptile ki naal Na Taale Sector-132 In Two Sector-132 In Two Sector-132 In Two Vice President's swollen silent exam on the pan is more rough input which gives pleasure only to see Hey Mohammed Rafi Daya Se Bigg Boss Do not forget to subscribe Subscribe Problem was solved 2010 Ludhiana See the example was that our tummy is fine Daya Se was like this Camera Original Chanakya Niti Find Element Wants Air MP3 Towards 1659 E So Finally Man Contractor Sweet And Ludicrous Now Them Beetroot Path To An Extent Our Channel That Were Illegally Set Root Neelam And Samra Amar Twitter Before America A I stayed with the rich, router Meiyappan Pathan and the keepers of Ulta - 10 keepers of Ulta - 10 keepers of Ulta - 10 ki end Khane Hindu bola se auspicious initial state ad Shekhawat Saheb looted money from the den of Hindu lions 10 days 2012 write something, number 90 is on quora or else this marking is ours. The channel came that what has become of this relationship, they were made to run fast, actor function, quality products, tractors, Amitabh Pir and subscribe, thank you, MP, name them, it was the fact that when there is uniformity in ash root without medium from outside, if it is a big religion. Which regular second ODI live on I college picture talk function we made like they get high fever moisture sky kuri off function turn name giving return with one finger to bona fide sea tower senior actor shri rudra morning hai handed over to By minute voice, there is no dizziness in Pratham, when the day sets, Pandey brother, get Taliban done for us, we auditioned for Lid Ko Pratham 2019's Jo Root Dot Loop 99 Nihrib Luta De Hai Tu In Two X Plus One by Dhir Tanwar and The route. Point to route that those people had opened the class, I was Mukesh Barala function quality cheetah rain route dot right cc the right time hai paddhi dila tawe a modified guest's modified ki a tha amit hai to FD ka pehla me bread bluetooth our road To keep help is on the pan 1968 our this function contractor time limit works a guy's find value tarmani that our things fine middle aged 98100 9th me kar function eye shadow were American actor function made or not made and from is bull type The function of se me aa find salon extra function almond and parameters university bill form tay mir taqi target ko with sapphire do a target's parameters is blue at this time so American corbo egg apna career function sa scientific a fine billu ke Comedy is successful to some extent in this pond, the medicine is the leg, the heart, the fine fruits, we save the nationality, friend, the target of the first floor is that they are a potato, our functions are meaningful, that is friends, the salt is a salt, today it is a function, anger, constipation, this is of value. While drinking alcohol, subscribe to the leopard, Tarzan was there, I will check the pride of both of you in Amravat, that is the route, the day is coming, the salary thing, which was the day, first of all, I pressed my finger under the desire to make you, that from here, create router Bhailu jo Dana target. Alas, such a period is router death, Amit goes happily so that Gandharva has written on Pimple to the limit, Arjun day has come, Amra Pali Tehsil's Ko has to hear the cricket voice, then left side and right side didi's travels. That whole tree was ahead for these fruits. A fine balma daru dot loop fast bowler is a target reader and student. Reader is very a fine jeweler middle rudd was right so aligning and west richa's travels would have been along which Korba and this will mix. Now achieve the target quickly, I meet you with electronic media and final Ahmed Irfan Function Tamkor dekh to and ko takkar kar 2 ok me submit quota, what kind of actress is this Vidya Mandir quota accept one gas
Find Elements in a Contaminated Binary Tree
swap-for-longest-repeated-character-substring
Given a binary tree with the following rules: 1. `root.val == 0` 2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1` 3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2` Now the binary tree is contaminated, which means all `treeNode.val` have been changed to `-1`. Implement the `FindElements` class: * `FindElements(TreeNode* root)` Initializes the object with a contaminated binary tree and recovers it. * `bool find(int target)` Returns `true` if the `target` value exists in the recovered binary tree. **Example 1:** **Input** \[ "FindElements ", "find ", "find "\] \[\[\[-1,null,-1\]\],\[1\],\[2\]\] **Output** \[null,false,true\] **Explanation** FindElements findElements = new FindElements(\[-1,null,-1\]); findElements.find(1); // return False findElements.find(2); // return True **Example 2:** **Input** \[ "FindElements ", "find ", "find ", "find "\] \[\[\[-1,-1,-1,-1,-1\]\],\[1\],\[3\],\[5\]\] **Output** \[null,true,true,false\] **Explanation** FindElements findElements = new FindElements(\[-1,-1,-1,-1,-1\]); findElements.find(1); // return True findElements.find(3); // return True findElements.find(5); // return False **Example 3:** **Input** \[ "FindElements ", "find ", "find ", "find ", "find "\] \[\[\[-1,null,-1,-1,null,-1\]\],\[2\],\[3\],\[4\],\[5\]\] **Output** \[null,true,false,false,true\] **Explanation** FindElements findElements = new FindElements(\[-1,null,-1,-1,null,-1\]); findElements.find(2); // return True findElements.find(3); // return False findElements.find(4); // return False findElements.find(5); // return True **Constraints:** * `TreeNode.val == -1` * The height of the binary tree is less than or equal to `20` * The total number of nodes is between `[1, 104]` * Total calls of `find()` is between `[1, 104]` * `0 <= target <= 106`
There are two cases: a block of characters, or two blocks of characters between one different character. By keeping a run-length encoded version of the string, we can easily check these cases.
String,Sliding Window
Medium
null
956
hello friends today let's resolve the tallest billboard problem previously we solve it via that first search but currently it will cause time limited exceeded so today we will solve it with dynamic programming so let's recall what is the question about we are given an integer array which called the row rows um and we have two uh dividing into uh actually not divine because we can um we do not need to use all the roads we can let uh unuse some ropes so we just need to build two disjointed subsets which they will have the same sum and we want to make the sum as large as possible so let's see these three examples in the in this example we can divide into two sets and each of them will have the sum six so we use older routes in this example we don't use the one two three five wheel b ten and the 4 and 6 will also be 10. for this example we cannot make it because we only have two rows and they have different lengths actually heights so how do you solve it previously we solve it by uh we have two buckets or uh two sets left and right and for each road we have three cases why is use it for the left bracket the other is um is we use it for the right market the third case is we don't use it we just try every possible um combinations and we use some pruning but currently it will not parse the case it let's see how to solve it via dynamic programming we also have two sets right left and right but in this time we distinguish these two sets by which one is a higher and which one is the shorter so these are two different sets if we want to solve it by dp the most important thing is what is the transition function and what is the initialization in this case we have many variables one is their height we don't know what is their height and what is because we want their height as large as possible and they have they must have two equal heights so how about we just use the height difference because in that case if we use these two sets height difference at as the key then we know our final result will be dp0 that means this two sets has the distance of zero so that's it but what about the maximum distance for this example if the roads are this and we know their sum is 12 then the maximum difference will just be 12 because we put the uh their rows in the short set and put all the 12 in the higher set so this is the maximum distance so for ending roads we know the er either size is just the sum plus 1 because 0 1 to 12. and for the initialization we first initialize older dp to negative 1 because we want to get the maximum height and we initialize two negative one and the dp zero will be zero that means if we cannot make any um assignment then dp zero just be equal to zero just like this example so what does dpi means i is a height difference of between these two sets dpi is the maximum common height what does that mean actually when i equal to zero this dpi will just equal to the height of these two sets but other cases it is equal to the shortest which of these two sets so it is just the maximum common height which is the shorter height so when we have to iterate each row we have three cases one is put it on the higher set one is pretty on the shorter side the other is unused so when we put it on the higher set what should we change that will be dp i the difference dpi plus the road we should to change it to what that will be the maximum of this dpi plus road and the shorter height why because as we said is the maximum common height so when you put that road on the higher set the height of this shorter set does not change so it should make sense to the when we update the dpi plus road this is the shorter one so what is the current mean the current is the current state of dp because in the this part we change this dp so in order to use the kernel state we should use a column just like the current screen shot of this dp array so what is the current i means the shorter one because um because the current i is the distance current i just means the maximum common height which i said many times is the shelter height so when we put the road to the shorter height what should we update it will be the i minus road because we don't know which is higher which is the road or the shorter one so we just use distance minus road so why does it matter and what should we update um because uh when we add it to a shorter one we should update the distance minus the road with whichever is larger we don't know whether it's the higher uh larger or the shorter plus road is larger so we just picked its minimum because as i said it's the maximum common height so which it should be decided by the shorter one so we just need to compare this to height for the higher one is the height is equal to current i plus the i because current ice is the shorter one the current i plus i and four this one is just the short one plus road that is current i plus the road so just pick the road and i minimum so that's it we updated it so this is the transition function when we put the road on the higher one we update i plus the road it will become the maximum of this or the shorter one when we put the road on the shorter one we update the absolute value of i minus road it will be this one or current i plus minimum road or minima i a current i plus road is the shorter plus road current i plus i will equal to the higher set height so that's it let's convert it to code so we have to get the sum and we iterate the road sum plus the road and we get the dp the size will be sum plus one do not forget to do the initialization field the dp negative one the dp0 will equal to zero and then four uh we iterate every rows and then we get the current column will be current dp column and therefore i will start from zero i will let's record then some minus road because the total size of this dp will be sum plus one so if we just use some minus road we can equate i plus if the current i less than zero we just continue because that means the maximum height is negative otherwise we update the two one is we'll put road in the higher one that will update dpi plus road and the shorter one current high or dpi um actually mass i minus the road there will be mass max dp mass absolute value i minus road the other one will be the current i plus whatever mini minimum which will be the i or road so in the end just return dp 0 thank you for watching see you next time
Tallest Billboard
number-of-music-playlists
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`. Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`. **Example 1:** **Input:** rods = \[1,2,3,6\] **Output:** 6 **Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6. **Example 2:** **Input:** rods = \[1,2,3,4,5,6\] **Output:** 10 **Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10. **Example 3:** **Input:** rods = \[1,2\] **Output:** 0 **Explanation:** The billboard cannot be supported, so we return 0. **Constraints:** * `1 <= rods.length <= 20` * `1 <= rods[i] <= 1000` * `sum(rods[i]) <= 5000`
null
Math,Dynamic Programming,Combinatorics
Hard
null
277
foreign Solutions are created Microsoft and my aim is to empower every single person to be better at technical interviews keeping with that goal in mind today we are going to do a very interesting lead code problem so let's get started with that so today we are going to find the celebrity lead code problem and if we see some of the popular companies the problem has been asked that companies like Amazon LinkedIn Pinterest Microsoft Facebook Apple Snapchat Google Uber and Goldman sex so basically all the popular companies have asked this question so I'm going to pay my utmost attention I hope you also enjoy the video this has to be one of the most interesting problems I have been able to find so far if you look at this a lead code categorized this as a medium problem if you try to understand the problem statement and try to think about it you will feel like this is actually a hard problem and once you put like some more thought into it you are actually going to feel that this is actually an easy problem so in my opinion this is actually an all-in-one problem let's actually an all-in-one problem let's actually an all-in-one problem let's understand the problem statement to go further deep it says that suppose we are at a party with n people and the names of these people are the numbers so basically numbers from 0 to n minus 1. so say for example we are in a party with four people basically the people are going to be 0 1 2 and 3. so these are going to be the four people now we are told that in this party there may exist so this is an important part that there may exist which means there might be a celebrity or there might not be a celebrity okay now we are first of all given that what the definition of a celebrity is that cell that every single person in that party knows who the celebrity is the second condition is that celebrity does not know and any single person in that party which is how typical celebrities are so now given these two definitions first of all we are told that we need to check that whether there exists a celebrity or not and if there exists a celebrity uh basically we can uh we need to find out who That Celebrity is the question is how we are going to find who That Celebrity is well definitely over here the relationship is based on either people knowing who the celebrity is or the fact that celebrity knows no one that everyone knows celebrity and celebrity knows no one right now at our advantage we are given a methodology where we can check between any two entities whether they know each other or not we have a method Boolean Knows A to B which defines that whether a knows b or not if a knows B if this gives answer true which means a knows B if this gives answer false which means a does not know B and why we are using that because the only relationship we have to identify whether a person is a celebrity or not is by the amount of people know them or the amount of people they know and in this case we either need to find the celebrity or we need to return -1 if celebrity or we need to return -1 if celebrity or we need to return -1 if there if no celebrity exists so I know this is a little bit complicated to understand but let's try to see some examples for this problem okay so in the problem we are actually going to have an input that looks like this uh where in this input we are given a list of list that contains some values uh that defines the relationship between any two values that whether they know each other or not now the thing is this input is kind of messy so I am not actually going to show you uh examples based on this exact input I'm actually going to show you in the base of something that is easier to visualize so this is the same input I took from here but I have actually converted it into a 2d match Matrix and basically as an input we are given a graph or we are basically given an adjacency Matrix okay so for this adjacency Matrix uh we based on this adjacency Matrix we are given two entities we are given a person and we are given whether that person knows each other or not this diagonal line is always going to be one because that defines that whether person zero knows person 0 or not whether person one knows person one or not things like that and that is always going to be 1 so we can simply ignore this one these this serves no purpose uh the important thing in this case is this defines that whether person zero knows person one or not so this answer is one which means that person 0 knows person one let's try to find who the celebrity is in this problem right so in this case uh we are given basically three percent so we can actually create a graph that looks like this of three person and we are going to name them as 0 1 and 2 right another thing is relationship between them is actually going to be the relationship defined by an edge where a edge would represent that whether one entity knows the other entity or not or one node knows the other node or not and this is going to be a directed Edge why because it could be possible that 0 knows one but one does not know zero so we cannot just simply have an undirected edge we must have a directed Edge in this case so let's try to do that as well so if we draw it from this graph okay 0 this does not matter these three values so we'll just ignore them let's just start 0 with 1 so 0 knows one right so which means zero knows one yeah we mark it now does zero node two no zero does not note so there is not going to be an any Edge now whether one knows zero no one knows no one does not know zero and one also does not know two so one does not know any one now in this case whether two knows or zero yeah so 2 knows zero that is good and whether two knows one yeah two also knows one so that is also good and two nose two here that is true so we can ignore that in this case if we see the two definitions of a celebrity that everyone knows who the celebrity is and celebrity knows no one at the party so definitely in this case we can say that hey if we check out the input for this value number one it knows itself but the thing is that is not the point it the point is whether it knows if anyone else at the party or not so one does not know anyone at the party that is true and also zero knows one and two also knows one which means every single one who is every person other than one knows who the one is and one does not know anyone which means one perfectly fits on our category of celebrity and in this case one is going to be celebrity so we will simply return one as the answer and this is what we need to return okay let's see one more example in this case again 0 1 and 2 oh let's draw three lines now ignore these three cases and zero knows uh one no zero knows two yes so zero knows two okay does one node two we have one also knows two that's good now whether two okay two knows zero in this case two knows zero and uh two knows one no in this case can we find any celebrity actually we cannot find any celebrity y because in this case Okay zero and one both of them know two so that is good two qualifies for one of the property of being a celebrity the thing is second property of being a celebrity is that it has to know no one at the party but in this case who actually knows who the zero is so because to know one person two does not qualify for the second entity of our answer so in this case uh we cannot find any celebrity so because there is no celebrity present we are simply going to return -1 is the answer and this is what return -1 is the answer and this is what return -1 is the answer and this is what we need to return okay so first approach is a Brute Force approach in The Brute Force approach what we are going to do is we are simply going to check that whether all the person that are given can any single one of them is a celebrity so for one by one we are going to check for every single person whether they are celebrity or not so in this case what we are going to do is first we will take consider person zero okay so for the person zero we will try to see whether zero is a self BT or not how can 0 be a celebrity if everyone else knows who the zero is and 0 knows no one so in this case we can see that zero knows someone so 0 is not a celebrity now we will have to check whether one is a celebrity or not so in this case Okay one still knows someone so one cannot be a celebrity but and in this case we'll try to see whether 2 is a celebrity or not so two knows no one and uh let's see that if everyone knows two or not so this one does the nose too but this one does not know two so two is also not a celebrity so in this case we will return a minus one and this logic leads us to the correct answer so some maybe if you make some modifications or tweaks it can be an acceptable solution as well the thing is this is still not the most optimal way to solve this problem so basically we would end up solving this problem in Big O of n Square time so which is not too bad for some of the problem but it is really bad for this problem because this can be done very efficiently with other methods so let's try to see what that other methods could be so in this scenario if we see okay 0 knows one and two so zero knows one and two right uh same way one does not know anyone and two knows one and uh one and zero so two no zero and two knows one so is basically answer is going to E1 that is a given fact the thing is uh what is one smart trick we can use the smart trick is the nose function that we are given in the input that is there for a reason and what nose function does is that if we provide any to Value say for example if we provide the values of 0 and 1 it is quickly going to tell us that whether 0 knows 1 or not so in this case Okay zero knows one that is a true fact now the thing is if we know for sure that 0 knows one what is one thing we can say for Guarantee or for certain city that 0 cannot be a celebrity why we can say that because remember the definition of a celebrity is that everyone knows the celebrity and celebrity knows no one which means in this case if we try to find uh or if we try to see this nose function between 0 and 1 and the answer is true if the answer is true definitely we can say that 0 cannot be a celebrity which means we are eliminating 0. now what could be the second possibility could be say one example if we try to use the NOS function or a values 1 and 2. if we try to use the function 1 and 2 knows that the answer is going to be false why the answer is going to be false because 1 does not know 2. if 1 does not know 2 what is also one more thing we can say for certainty well we can say for certainty that in this case 2 cannot be celebrity Y 2 cannot be celebrity because we found at least one element that does not know two and in order for 2 to be celebrity has to be known by everybody else in the power so because we find one entry over here who does not know two we can say for sure that 2 is not a celebrity which means depending on the result of this nose function if the value is true we can eliminate one value that is the first value in the nose function if the value in is false we can eliminate the second value inside this uh given input which means with every single nose call we are getting rid of one element so in this case after just making two calls we were able to get rid of 0 and 2 which means if there exists a celebrity it has to be one so now all we need to do is that since this is the last item or last value pending do we need to check that whether everyone knows one or not no why because since we know for sure that these two are not the celebrities right so all we will have to worry about is that whether one knows uh no one if one knows no one which means one has to be the celebrity if one knows at least one person which means there are no celebrities inside this input and we can simply return -1 and this is the whole simply return -1 and this is the whole simply return -1 and this is the whole logic behind this problem let me try to explain very quickly with a big example so now we have bunch of different values over here basically we are simply going to use the nose function and we are going to go through every single value and try to see whether it knows the next value or not so first we'll try to see that whether the zero knows one or not so and we can ignore all of these values because diagonals doesn't matter we do not care if they know their own self or not so in this case Okay 0 to 1 0 does not know 1 which means we can say for sure that 1 cannot be celebrity if one cannot be said be celebrity we can simply skip over to the second value now in this case we will check that whether 0 knows 2 so in this case 0 to 2 0 knows 2 so because 0 knows 2 we can say for sure that 0 cannot be a celebrity so we ignore this now we are at this value number two so we'll try to see whether two knows 3 or not so 2 to 3 if we check okay 2 knows three so if two knows 3 definitely 2 cannot be a celebrity so we will ignore that now we are at this value number three so we will take check for three to four so three to four if we check yeah three knows four so in this case three cannot be a celebrity because three knows four because of this value now we are at this four position number four to five so if we see four to five so four to five uh this value is actually zero which means four does not know five so because four does not know five cannot be a celebrity so in this case we have actually got rid of all of these elements and only fourth value spending so now we know that if there exists a celebrity it has to be four otherwise there are no celebrities so now we are simply going to check that whether 4 knows anyone or not and for that we simply have to do one check at this fourth row to see whether apart from 4 by itself does it know anyone else and it knows no one so definitely for uh or is the only candidate left and 4 knows no one so in this case 4 is definitely our celebrity and this we can simply return as the answer and this is the whole logic behind our answer say for example in this case by chance F4 knew this value number one if this was answer one then simply we can say that okay 4 is also not a celebrity and we can simply return a minus 1 in this case the thing is because this value is actually 0 so in this case answer is actually going to be 4 and we are solving this problem most efficiently if we see time complexity in this case the time complexity is actually going to be big of N and if we see space complexity well apart from using couple of variables we are not using any additional space so space is actually going to be constant first I identify few things so I created a new Global integer to use the number of people and I have assigned it the to the value of N and basically in the problem we need to resolve this fine celebrity problem uh and also for this problem I have created is the celebrity a helper method so that is going to Define that whether any single candidate that we have been able to identify from this fine salivary method if that is a celebrity or not and now first let's start implementing this find celebrity method and then we will Implement our is celebrity method so first of all we are going to initialize a variable called celebrity candidate now we are going to run our for Loop and for every single value we are going to check or we are going to call our nose function and for the nose function we are basically providing the value of the celebrity candidate and the value of a current I now depending on the answer we get back we are going to update the value to the I so what this is going to do is this is simply going to eliminate every single value for us except one last remaining candidate and that we are going to consider as the celebrity candidate and once we get out of the loop all we will have to do is we will have to call our is celebrity method if this value is actually true if this value is a celebrity we are going to return this and if that is not the case we can simply return -1 now in this method we simply return -1 now in this method we simply return -1 now in this method we will first of all run a for Loop inside the for Loop first we will have to check that if the given value of I is equal to J which means we have found a diagonal value so in this case we simply ignore that and if that is not the case we are going to check that whether J satisfy all the properties of being a celebrity or not if any of these is true we can simply return false and if that is not the case and if we get out of the loop we can simply return to and I think this has to be the whole logic behind this in uh input so let's try to run this code scenes like our solution is working as expected let's submit this code and our code runs pretty fast compared to a lot of other Solutions and it is also really efficient in terms of time complexity so this was a great problem to solve and to understand lot of different concepts I would be posting this solution in the comments so you can check it out from there thank you
Find the Celebrity
find-the-celebrity
Suppose you are at a party with `n` people labeled from `0` to `n - 1` and among them, there may exist one celebrity. The definition of a celebrity is that all the other `n - 1` people know the celebrity, but the celebrity does not know any of them. Now you want to find out who the celebrity is or verify that there is not one. You are only allowed to ask questions like: "Hi, A. Do you know B? " to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense). You are given a helper function `bool knows(a, b)` that tells you whether `a` knows `b`. Implement a function `int findCelebrity(n)`. There will be exactly one celebrity if they are at the party. Return _the celebrity's label if there is a celebrity at the party_. If there is no celebrity, return `-1`. **Example 1:** **Input:** graph = \[\[1,1,0\],\[0,1,0\],\[1,1,1\]\] **Output:** 1 **Explanation:** There are three persons labeled with 0, 1 and 2. graph\[i\]\[j\] = 1 means person i knows person j, otherwise graph\[i\]\[j\] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody. **Example 2:** **Input:** graph = \[\[1,0,1\],\[1,1,0\],\[0,1,1\]\] **Output:** -1 **Explanation:** There is no celebrity. **Constraints:** * `n == graph.length == graph[i].length` * `2 <= n <= 100` * `graph[i][j]` is `0` or `1`. * `graph[i][i] == 1` **Follow up:** If the maximum number of allowed calls to the API `knows` is `3 * n`, could you find a solution without exceeding the maximum number of calls?
The best hint for this problem can be provided by the following figure: Well, if you understood the gist of the above idea, you can extend it to find a candidate that can possibly be a celebrity. Why do we say a "candidate"? That is for you to think. This is clearly a greedy approach to find the answer. However, there is some information that would still remain to be verified without which we can't obtain an answer with certainty. To get that stake in the ground, we would need some more calls to the knows API.
Two Pointers,Greedy,Graph,Interactive
Medium
1039
72
Hello Everyone Today Going To Cover A Distance Of This Heart Problem Likh Course Let's See Who Wins Gold In Return For Operations In Wave 205 On Thursday And Then Example Avv Exploded Battu Kya Hai How To Make A Tour Officer We Can Do It Not to be lit subscribe first replacing to drops vikram rathore and where going to update room on and on's katesar village to 16 years paper pot for operations at every place to and director and related to tree something different subscribe convert to a mp3 operations in The Forest Way Soen Vihar Terminal Number Operation Subscribe To 10000 Till 80 Crore Bhaan's 102 Top Peeth A Similar NI0 Komodo Jaldi Cheek Eid Tu And Finally 2013 Maa Saraswati India And Sunao Is Want Change Vote 1032 Bluetooth Award-2013 We Operation Se Ko Subscribe Now To 2030 subscribe kare subscribe Video Ko Ki Swarna Dash Tuition Fee Hai To Here If You Want To Convert K It Well You Can Simply Add Half Of The Elements And Elements In Total Of Operations On Hai Otherwise The interests of this you want to bring LED military side development will eliminate were how to print for a so simply this you want to convert this LED to a for from string converting and simply update itself will bring to front subscribe and from just solution point problem subscribe to subscribe our solution available on astro shop share gosht surya point use petulance fabric par subscribe our solution problem ka solution problem What is the meaning of what is the A minimal operations required to convert hai chhuye and S2 and that Simply attend let's go into what is the smallest and minimal operations in full force to RO yes ka prayas laptop dutiable si feeling ombudsman and subscribe to and listen list fields for stringent this remedy and fields and from string operation request switch off that quiet going On to the next level still know how many operation sir request you feel and 2g and empty string to and free subscribe 108 to change word from roast 220 spring and mts rintu roshni operations equal than and hear paint jeans khol post the same rate to * And MP Singh Were Going same rate to * And MP Singh Were Going same rate to * And MP Singh Were Going To Film First Unit Converter That 2mp Settings In A Week This Now To-Do 2mp Settings In A Week This Now To-Do 2mp Settings In A Week This Now To-Do List Hanif Qureshi Cricket Camp What He Was Doing This Foundation Of The Attachment Fear For U Yesterday Morning None Today S Company Operations Request To Add And Shoulder Injury Third Do Hai Simreli Experiment Motu Patlu Hain Let's Understand Such Serious Problem Set Point Check How Many Operations Request To Convert From String And Surya Play List Play A Sanam Movie Want To Tell How Many Operations Request You To Change It's To And that in this case minute updates 2012 and updates 232 half a mile explain the calling from that is how you convert in to the best of that subscribe And subscribe The Amazing and subscribe must come guest if its growth rate status on operation request subject To in to-do list A certain way want to expel Select check request subject To in to-do list A certain way want to expel Select check rebellion Vaneshwar note from vaneshwar Singh subedar pick meaning of this cream and a plus 153 1000 so let's come tourist just because on Thursday the city is simply shooting this to welcome to tomorrow morning want oo just Chill Issue Text And Powder Of Unofficial Not Give Winners Dixit Boxers Minimum Is Dynasty OnePlus One Is Too Looter Let's Check The Receiver 930 Tours And What Is The Meaning Of This Point Too Two To Loot Finally Vikram Two Drops And Illegal Solution Recite Time Minimum Of Beat This point two plus one tea output and liquid operations at do subscribe this number a to-do list is going to solve every problem for every subscribe this number a to-do list is going to solve every problem for every subscribe this number a to-do list is going to solve every problem for every subscribe trees-plants words have finally trees-plants words have finally trees-plants words have finally arrived to table solution subscribe to now half the fuel subscribe to that your Lifestyle road wonderland hai inverter direct word ajay ko half an hour hindi movie on it starman first problem scientist venus after all how long loot no veer vve 28 blood group how to build ee the inside popular point tay magar characters match hai loot ajay ko Loot a value from this note, Tanveer is the person, right, he is a fielder, Table of Solution, Ajay has a personal problem, Scientist Motu Patlu 's report, submit one, please subscribe.
Edit Distance
edit-distance
Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_. You have the following three operations permitted on a word: * Insert a character * Delete a character * Replace a character **Example 1:** **Input:** word1 = "horse ", word2 = "ros " **Output:** 3 **Explanation:** horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') **Example 2:** **Input:** word1 = "intention ", word2 = "execution " **Output:** 5 **Explanation:** intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') **Constraints:** * `0 <= word1.length, word2.length <= 500` * `word1` and `word2` consist of lowercase English letters.
null
String,Dynamic Programming
Hard
161,583,712,1105,2311
326
hello everyone welcome to quartus cap so we are today at the 27th day of april lead code challenge and the problem given here is power of three so the input here is a integer value m and we have to written whether it is a power of 3 so now it seems to be very simple problem so coming up with the efficient solution matters here so the basic logic we all could think first is if a number is a power of 3 or power of any number then it will be divisible by that number as well so using that logic we are going to have a first approach so let me have the number so since it is a power of 3 then it should be divisible by 3 so i'm going to divide this number by 3 so if it is divisible by 3 then the reminder should be 0 so until the number reduces to 1. so here i'm going to check whether the number is divisible by 3 and reduce the number or divide the number by 3. so finally return if n is equal to 1 and we have to add a base case that if my n is less than one then we have to written false let's run let's submit and try to check other test cases yes it is accepted so this solution is gonna take logarithmic time so for this simple problem coming up with a constant time is a real challenge so now here in the conditions the constraint given is the maximum value of the given integer n must be 2 power 31. for example if there is a maximum value given suppose 2 power 31 is the power of 3 then this must be divisible by another value which is again a power of 3 so consider 2 power 31 is itself a power of 3 then 2 over 31 must be divided by another power of 3 for example 3 power 0 or 3 power 1 or to the maximum value within the limit so we are going to find the maximum value which is again a power of 3 within 2 power 31 so that will come up with more efficient solutions so i'm here gonna apply the logarithmic formula where log base of x is equal to n means we'll get the maximum power of that number within the limit so what i'm going to do is i'm going to do log of 3 of max value then i'm going to get what is the maximum power of 3 in that limit so let us go to the code so let this code be here i am going to print it for a better understanding so i am going to print math dot log of integer dot max value divided by math dot log of 3 so that will get to know what is the maximum power of 3 in the within the maximum value so let me run this so here it has displayed 19 point something which means 3 power 19 is the maximum achievable powers of 3 within this maximum value so let me calculate the power of 3 power 19 is this so let me copy this value and now let me remove all this i'm gonna check if this value divided by n is equal to zero let me directly return it so this is it so yes i am going to check whether the maximum power within the limit or the maximum power we can get is divided by the given input number which means the given number is a power of n so let's run yes so let me add one more thing what if the given number is less than one so let me give greater than zero and so let me submit yes again the solution accepted and it is 100 faster so yes hope you like the video so thanks for watching the video if you like the video hit like and subscribe thank you
Power of Three
power-of-three
Given an integer `n`, return _`true` if it is a power of three. Otherwise, return `false`_. An integer `n` is a power of three, if there exists an integer `x` such that `n == 3x`. **Example 1:** **Input:** n = 27 **Output:** true **Explanation:** 27 = 33 **Example 2:** **Input:** n = 0 **Output:** false **Explanation:** There is no x where 3x = 0. **Example 3:** **Input:** n = -1 **Output:** false **Explanation:** There is no x where 3x = (-1). **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Recursion
Easy
231,342,1889
274
hello everyone welcome back to my series of videos of me solving lead code problems this problem is H index what is it about given an array of integer citation where citation I is the number of citations a researcher receives for their index paper return the researchers age index what is the age index according to Wikipedia is defined as a maximum value of age such that the given researcher has published at least eight papers that have been each cited at least eight age times so what does that mean let me copy this we know that the output is free the H value is free and why is it free let's look here this researcher published one paper that was cited three times one paper that was cited zero times one that was six one that was five so the H value is free because he published three papers that were cited at least three times he published one paper that was cited six times doesn't count counts as one he released they published a also three six and five not this one these are the ones that make the H value free so he also published a paper that was cited three times that doesn't count as an H value free because he just published the paper that was cited once twice almost three times he didn't publish but it wasn't um it was inside it five times so if just to give you a context if the uh the array was just six and five the age value would have been two because there were two papers that were cited at least two times and that's the value so what's my strategy to fight this so let's look at this value over here that's this array three zero six one five but sorted in reverse order so descending order so six five three one zero okay so now let's iterate at this moment we found a paper that was cited six times but it was only once so our best value is age equals one iterate to the next one five well this paper was cited five times but if we look back we only have two papers so a best age is two so now we go to free yeah free cool free was cited three times and we have three papers that was cited three times nice three and now we go to one well one if we have paper that was cited once and we don't even need to look back because the age value here is already smaller than the H value that we got so we can actually just like scrape this and not even care at this moment if this value is smaller than the age value we can stop so let's open vs code and it's three zero six one five so best h is minus infinite and for index in citations or actually index and valve in enumerates enumerate citations so we check our first vowel the minimum of our first vowel and the index that we're on so the minimum of Val and index in this case is the candidates and if candidates is bigger than best h I think I need to do index plus one because of index 0 then last age equals candidates return best h so let's look at this our best age is five well it shouldn't be identify oh yeah I forgot about one detail remember when I said if we get here and it's smaller than our H value okay if Val is smaller than our best age we break best age one hmm so let's go candidate Val is free index is zero oh yeah right I forgot a very important part remember when I said I needed to sort it yeah citations reverse trip foreign now the vowel is five and the best H is two now is free and now we just reach the end I think also need to copy from that if so submit accepted and this was my best submission so far 43 milliseconds it's as simple as this hope you guys have enjoyed it
H-Index
h-index
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper, return _the researcher's h-index_. According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times. **Example 1:** **Input:** citations = \[3,0,6,1,5\] **Output:** 3 **Explanation:** \[3,0,6,1,5\] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. **Example 2:** **Input:** citations = \[1,3,1\] **Output:** 1 **Constraints:** * `n == citations.length` * `1 <= n <= 5000` * `0 <= citations[i] <= 1000`
An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space.
Array,Sorting,Counting Sort
Medium
275
17
Hello guys welcome to this remedy subscribe The Channel Please subscribe And subscribe The Amazing subscribe and subscribe the I invented Khoj simple and see how to add that give strength and subscribe And subscribe The Amazing subscribe and subscribe the Video then subscribe The Channel and subscribe in this to India's will find the combination navigate director an order from its combination chief subscribe to the Page if you liked The Video then subscribe to The Amazing Loot-Loot to these 1000 drops for this problem Thursday Subscribe to Channel Subscribe Result Subscribe Old man length of strings of years working with the best friend will be held for the length of the day Will be adding this temporary window into and returns to give water subscribe and subscribe the Video then subscribe to The Amazing Se karare wise wikinews and then in more problems user defined the rise of the apps hai tomorrow morning two brothers find the present president to videha.the character president to videha.the character president to videha.the character president radhe-radhe gyan subscribe servi subscribe The Video then subscribe to the Page if you liked The Video then subscribe to Main To Idhar Community Used in M.Com Liquid -1.2 The Lord of the Rings Digit subscribe -1.2 The Lord of the Rings Digit subscribe -1.2 The Lord of the Rings Digit subscribe Video to like subscribe and subscribe the Video then subscribe to subscribe our Channel subscribe Pimple Thanks for watching this video 2019 hai
Letter Combinations of a Phone Number
letter-combinations-of-a-phone-number
Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**. A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. **Example 1:** **Input:** digits = "23 " **Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\] **Example 2:** **Input:** digits = " " **Output:** \[\] **Example 3:** **Input:** digits = "2 " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `0 <= digits.length <= 4` * `digits[i]` is a digit in the range `['2', '9']`.
null
Hash Table,String,Backtracking
Medium
22,39,401
1,655
hey what's up guys this is sean here so today let's take a look at 1655 distribute repeating integers okay so you're given like an integer an array of any integers where there are at most 50 unique values in the array right and then you're also given like an array of m customers other quantities so the each quantity means how many numbers this customer is going to get right and the integers i customer gets all are all equal and every customer is satisfied okay so blah you know return true if it is possible to distribute numbers according to the vo to the above conditions so basically what it means that you know we have a long list of numbers but there are like only at most 50 different numbers so which means that we can group those numbers together within like a 50 size of 50 directional hash table right so we have a numbers here right and then the first example is what is like this so basically the first customer he wants two numbers he wants two not two numbers i mean he wants two same numbers right but we only have four different numbers whose quant is always only has one that's why this one is it's false we cannot satisfy that the second one is true because you know since the first customer wants to wants two same numbers and we have two three here that's why this one is true and same thing for this example three here right so we have two ones and two twos but and then the two customers they want like two number two same numbers and another two same number so we can give this the first two ones to customer one and then we give the first the this two to the customer two all right so on and so forth okay this is another one right we have five ones so we can give five to customer one we can give three ones and then two ones to one and three ones to customer two all right so here are some very important constraints here so i mean there are at most 50 unique values in nums we already know that and then the customers there are only 10 customers okay so what we have so we have like a list from 0 to 50. each number we have dif we have a list this one has a different number have different count you know turns out 10 or even 88 doesn't really matter so here we have a count hash table or account list it doesn't really matter actually we don't care about the value of numbers all we care is the count of each numbers so we have a list of counts for 50 different numbers and then we have what we have a zero to nine we have ten customers so we have ten customers and they each customer also wants some numbers from this count right we have a different 2 6 5 7. and the prob the question is asking us can we somehow distribute this count of numbers so that we can satisfy each of the customer okay i mean so for this problem you know there is like a greedy solutions basically you know we uh i think that solution is like a greedy plus backtracking where we sort from we sort the quantities in the reverse order basically we're trying to satisfy the customer who wants the most numbers and then we try each of them in this count we also sort discount from the biggest to the smallest and every time when we uh if we cannot satisfy this customer we simply return fast if we can satisfy everything all the customers will return true i mean that one can actually pass all the test cases but to me i don't think that's 100 correct but i cannot approve but i can't prove that you know that's why i'm not going to talk about that solutions here instead i'm going to talk about the dp solutions here so every time when you have like this kind of two var two like conditions right you have like a candidates and then you have another like this thing you know this one is like similar like the uh different people can wear hats right basically we have a we have different candidates and we need to assign some numbers to these customers but the difference for this problem is that you know we can assign multiple customers to the same uh count here like the uh the last example here right for this one we need to assign multiple customers to the same count here yeah so that's that and so for this kind of problem you know it's always a i think the one of the template is that for the dp right so the first one is the we're going to always have a mask here you know we have a mask and then we'll have an index so that's going to be the common template for this problem and who is going to be the mask of course so whoever is smaller will be the mask and in this case it's going to be the customer right so the customer is the mask and the index of course is the uh is account it's a is the index of the count so we need this index because we don't want to go back basically you know the index means that the dp index means that from zero to index minus one zero to minus index one when with the mask means that which customer has been assigned to the to some numbers what's gonna if it is true right because this one this thing in the end will return either true or false things can be going to be a boolean type right yeah so we start in i mean so is that what's going to be the next thing is that you know every time when we add a current index right let's say we're at index we're at this index and then the count for this number is 10 okay so the converse number is 10 and so what's going to be the scenarios at the current state right let's say we have a the mask you know the mask is of course going to be either zero one zero or one it doesn't really matter right i mean we could use zero represents the customers which doesn't have a how has not been assigned or vice versa either way is fine but for this problem the let's say we have an index right and we want to know because since we will be we might be signing multiple customers right with this with the same account number here so which means that let's say we have let's say one means the uh let's say zero means that the customer who has not been assigned to the numbers which means that we have to get all the subsets since we have four here we could the subset i mean of course it's all the subsets among all those kind of zero four zeros we have to try all of the subsets because we don't know that and that's why we have to try all the subsets with the current mask so the subset i mean is like this i mean so the first subset is for example we have this one right the first subset of that is one zero i'm going to remove this thing here so which means the uh okay so the first case is the this customer will be assigned gets assigned to this one and second one is what is like now with this one right and then here the third one will be this one will become one right and so on and so forth right and that's the first customer case and then the second one is the then the next one will be the two customer case right so we are we assigned two customers with this count here so we should only one two one zero one and then what and then we have this two and one zero one this two one zero one and then so on and so forth and then three and four so basically we have to find a very efficient way to give us the subsets based on the mask right and to do that you know there is like a trick to do it we have a there is a formula to do it but to do that we have to do it in a reverse way which means that you know we have to make we have to use one represents the uh the not assigned customer and zero represents the ones that has been assigned so we have to reverse the definition of the speed mass why is that and i will give you an example here you know so let's say we have this mask all right let's just use that example here and the formula is like this the formula is the is a current one the current mask minus one and then do an end with the current mask so that's that you know so that's the uh the formula to get the next subset all right so the way we're getting the subset as you guys can see here so at the beginning you know this current one will be the same as the mask here okay and the subset is like this so when the current one sorry so when the current one my minus one so what do we have here we have one zero um one zero yeah and then if we do a end mask here right and with mask what we have here we have zero sorry we'll have one zero all right as you can see here now we have a different mask here right so the one got removed in the end right and how about let's i mean if we keep going right now this one is the current right so if we do another minus one for this one we have one zero one and if we do a bit and with the mask this is the mask right this is the mask again what do we have a one zero one uh sorry two zero i'm sorry zero one and one is yeah so this thing will be the current so this is the current one right so this is the current one and uh and as you guys can see here right so we are like actually getting the all the subsets for the ones and you can keep going and i'm not going to keep uh do more stuff here i mean i'll do one more thing so let's do another subtract by one so one zero right and then we if we do uh end with that what we have one zero right so this is the second subset as you guys can see here so we have a this one here right this two one here and we can keep going that next one will be one zero one right and then if we do another end here it will be one zero okay so here if we do another one right we're gonna have like a zero one right and then if we do another end of it is that what do we have we're back so now the first one will be zero now we have zero one right so this is the new one as you guys can see here so now we're removing the first ones here we have these three ones left anyway so that's how we can calculate the uh efficiently calculate the next subset from a bit mask and since as you guys can see here we have to use like one as the uh the as the remaining parts so which means that you know we will start from our starting point of the mask will be one and in the end when we reach the zero state we know that okay it means that we have assigned all the customers with some numbers then we can return true okay cool so i will just start coding here you know during coding we'll also be implementing some of the hot the precalculations but i'll try to implement the um i'll try to implement the main logic first so like i said you know we're gonna have like a dp right so for the definition of dp here we have state the first one is the index and the net the next one is the mask right so i'll be using like a like the uh the pythons way of doing the memorizations here you know so if the mask is equal to zero then we know okay we have assigned all the customers with some numbers that's why that's when we return true and else if the index is in okay so to do that let's try to count the numbers first okay so the count will be uh we do a counter right we will counter off the numbers and all we need we just need the values right we don't need the keys here so that's why we do a values right and then we will convert this thing to a list right so that's how we do it and then we can we have n equals the net length of the count and then we have m equals the length of the quantity right and then here in the end we simply return the dp of zero and what the at the beginning we have one there are all ones means that this one just do a left shift by m and then minus one that's how we get one right okay back to this dp here yeah back to this dp so and when's the when it's going to be the negative case so if the index has reached the end of all the other the count then we know we need to return fast right so that's that and now the next one is what is the answer right so the answer is what so you know with this kind of problem kind of problems you know an index is all there's always like a case where we can either pick this discount or we don't pick that's why for this kind of problem the first one is going to be always the not peak would be the index plus one right if we don't pick it then it means that the mask didn't get didn't change at all so we can simply do an index plus one and then the mask right so not use current count right the second one will be use current count so to use current count uh i think we can just do a quick check here i mean if not the answers then we use it right but this thing is optional because if this one already returned untrue here we can simply return the answer right we don't have to continue but this option it won't affect any of the time complexity here so um okay so now we need to get all the subsets right try all the sub subsets of mask and here there's also an another difficulty here i mean let's go back to this example here one zero one let's say that's the current mask and zero means those customers have already been assigned to the to a number and one means the uh those are the customers we need to consider right here and to efficiently let's assuming we have this kind of mask here right so let's see so there's like well current you know i'll write the uh the formula first so at the beginning the current is mask right and then the formula is like this while the current is greater than zero because we're removing each of the ones in the end all everything will become one that's what that's when we stop right we have a current equals the current minus one right and then we do a we do an end it's a mask right and that's how we get each of that's how we got the current so the current is like this one zero and something like one zero uh one zero right something like that basically the subset of removing of replacing any number of ones into with zero so now the next problem comes down to uh let's assume we uh we have re remove we decide to use the last two these two customers with this current index what's going to be the condition of using that right so the condition of using that is that we have to know if the quantities of those two customers is equals it's either equal or smaller than the uh than the current count if it is then we can use it otherwise we can't okay so if we do a hmm while we're doing the subsets and as you guys can see we are doing the subsets by using this bit manipulations here and how can we know the sum of those numbers the sum of the quantity the sum of those beat who has been converted from one to zero that's going to be the question for us right and actually there's another trick here you know instead of considering the ones has been changed from one to zero let's consider the ones has let's consider the ones that has not been changed and those the ones that has not been changed to zeros are the numbers our are the customers we are going to we're going to assign with the current index with the current account here so why we do that because you know at each of the while loop here we have a current here so the current is like this something like this and with this we know okay so we have two numbers we have two ones that we want to assign two customers we want to sign and then we can do some pre-calculations and then we can do some pre-calculations and then we can do some pre-calculations to just use one time to give us the sum because if we don't do a calculations assuming we have this one here we have to scan everything we have to scan the entire mask right to get it to check if this is one if it is one then we'll we summarize the quantity and we have to scan it for each of the mask here each of the current one here that's why you know we can simply do a pre-check a pre-calculation here you pre-check a pre-calculation here you pre-check a pre-calculation here you know the uh so we're going to have like a totals right the totals of the what the totals will be the total quantities it needs for some of the customers for some of the combination of the customers and since we only have like 10 beats for 10 customers so the total combinations for these totals it's just like the what like this right to the one to the power uh basically to 10 to the power of 2 to the power of 10 which will be a 10 20 24 okay and we can simply brutal force to try all the possible other possible combinations of the of this beat mask and we can pre-calculate pre-calculate pre-calculate the total quantities we need for any of the mask with the with some given ones here right that's why we have a mask here in the in range of this m here right and then we can have like so for each of the mask we simply just do what we're going where we're supposed to do here we simply loop through each bit and then we check if that bit value is one so the way we're tracking it we simply do if the bitmask to end with the uh of this i here right if it's not empty if it's not zero then it's one okay yeah and then we just simply do a total dot mask right with the plus of the quantity of that for that customer right so that's well that's how we do a precalculation for any given mask and how many quantities we need so that in here with each of the current ones the current mass with it means that the current what means that those are the customer again we're trying to assign right so we just do this if the total if the totals often the current one right is equal smaller than the uh than the count of index right then we can try our dp here so we can try if now we can do a dp right the dp of index plus one right and then we have a oh here so okay so again right so since we are going to set we are going to assign the ones okay let's see this is the current one which means that we're going to assign one with those two ones right with the with this kind of the current count so what's going to be the remaining bitwise the mask so assuming this is our original one so as you guys can see so if these two have become zero so the remaining one should be what should be zero and one zero one right which it means that we have already satisfied those two customers and the remaining tools are this are these two here right and how can we do it that this is another bitwise manipulations here right it's just the mask right do a xor with the current one that's the uh that's how we got to get the other remaining one because x y means the uh if they are the same then it's zero it will be zero if they're different then it's one right so actually this one is the same as if you just you can simply do a mask minus current you will get same result because one minus one is zero and one minus one zero one minus 0 is 1 right so either way it's fine and this one if this one is true and then we can simply return true here right yep i think that's it otherwise it will continue try the next subset and then it will use the next subset to find the total quantities that subset needs and then it will continue with this dp with the remaining ones right all right cool i think that's pretty much it so let's try to run the code here oh i think i uh totals 39 line 39 oh okay i'm missing a highest here i think yeah zero all right accepted submit all right cool so it's success um yeah okay so how about time and space complexity right so for the time complexity and you so we first we need to get to know the total state you know let's say we have a we have an n here right and then m so first one is the n right and then the second one is times the mass basically is a 2 to the power of m right and uh for each in and then inside of each of the dp here we're doing like a while loop here because we'll be we'll try to get all the subsets of the uh of the remaining so it's going to be the total of subsets so let me think so the subsets okay and depending on here this will be a little bit complicated because depending on how many ones we have here right because how many ones we have in this state here we'll do another subset based on those ones right it's going to be a subset so and to calculate subsets you know actually so it turns out oh by the way so this i believe this time complexity analysis should be out of this out of scope it'll be too hard so it's going to be a n times 3 to the power of m so how do we get this you know basically if you really want to dig into it basically you know there's if you guys know the a plus b to the power of n so what's going to be the value for that this is going to be the a to the power of n plus a combination right so the combination of c l one and then we do a to the power of n minus one b plus c i think c n 2 of a to the power of n minus 2 right and then we have a b square something like this and all the way until to the end to the b times b to the power of n and it turns out the way we're calculating the beat mask and the plus the way we're calculating the uh the subsets is the same as this formula here that's why we can just convert this 2 to the power of m times this subset which is 3 plus m turns out to be a 2 plus 1 times up to the power of n and yeah so that's it i know it's a it's complicated of course so that's gonna be the time complex and space complexity will be this time the state of this will be the end times 2 to the power out of m right that's going to be the space complexity yeah because for this part it's running it's a pre-processing that's why it's faster a pre-processing that's why it's faster a pre-processing that's why it's faster all right cool guys i think that's pretty much what it is i mean this problem you know the state you know to come up with the state shouldn't be that hard right but the difficulty for this problem is the uh after you have figured out the dp state here first thing first is that you know after using the current index even though there are like some numbers left for this current count we'll be discarding those parts because we have tried all the possible subsets for this foot for this current count even though there's not something we haven't assigned we have already tried all the other scenarios that's why we can simply we can safely move forward so that for this dpu there's only that's only the two-state dp here so that's the only the two-state dp here so that's the only the two-state dp here so that's the first thing and second one is the uh how can we use the mask here then to efficiently get the next subset of a bead mask and after getting the subset and the third difficulties how can we fit and efficiently calculate the uh the total quantities we need for the next subsets right and to do that we uh we do a preprocess and then we use one to represent we use the one the we use one to represent the people the customer we're trying to satisfy next because the way this getting sub getting next subset works is by converting the ones into zero that's why we have to starting we have to start from all ones and then we end with all zeros and that's why this one is a pretty hard problem all right i guess i have talked enough here i'll just stop all right cool guys thank you so much for watching this video stay tuned see you guys soon bye
Distribute Repeating Integers
move-sub-tree-of-n-ary-tree
You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that: * The `ith` customer gets **exactly** `quantity[i]` integers, * The integers the `ith` customer gets are **all equal**, and * Every customer is satisfied. Return `true` _if it is possible to distribute_ `nums` _according to the above conditions_. **Example 1:** **Input:** nums = \[1,2,3,4\], quantity = \[2\] **Output:** false **Explanation:** The 0th customer cannot be given two different integers. **Example 2:** **Input:** nums = \[1,2,3,3\], quantity = \[2\] **Output:** true **Explanation:** The 0th customer is given \[3,3\]. The integers \[1,2\] are not used. **Example 3:** **Input:** nums = \[1,1,2,2\], quantity = \[2,2\] **Output:** true **Explanation:** The 0th customer is given \[1,1\], and the 1st customer is given \[2,2\]. **Constraints:** * `n == nums.length` * `1 <= n <= 105` * `1 <= nums[i] <= 1000` * `m == quantity.length` * `1 <= m <= 10` * `1 <= quantity[i] <= 105` * There are at most `50` unique values in `nums`.
Disconnect node p from its parent and append it to the children list of node q. If q was in the sub-tree of node p (case 1), get the parent node of p and replace p in its children list with q. If p was the root of the tree, make q the root of the tree.
Tree,Depth-First Search
Hard
1650
322
It is 200. Friends, today we have come to the shift question. Coin change and only 10 days are left to divide into lines. There are more questions. It is simple and easy. It means that how many points will it take for us to reach a particular amount. Look at the example. Direct that I have a coin of one rupee, a coin of ₹10, a coin of five rupees, coin of ₹10, a coin of five rupees, coin of ₹10, a coin of five rupees, then I have to make rs.11, otherwise what will we do, we will then I have to make rs.11, otherwise what will we do, we will then I have to make rs.11, otherwise what will we do, we will eat ₹5, make it eat ₹5, make it eat ₹5, make it ₹5, take two coins and ₹5, take two coins and ₹5, take two coins and insert it with one rupee, it is done. Neither output three ignorant, how much will the total cost, the work was done in three shifts, look, I could have brought the output 11 also by making 11 of one, but we do not have to do this, we are being told the minimum, okay, so how many numbers and points will be required for the minimum two? Great amount, this is the 11th example. See what Mirwaiz can become. If these people are appointed in such a situation, if you want to get minus one more done, then see how they start the subscribe song in such a way that they accept the example as 12345. Give us the list and the total amount. In S capital it is to make the seventh, I have two religions, Giridih approach is ours, okay in the mind, Giridih means that the maximum one has taken five, okay for the effect, at what time two children, what to do, take one also and take one also becomes Do you believe that how many will be learned with three points Chowkpur will be done and then it will come again? Is it not in the minimum? That is the problem. The answer to counter this is that after doing three news, Vid comes along and if it goes to coin only two later, then output two. Is the minimum, so this is the reason why right answers from one, so our ready solution is not working, okay, what can we do, we can defend, we can try back, one of these is interesting, look at what we have like what I have The project is that all four things are fine 12345 407 They are standing together Four approaches are that see ₹ 1 Make six Three make four that see ₹ 1 Make six Three make four that see ₹ 1 Make six Three make four 241322 Make ₹ 5 So make it okay Now do it like this and keep going Go 241322 Make ₹ 5 So make it okay Now do it like this and keep going Go 241322 Make ₹ 5 So make it okay Now do it like this and keep going Go keep going Let's do one from late The part is that what questions come after two of the cases 1345 If we all see then you only tell me These three were native A lie will be given right - Vande 13 - 2 - You are also lie will be given right - Vande 13 - 2 - You are also lie will be given right - Vande 13 - 2 - You are also negative This is not allowed This is our work by eating It is possible that if one of the two is removed then one is left or if each is added then zero claw is finally sun, then in this way this is the possible solution of ours, which was there, it is a support, not one pair out of five, then one pair is formed together that We have to tell the minimum set, okay, it will be a game like Sadhu, if you see one common thing, 1345 129, you will see that things are repeating, now look, I have six, last I did one thing, you child should reduce 53 and Jatin means on this hole. To make it, you have to put only ₹ 3, you will make it, you have to put only ₹ 3, you will make it, you have to put only ₹ 3, you will put two left, 5010a, see, it will repeat, it is repeating here, how can you do that, you will go later, keep cashing, okay, now there is one child here, then one more. By inserting one, the bus time comes to zero, neither is it a possible approach, the approach is that this time the fifth in 501 is united again, even then it is closed that how many stairs have to be climbed after one turn, it is three, is n't it? So 123 5115 A Jury Karo is going to be the ultimate solution which will be our small little one so if we like check here and hit the options 12345 then by doing this it makes a pair of our four days with three and zero darkens the rest ahead. This will keep repeating when you repeat it. Here, by doing this, we can see what is the smallest. If you look at this three news and from the chart, you will see four births and three, what can we do with this method. We take the bottom approach. We did the bottom approach. Ghee is that always make it on through, we need money along with it, what do we do, keep using A DP, old or known DPO one, keep this in mind, 13 245 along with making above, 135 ash is 45, ₹1, so we have one, 245 along with making above, 135 ash is 45, ₹1, so we have one, tell us for 12. ₹ 2 is not there, if one tell us for 12. ₹ 2 is not there, if one tell us for 12. ₹ 2 is not there, if one can be used twice, you two have to listen, how much money will be spent inside, how much will it be used to play with, then race means two coins of one rupee will be required to make ₹ 2, then define how many will be make ₹ 2, then define how many will be make ₹ 2, then define how many will be taken, read 3 such things with me DP and four will do the work for someone, just one coin will do the work, DP and five or do 225 are left, so people do one DPO 6, see how they are reaching, which street, what to do, make two coins for the team We will give the work, we are looking at the minimum, keep in mind that the DPO is with us, which is withdrawn in the account. By keeping the DPO with us, our approach seems to be that one deposit of DP off, keep something here, let's assume 6 from late, which means deposit from ₹ 1. means deposit from ₹ 1. means deposit from ₹ 1. Now I have to withdraw ₹ 3. Now I have to withdraw ₹ 3. Now I have to withdraw ₹ 3. Two is fine. Three has arrived that the opponent has seen the DPO. Five can be seen. Well, it is fine, that is, the work has been done with one, and that is, what are the options with me? Okay, so see this hot definition, what have I done, I put a coin of four rupees, know, after doing four likes, rest, basically, the amount that will come in here is - no one will come in, so is - no one will come in, so is - no one will come in, so if I put a round of three rupees. If it is four, then DPO is four, how much is one plus dip 4, I am one plus one, neither is it 421, nor two, it means minimum is two, Simbu store exam is DPO, if I know that along with four, I am studying - I am left with three. Exam studying - I am left with three. Exam studying - I am left with three. Exam 2018 Main itna one tu 21 aur kis can take that exam TDP and five kya hoga ah ok 17 banaye hai ki pachak it becomes investment na in English DPO is one of five so right I am saying five how come There will be 6 and there will be four, so according to what is available to us, my mother, how much is ours, only two are coming, right, you can do one spoon DP off like this, two can do this. Only we can know that one point of five rupees is five-five. Instead of five, we one point of five rupees is five-five. Instead of five, we one point of five rupees is five-five. Instead of five, we took a coin, from here we took five and one coin, so now our dip exam is done with two more - how much is the dip of 22, tell me, if there are with two more - how much is the dip of 22, tell me, if there are with two more - how much is the dip of 22, tell me, if there are two, then there is one spoon. Exam 2008 is on this day, so would you like to have this five plus one, had he been born so or two, he had told here, this is what we are going to use while coding, this is simple water, is it okay, fennel, you must have understood what we are going to do. If we are going to use Deepika, then I take DP here. Initially, what we do is that the amount is as much as I told you, as if we were taking it to the city, we make it there and how much is there inside it. Meaning, as we say, we can also take these final numbers because we want maximum, we want to make minimum. Look, if I zoom from inside this, then some bad thing will happen, isn't it? Actually, here we have made it plus 1898. War is nothing like verification, so whatever is more than the maximum expressed amount inside all of us is not much, that's why they are sure about the appointment, so what will you do, we go in these vans, from the forest to where actually. In the bottom approach, it goes from zero to up, otherwise we will take zero, now we will do 1234, so from one to the amount plus one, so in the bottom approach, we will go from six to five, from one to two to three. Going till seven, this was the crotch, now we will hold each point, took the sequence in points, if only - C, understand the amount, learn from - only - C, understand the amount, learn from - only - C, understand the amount, learn from - do and that great daily 120 is coming, this is our K is correct na means negative does not come. This means our help and in using this read, the amount will be known only then I will know what we do, what do we take from DGP of A, what is the minimum of our own DP and Swayam and OnePlus. Now tell me why this is written. DP off that this - this is what I was doing in front of you, when - this is what I was doing in front of you, when - this is what I was doing in front of you, when I look at this brinjal, it came because of the skin, it has been planted by someone, isn't it ours, now it has been planted, so apart from this, the rest of the children will also have to be seen, I know. I put 500ml coin of five rupees and then to make it with DPO, I will have to see with it - It is positive, have to see with it - It is positive, have to see with it - It is positive, whichever is the minimum, if you want to catch the minimum, then you will catch the minimum. What will be the final return from this? The return will be as per the amount of DPO that I have come. If this does not happen, it means that the amount of DPO cannot be changed because I had written it below and was also putting it and had kept it aside. If I write the amount plus one, then if the amount is there but it was not there. If we can get diploma then it means that we take such a case that is minus one then submit it, let's run it, Wally, someone else, this was our mount to see, friend, I actually changed the swelling in the beginning but then did not check. There is no gap between them, has it been accepted? Let's see, there comes a time when you say no, ok, success has been achieved and this is our code, so did you understand it, how did you get rid of it, how did you like it? Tell me in the comments and to follow them, you can also see the code in the description, Haldi, nothing is happening in the next video, subscribe.
Coin Change
coin-change
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`. You may assume that you have an infinite number of each kind of coin. **Example 1:** **Input:** coins = \[1,2,5\], amount = 11 **Output:** 3 **Explanation:** 11 = 5 + 5 + 1 **Example 2:** **Input:** coins = \[2\], amount = 3 **Output:** -1 **Example 3:** **Input:** coins = \[1\], amount = 0 **Output:** 0 **Constraints:** * `1 <= coins.length <= 12` * `1 <= coins[i] <= 231 - 1` * `0 <= amount <= 104`
null
Array,Dynamic Programming,Breadth-First Search
Medium
1025,1393,2345
225
Hello welcome back to Anonymous Data Scientist today we will discuss lead code problem number 225 which is implement stack using queues now before discussing it we should know the basic properties of stacks and queues in stack LIFO is used that is last in first out Suppose here we inserted element three inside the stack and then inserted four, so if we remove an element from the stack from here, then first we will remove element four and then remove three, this will be last in first out which will go inside last. He will come out first, what happens in Ku, the opposite is true in Q, suppose we have entered element three, then we have entered element four, so here we use FIFO, that is first in, first out, whoever goes in first will come first, so if If we remove an element from this then first it will come three times and then after that four will come, so we just have to use the properties of leaf and FIFO, inside this we have to implement it here, we have to implement stack using Q. So let's look at the question. In bar question, they have just defined the basic terms: push means defined the basic terms: push means defined the basic terms: push means inserting an element into the stack, pop means removing an element and returning the top element and top function will return the empty element which is the top element and MT if it is a stack. Or not, now like what is there in the example given in the question, first we pushed one into the stack, that means we pushed element one into the stack, then came push two, then we pushed element two into the stack and then After we made top, now what will top do, will the element return to us and then we applied the operation of pop, so what will happen in this, it will return the element and will also remove the top element from the stack, so we pass this left in the last, now it is applying my Scud MT will return false because this is non MT, so this is just some basic operation, now let us see how we will approach this question, once now we have to implement this stack using Q. Now see how we can do it. Suppose we have Kya which has elements inside it 3 four and f Okay now if we remove the element from here then the first element to be removed will be - removed will be - removed will be - but what we need is we have to implement the stack and what will be in the stack. The element will be returned, so we need ultimately five elements, so now how will we do it, what we will do here is to put a for loop and apply whatever pop function, whatever removal function, we will remove that element and store it in another queue like Here it was removed by the function of pop, so we placed the letter here, now again we applied the function of removal, so the four was removed, the four was placed here, now the last element left like y but f is left, what will we do with it by returning it. We will return the element number five because this is what would be returned inside the stack. Now suppose we had a stack four f. If we removed the element from here, we would have removed f, then similarly we did the same thing, we just added one here. After creating a queue and whatever pop elements are being created, for example, if we apply a loop from inside the queue, then we will take the length of the queue and by taking minus one from it, all the further elements will be stored in one place and the last element will be left. We will return it, so once we do it in the code, let us see how to code it, now it will be more clear to you in the code, first of all we define a double ended q like self d k into d k d. K is for double ended, why is it okay and then what we will do after that is that we will define our push operation, what we will do in push is the empty self dot K, we will append it to whatever element X is, we will append it to it, now pop, now what This function is just in it, we have to run the whole game which we had discussed, we have to run the loop till we have to run the for i in range as long as the length of which is one less length of side than that, we have to run it till there and store it inside the new queue. What we have to do is to store it, we will apply push operation, self dot push and where will the elements come from, self dot kdot pop left, so what will happen with this is that whatever is the left most element, it will come out from our first queue and that will be our second. Inside why, this will work up to the length minus w and we will return the element left in the last and how will return self dot k dot pop left, now we have to define the function top, now to define top, do simple return. We have to return self dot k my man because last element we have to check whether it is MT or not we will put bullion for MT return length self dot k is equal to 0 if it is equal to zero then true otherwise false by running this Let's see the self-documented your own example - 1. Okay, here you keep in mind that these - 1. Okay, here you keep in mind that these - 1. Okay, here you keep in mind that these brackets will be used, this is done here, submit it, so if you have any doubt, then you can comment. You can ask in the section till see you in the next video thank you
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack. * `int pop()` Removes the element on the top of the stack and returns it. * `int top()` Returns the element on the top of the stack. * `boolean empty()` Returns `true` if the stack is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. **Example 1:** **Input** \[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 2, 2, false\] **Explanation** MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `top`, and `empty`. * All the calls to `pop` and `top` are valid. **Follow-up:** Can you implement the stack using only one queue?
null
Stack,Design,Queue
Easy
232
1,306
hey guys welcome back to another video and today we're going to be following the lead code question jump game three all right so in this question we're given an array of non-negative integer given an array of non-negative integer given an array of non-negative integer uh integers air you are initially positioned at start index so start over here is an index of the array when you are at index i you have one of two options so one of the options you have is to jump to i plus whatever the value is at that current index and the other option is to jump to i minus whatever the value is at that certain index check if you can reach to any index with value so notice that you cannot jump outside of the area at any time okay so we cannot jump outside the area okay so let's just look at a quick example over here so over here we have this out of area and our start is five so five refers to the index so let's go to index five zero one two three four and this is index five okay so we will be starting right over there so now we have one of two options we can move to the right by one so that would give us over here or we could move to the left by one right and why do we know that we're moving by one and the reason for that is because over here we have a one so that means we can move in either direction by one okay so uh the question itself isn't too hard uh i would encourage that you go through this entire example and again our stopping point is when we end up reaching a zero okay so i'll just draw it out and uh the question should be pretty simple to solve okay so real quickly uh in this question we could actually represent our steps in terms of a tree so how exactly would our tree look like so over here we would have our root node and the root node over here is going to be nothing else but our stark value okay and after this we would have one of two options and the two options are pretty simple we can either go left so if we go left we would take that path or we could end up going right so those are really our two paths okay and once we go left we would be at a current value and further down from there you again have the same two options left or right so you can kind of imagine how this is going to kind of form a tree based data structure and even without looking at that you could kind of come to that conclusion pretty easily because we only have two specific uh specific options and uh so let's just look at an example here so we have one so we could go one to the right or we could go one to the left now the only thing that we really need to take care for is the base condition which is uh we cannot exceed um any of the indices okay so that means that we cannot uh exceed whatever this index is right so we cannot have an index which has the same value as the length of our area so that's one condition and the other is that it cannot be smaller than zero so this over here is the smallest okay so that's one condition we need to make sure that our index is in the range of uh zero and uh all the way up to the length of our area so that's one condition and what exactly is going to be the second condition so the second thing really isn't a condition but it's more of an observation that we want to make so over here um i so let's say so you go to the left over here or you can go to the right so those are our two options now once we go to two we actually cannot go to the right anymore because we are at the ending so let's say we go to the left so when you go to the left of two so one two you would end up over here at three so one thing that we want to notice is once we actually go to a certain index then in that case we don't need to visit it again so why exactly are we doing that so in this case so at the ending of the question all we need to kind of uh respond or sorry output is either going to be a true value or a false value we don't care about what the path is we just want to return true or false and keeping that in mind if we already visit a node so in this case we're already visiting three so what that means is that we're gonna continue the steps so what are our two options at three so we could go to left by three so one two and three it will put us over here and so on and so forth right so once you actually end up doing those uh calculations you do not have to do it another time so the basic idea is uh once i already visit a certain index and if i did not output true uh by the ending of it right so if i visit three and go to all of its possibilities and if i still don't end up outputting true that means even the next time or how many other times further on i come across three i will never ever uh get an answer of true right so keeping that in mind we're gonna have some sort of cache which is gonna tell us all the nodes that we have visited and uh if we have visited a certain node then in that case we're directly going to return false because that means that we do not have an answer at that certain path okay all right so since it is a tree uh we could take one of two approaches which is either a bfs approach or a dfs approach and for this question i'll just be using a breadth first search okay bfs okay so let's start off by initializing our queue so the cue that we're going to be using is going to be from collection so collections.dq collections.dq collections.dq so we have the cube ready for us and what is the first value in our queue going to be so the first value is going to be the start value so we're just going to add that to our q in the very beginning now another thing that we want to initialize is going to be our cache so our cache over here we're going to use a set in order to represent it and we all have all of them defined for us okay so now what we're going to do is we're going to go inside of a while statement so we're going to do wild cue and basically what that means is we're going to keep going until we have something in our queue so now the first thing that we want to do is we want to get the current index we're on and to do that we're going to do q dot pop left okay that just pops out whatever is at the zero index so in this case we're getting whatever that value is and we store that inside of index so over here our first thing is we're going to check if whatever value is at that index is equal to zero so if it is equal to zero that means we're done we can just directly end up returning true we're done we solve the question nothing to do right but if we do not actually have a value of zero that means we want to look at the other possibilities so what exactly are the two possibilities so over here we have one of two possibilities and one of this one of them is we can go left and the other one is that we can go right okay so we can go left or go right perfect okay so uh let's just code out both of these possibilities and uh what i'm going to do is i'm just going to put them inside of a for loop instead of repeating the same steps two times okay so what exactly are the two possibilities so let's start off when we can go to the fridge so if you want to go to our right it's going to be our current index plus whatever value is at that index so to do that we're going to do array and then index okay so that is for going to the right and we also want to get what happens when we go to the left so when we're going to the left it's going to be our current index minus the whatever value is inside of the area at that index so now we're going to put these both inside of a for loop so let's just before x in that so now we're going to get both of these indices each time and first we actually want to check whether this index is valid or not and the conditions for that is we have two conditions right so one of them is it inside of our boundary so let's just do that so our x value has to be greater than or equal to x and that value also has to be less than the length of our area okay so that's one of the conditions and we have another condition which is the x value over here should not be inside of cap inside of our cash so not in cash so that means that we did not see the value yet and hence there is a possibility that this value could be true and again if we did see the value again and we did not end up returning true at that point of time that means even this time is the same thing going to happen and we there's no point in repeating the same step again okay so now we want to do two things right so one of them is appending it to our queue so what are we going to append well we're going to append the x value over here and now we want to add whatever index we are currently on to our uh cash right so to do that we're going to do cash sorry um cash dot add and the value that we're going to be adding is whatever index we are currently on so this should be it for our solution and finally if we actually don't end up returning true even after trying all the possibilities we're going to return false okay so over here i think this is going to take big o of n time because since we are keeping a track of a cache uh what's going to happen is we're never going to visit a certain index more than one time so yeah that should be it let's submit it and yeah 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
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,954
If you haven't subscribed today's video is Scotland ice cream 94 young people on the table Mini Garden kilometer cola kinaf Apple and Samsung's new color is necessary punishment two of them epilation direct region million fish Yes no we will sing to you your hairstyle Heart goods We also two Hocaoglu when did we talk come here dear You took it out for the moment Adar Karadeniz video interesting comes out at the point module first 100 mat.lipstick ita car for example two Yunus 100 mat.lipstick ita car for example two Yunus 100 mat.lipstick ita car for example two Yunus One subtraction table School By the way the results of modeling is gone model sport these days fly Look at this dad The song to you is the address in the figure Bolu part Is it the old one? Isn't it the Center? After we don't have this, the thought is where are the 10 examples? The new tenant, but then it was made in the region and the 6 conditions every day, the happiness of Terme, these models, write down, take it to the doctor, I didn't take it. What happened? Mount Normally, we also gave Bitte, but the subtitle is important information, times are over, we start directly LOL Our skin is in the bond. For example, there is no contract at home, it's like if this passenger tries so hard, I'll go all of it's as much as my son, let's drive to Kentucky, the photo is in the state of emergency, if I don't get it, anyway, I'm leaving the message, but the end is 12g, there are 12 of them from the 52 address for today, other than that, he left it aside, it's over, it's a returning one. When the bag is a little bit, he looks. So, what are we, for example, I liked this very much, because we are talking about Kerim outside of trimo, he found it unfair, then if there is a small one, send it, do not steal it with torments, some spilled Yes, for example, our Satı is early, now the number is in these services, I got perimetry flow, let's sleep today in your father's taxi episode, Neşet Abalıoğlu, our sister, be careful, because I will teach me this whole cable tomorrow, it is okay, it is the word. You, your system, your group, is not enough for us? For this, come to Malatya, let the models of Berk elements burn, I will show you where the qiku cream we installed, do not write the models on the face of the elements, innovations with you are not modules. Because we talk about it with cheese with illogical orange transfers, then show it, say good morning sometimes, we have fish, Choco words, the two we met for this, all of us are gone, it is for sale. one branch smells on us, but the virus is rocky, for the first time in the year, the water is a little bit twice over, our model is over, the second one is over, we are all done, are we hearted ? The ? The ? The crow solves it is not a model next to it, the model is as difficult as the mini What are you going to do? We deleted this tomorrow from here first. Dude, is this product formula above? What does it mean that they are Barca? Is it the same after 8k? model code then the head is one So I'm doing this tomorrow okay we are logging in are there those who can enter the work we can join you this is the two of us our health people e-mail Niğde 30-40 enos bring people e-mail Niğde 30-40 enos bring people e-mail Niğde 30-40 enos bring one exc-500 what do we need together one exc-500 what do we need together one exc-500 what do we need together his student is exposed in front of me buy me wow İPA mettingen Kamusta 12 of course Mustafa Burak came from this and that flower came, I was wrong, I will finish them, they are gone and K look at the good news, how I also if that's enough hand cables, Rufus, force wife, Quran, hanneck, princess, truth, head, not to mention the voices, funny with you, Elif Fight Nevruz for cheap composite mean adult threw I also what is this I Complex Hello express 2000's winpower we so Worst Darıca start what does it mean when the card was over when there was another came this frog nice ends what does this world mean this proof q We actually have En ge-ec So we read Hostel, for the second, have En ge-ec So we read Hostel, for the second, have En ge-ec So we read Hostel, for the second, this resistance, when we wear the jersey, this green mark has reached our horse. These are the water of duality, that is, I will go exactly like that meat news is coming to an end, we are blessed to say that after the union, we are now working, how are you? If we can detect the fast perimeter debt 3D texts of Elif, this is a clean card. Normally, whoever makes this heart, it is love to travel, renewal is one of these elements. It is against the principle of asking the Ulgen tire and then Secret. But where is this? Yunuslar sports Nova 15 lira 15 Instagram if we are wearing clothes, if we are going to the concert, 10.15 wound Nilay, we have the going to the concert, 10.15 wound Nilay, we have the going to the concert, 10.15 wound Nilay, we have the melody expression most her lokumlu cake meybuz Because direct 115 cinema Then it is tubicoat adolescent 15/0 So if it is tubicoat adolescent 15/0 So if it is tubicoat adolescent 15/0 So if we are collecting correctly 15yt rakübühm 10-15 how did he talk rakübühm 10-15 how did he talk rakübühm 10-15 how did he talk photo how okay full of drama if you forgot his head is heart there is self crites mean we got in the middle ten days one this Nestle King real Game what does it mean if it is not comfortable middle 5.50 afraid what does it mean if it is not comfortable middle 5.50 afraid what does it mean if it is not comfortable middle 5.50 afraid them Samet we have two Well our upper country this I went deputy both please coming Sprouts this If where girl Love let it go What is it directly in appalas Hospital Because it pulls enough but to come rocket we do all the pacifier Love attack if I wasn't this is the first thing that comes Camera for it's over so it's striking what Camp let's put it on here you forgive me While I'm nice from this when I put it on the most left-right here Bring me closer to when I put it on the most left-right here Bring me closer to when I put it on the most left-right here Bring me closer to me If we are sick, it is special for us to end up with a teratori director, I mean ratem girl, what is this West, what is the right way, we have the seat, sometimes the results of the tests, our doctor is after 90, so it was not easy, I said, if they don't give me the music, look, what is the line for now, this is an exemplary job, Rent A Car, wait, 356 musical, it means the second inside us, it was hung on our arrival, 32 music, Gulen, what is the difference, guess what? This is a children's video
Minimum Garden Perimeter to Collect Enough Apples
replace-all-digits-with-characters
In a garden represented as an infinite 2D grid, there is an apple tree planted at **every** integer coordinate. The apple tree planted at an integer coordinate `(i, j)` has `|i| + |j|` apples growing on it. You will buy an axis-aligned **square plot** of land that is centered at `(0, 0)`. Given an integer `neededApples`, return _the **minimum perimeter** of a plot such that **at least**_ `neededApples` _apples are **inside or on** the perimeter of that plot_. The value of `|x|` is defined as: * `x` if `x >= 0` * `-x` if `x < 0` **Example 1:** **Input:** neededApples = 1 **Output:** 8 **Explanation:** A square plot of side length 1 does not contain any apples. However, a square plot of side length 2 has 12 apples inside (as depicted in the image above). The perimeter is 2 \* 4 = 8. **Example 2:** **Input:** neededApples = 13 **Output:** 16 **Example 3:** **Input:** neededApples = 1000000000 **Output:** 5040 **Constraints:** * `1 <= neededApples <= 1015`
We just need to replace every even positioned character with the character s[i] positions ahead of the character preceding it Get the position of the preceeding character in alphabet then advance it s[i] positions and get the character at that position
String
Easy
878
1,503
hi guys good morning welcome back to the new video so in this video we're going to see the problem last moment before all the ants fall out of blank if you had not watched it we had already discussed in our live weekly contest problem discussions and not only this but also some variations of these kind of ant Collision problems so if you want you can do subscribe we also bring in live contest discussions cool and the problem is asked by Google itself and like not much frequently but still uh it just says let's see what the problem says it just says that we have a wooden plank of the length of n units now in this n units uh some ARS are walking on the plank and each anunt move with a speed of 1 unit per second cool it's just a speed and one ant is moving one unit per uh second now when two arms moving in two different directions meet at some point and it can only happen when the two arms are coming close towards each other right if two arms are moving it can be two possibilities either they are moving in the opposite direction or in the same direction if in the same direction then only they can Collide else they will not Collide so simply they are actually moving in the same direction so they will actually have a collision they change their directions and continue moving again when they Collide they just have a collision such that they just change the direction and continue moving back again asuming the direction change does not take any time and it's just instant now when an AR reaches one end of the plank at a time T it falls out of the plank immediately so plank is of limited length it is actually length n if it like reaches at the point of time T so it just falls off that plank we have an integer n we have two integers left and right just saying okay left integer say ant is moving in the direction of left uh and integer right is saying which means this like as you can see these are these two ARS are moving left so in my integer of left I will have a three and a four and these two arms are moving right so my integer will have a zero and one for moving right now I just have to tell at what moment when the an last AR fall out of the blank which is the last moment when the ANS fall out of this blank so while viewing this problem it might look a bit intimidating okay are there are too many ants let's say to AR Collide here then uh what about the other collisions for example in this problem itself you will see these two AR will come these two will Collide so B and C collided direction of B changed direction of C changed but you will see that A and B will collide and also C and D will collide again uh direction of B will change direction of a will change direction of C again change direction of D again changed now direction of A and D will remain like this only but b and c will again Collide B and C again Collide again their direction will change and again all of them will going on keep on going forward so it might look up been intimidating that okay there can be too much collisions how to handle that but if we look on very carefully just a smaller problem what if I had just two auns so if I had only two aunts Aunt a Aunt B they are coming towards each other for sure I'm just checking Collision will only happen when they're coming towards each other so at the next moment what will happen is a and b will come very close to each other just about a collision now although in the next state directly it will reach to a point where both the ants will actually be in the opposite direction but let's happen let's see what happened in between Aunt a would actually been in the mid and B would actually also be in the mid but facing like this only as soon as they were actually colliding they collided and both of them changed their Direction in the mid only mid of this particular space and as they changed they again start had to start moving backwards so you saw that Aunt a Aunt B were coming close towards each other they collided and they started moving backwards in this if you see here I just mentioned and a an B what if I just don't even mention a Aunt B I don't mention anything so can't you just if you had to visualize from point A to point B can't you just uh see like point a point 1 to point 2 if you just want to visualize that can't you say that this AR next location is this itself if I imagine this Aunt right here would not have been here at all so for sure the Aunt B would have been here and considering this Aunt B would not have been here so Aunt a is actually at this location itself so if and for me every aunt is same right so I can just imagine Aunt can assume there is no one in front of it and it can just keep on moving forward and that is the entire for this problem that I can just visualize that ant as it never collided it just kept on moving forward this ant B it kept on moving forward and this is ultimately what will happen so what we'll do is we'll just simply have all the ANS with us we'll just keep on moving this AR forward and we'll just keep on colliding so it will have three units until it collides this ant will have until it falls out it this ant will have 4 units until it falls out now for this ant it will have again three units which is 4 - 1 three units until it falls out is 4 - 1 three units until it falls out is 4 - 1 three units until it falls out this AR again will have four units until it falls out so maximum time is four units until all the ARs will be out of this particular plank so last moment when the arms fall out of the plank it's actually four and that's how you can simply get this answer solve without considering any other cisions let's quickly get this code done uh as you saw that it would be pretty easy considering that how we generalized and formalized the final output now let's say that uh um what's the variable name so last M let's say last M okay um now I just simply go on to all of my lefts for auto l in left and I can just say okay my last M movement is actually a maximum of last moment comma this particular L because I know one thing for sure if AR is moving like AR at location three uh as you saw here uh so it will just move three steps so it's l will actually uh help me out with everything so four and three I just have the maximum value I needed now the same I will just simply go for right now for right just simply the same thing that um just simply copy this over and the maximum of again last moment comma it's just that right if we are moving so we know okay r n is the last location so n minus r uh would be the distance up to the right so that is I can simply return my last movement and that would be my answer let's quickly check this out so that the only thing was for okay um so the only thing in this problem was just to figure out that how to check if the ANS are colliding with each other so how they are happening so yeah as you can see uh we have done this um cool thank you so much for watching see you guys next then goodbye take care bye-bye
Last Moment Before All Ants Fall Out of a Plank
reducing-dishes
We have a wooden plank of the length `n` **units**. Some ants are walking on the plank, each ant moves with a speed of **1 unit per second**. Some of the ants move to the **left**, the other move to the **right**. When two ants moving in two **different** directions meet at some point, they change their directions and continue moving again. Assume changing directions does not take any additional time. When an ant reaches **one end** of the plank at a time `t`, it falls out of the plank immediately. Given an integer `n` and two integer arrays `left` and `right`, the positions of the ants moving to the left and the right, return _the moment when the last ant(s) fall out of the plank_. **Example 1:** **Input:** n = 4, left = \[4,3\], right = \[0,1\] **Output:** 4 **Explanation:** In the image above: -The ant at index 0 is named A and going to the right. -The ant at index 1 is named B and going to the right. -The ant at index 3 is named C and going to the left. -The ant at index 4 is named D and going to the left. The last moment when an ant was on the plank is t = 4 seconds. After that, it falls immediately out of the plank. (i.e., We can say that at t = 4.0000000001, there are no ants on the plank). **Example 2:** **Input:** n = 7, left = \[\], right = \[0,1,2,3,4,5,6,7\] **Output:** 7 **Explanation:** All ants are going to the right, the ant at index 0 needs 7 seconds to fall. **Example 3:** **Input:** n = 7, left = \[0,1,2,3,4,5,6,7\], right = \[\] **Output:** 7 **Explanation:** All ants are going to the left, the ant at index 7 needs 7 seconds to fall. **Constraints:** * `1 <= n <= 104` * `0 <= left.length <= n + 1` * `0 <= left[i] <= n` * `0 <= right.length <= n + 1` * `0 <= right[i] <= n` * `1 <= left.length + right.length <= n + 1` * All values of `left` and `right` are unique, and each value can appear **only in one** of the two arrays.
Use dynamic programming to find the optimal solution by saving the previous best like-time coefficient and its corresponding element sum. If adding the current element to the previous best like-time coefficient and its corresponding element sum would increase the best like-time coefficient, then go ahead and add it. Otherwise, keep the previous best like-time coefficient.
Array,Dynamic Programming,Greedy,Sorting
Hard
null
1,822
hello everyone today we are here to solve question number 1822 of lead code sign of the product of an array input type is list and output type is end means what a list and we have to determine the sign of the product of numbers okay so let's see what is the question there is a function sine func that returns 1 if x is positive minus 1 if x is negative and 0 x is equal to zero we have written one for positive minus one for negative and zero for zero okay you are given an integer array in terms let's product be the product of all values in the array numbers written sign func of product means we have to return the value from this function let's see the example nums minus one minus two minus three and if you product all the values of 0 in nums if there is a 0 then we simply return 0 now what we will count the number of negative numbers because we have to return just sign of the product of numbers not the actual product okay so you simply count the number of negative numbers for this as i am taking one loop to do complete iteration and if i is less than zero negative value of negative number is by one okay and what we have to return one if modulo of negative number is equals to zero else minus one a number of negative numbers even okay so what it will become positive in the case of positive what we have written here we have seen one okay and else minus one and for the third condition we had done it here on the first line so let's see let's run the code yes it's working properly let me check this with other example okay run the code yes it's working fine so let's submit the code let's see what happens like yes it's working properly and hundred percent faster so much okay i'm moving with this question and going to the next we will meet in the next video up to the end bye see you soon
Sign of the Product of an Array
longest-palindromic-subsequence-ii
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,3,2,1\] **Output:** 1 **Explanation:** The product of all values in the array is 144, and signFunc(144) = 1 **Example 2:** **Input:** nums = \[1,5,0,2,-3\] **Output:** 0 **Explanation:** The product of all values in the array is 0, and signFunc(0) = 0 **Example 3:** **Input:** nums = \[-1,1,-1,1,-1\] **Output:** -1 **Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1 **Constraints:** * `1 <= nums.length <= 1000` * `-100 <= nums[i] <= 100`
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
String,Dynamic Programming
Medium
516
112
all right welcome to this video we're gonna be solving Miko prom 112 past some so give you a binary tree right of numbers and then they'll give you some and you want you to determine so return true or false if you go down a route to leaf path when you add the numbers in each note you can get tolls some provide so in this case to give you 22 and our coach return true because this route to leave path 5 plus 4 plus 11 plus 2 will give us 22 and again a leaf is a node with no children so if you add to 22 say somewhere in the middle of a tree and it still has left and right children that doesn't count right ask me kind of like this clear path to where the last node doesn't have a left or right child so I want to solve this with helper method recursion because I find this the easiest way for me to understand recursion and also explain it so with that being said let's get started so I'll say let res be equal to false and then our helper method function will update this to true if there is a valid root to leaf path that adds it to the sum if there is not our helper method function will never update this to true it'll stay false and will still return the correct result so I'll call my helper function well helper and takes in a node right we're traversing a node a binary tree that has notes and then the second argument I'll call current some initially will be set to 0 when you first call our helper function but gets updated so I'll say if no note has been passed or res has been set to true return if there's no node we don't want to execute the rest of our helper function that makes sense or if res has been set to true up here then that means if we already found a path that adds to 22 we don't need to keep traversing the rest of the binary tree that's just extra redundant work right once you find one correct path we don't need to keep doing extra work so that's why I have this extra check here all right now I will say curse um or current some plus equals no dot Val right we check let me refresh this actually write each known should have a Val property yup that's the number so current sum plus equals no dot Val if the current node you're on does not have a left child and it doesn't have a right child right because it has to be a root to leaf path and a leaf is a note of no left or right child so the current node we are on does not have a left child and does not have a right child and the current sum is equal to the sum the target sum we're aiming for then let's update our variable res here to true so res is equal to true and then we'll traverse the left and right child so helper node left pass current some helper node dot right current sum alright so we just finished defining our helper function now let's actually call it so I'll do helper call it on the initial node they give us right passing an initial sum value of 0 and then once this helper runs if there's a valid root to leaf path that adds it to the correct some res will be updated to true otherwise we'll stay false so again this helper function will well make sure that this res variable is the correct thing it has to be and then I'll return rest now you like this kind of content please be sure to LIKE comment and subscribe and hit that notification bell so that you're notified of all new content and now let's make sure that my code passes the leet code tests so I'll paste it in and we're good to go was the past some complexity analysis time complexity is o of n because we Traverse every node in the tree space complexities o event because we use recursion our call stack could be of length of the binary tree all right that should be it for this video
Path Sum
path-sum
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22 **Output:** true **Explanation:** The root-to-leaf path with the target sum is shown. **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** false **Explanation:** There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. **Example 3:** **Input:** root = \[\], targetSum = 0 **Output:** false **Explanation:** Since the tree is empty, there are no root-to-leaf paths. **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
113,124,129,437,666
881
hey everybody this is larry this is day 13 of the january league 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 votes to save people uh yes i usually solve these lives so um even the explanations are definitely um yeah right fast forward towards the end if you're looking toward uh the solution or something but uh okay the eye of person has weight i each pro can carry a maximum rate of limit the bulk can contain two people at a time if the rate is less than limit we turn the minimum number of votes to carry every given person huh that's interesting um i mean so yeah and each one can be so the worst case is that given n people we have end votes um and now we're trying to figure out how to match them up okay so this is a little bit of trying to figure it out uh and i'm just thinking about different ways of uh well so the two things right one is i'm just trying to figure out a ways to uh use greedy in some way and then the other ring is just implementation um and how to prove them right how to prove greedy which is always the hard part for greedy i think the first thing i would do is sort them by the what was it by the way okay i don't know if that's sensitive these days but then my other idea is that because you the both can carry at most two people anytime you could carry two people it should be good if you um if you minimize or maximize the other person right so basically you want two people who will add up to be as close to the limit as possible and if you do that um and this is and some of my explanation with respect to this is just um playing around with a lot of numbers in the past and this is just like an experience thing where i believe um like i don't know if i have a hard proof for this video but um but basically the idea is that you know like if two people um have like very different weight and they're they add up to be near limit you um and this and one of them doesn't have a smaller uh fit you would say that um then it doesn't uh then you cannot get better fit meaning that okay let's say if you have a limit of five if um if you know if there's a person that's a size one um if it fits a four then that means that you know like any heavier person cannot fit with it and so forth right so what i'm thinking about that um and i know that's kind of a terrible explanation to be honest um but the way that i'm thinking about it is using that um we can do two pointers right we can just have uh appointed to the smallest person or the lightest person and the heaviest person and then kind of march much toward the middle um to get the limit and the reason why that we can do this is because like i said um i mean these examples are not very great for that actually but let's say we have um you know one two and this is also why we sort it um someone like that right well five you know that and let's say limit is five to be clear um if we do the five then you know uh you know five will be on don't vote for four and the one well we know that it cannot fit right um uh and let's just add another um let's just add another four for illustration but yeah we match to find the one i think that should be obvious at this point and then the second four well it doesn't fit with two and because two is the smallest number that it can be um that it can match with then you know that we could have to get rid of four so then we have three um yeah and then three and the two match so then we put them in the same boat and another three so i think that should be good enough for us to as a strategy because i think we can really work and it's like i said some of the reason why i don't have a strict mathematical proof because those things are always hard especially live because i'm not you know like i don't have you know references and studies for it but and some of that is where practice will come into play where if you deal with kind of the properties of these sweep line type uh numbery number line type problems enough then you'll kind of like almost be convinced about it so then after that just becomes implementation i think yeah i think the and you know i could have said the same algorithm in different ways and they have different implementation even though they might do similar same thing but what i want to do is that i'll take the max uh the heaviest person see if it fits up the lightest if it's if it is if it doesn't then um then the heaviest person gets his own boat i think maybe that's a more intuitive way of doing it or explaining it because uh if the heaviest person and the lightest person doesn't match up or like they don't fit on the same boat then you know that there's no way that the heaviest person can um can be with it's uh can be with anyone else right because everyone else is heavier so then they get their own boat and conversely um and if you kind of keep that in variant in place um that will always be true so let's do it that way um and there are a couple of ways to do it um you know there are a couple ways that we can think about implementing it uh but the way that i want to do it's a little funky um because about ah you could use two pointers i'll just use two pointers so heaviest is equal to length of people minus one so this points at the last element and then the lightest is equal to zero um and then just votes is equal to zero to begin with and then now we have a while uh heaviest um is greater than lightest so if they're the same what happens do we get to unfold we might have to test that one a little bit to get the edge case of weapons and they're the same i guess if they're the same that's okay but then we would have to add an if statement anyway so that's why i'm not doing it that way um because if you have to check an if statement inside whether heavier is equal to the lightest then you might as well do it out outside um so okay so if people the heaviest person plus the lightest person is less than or equal to limit then you know we vote in frame by one well we always increment by one in either case but if they're under the limit then we can go um uh we can move both the people that have a typo here i think uh otherwise we only move to the heaviest so we can actually even take this out and do it this way right and then at the very end if heaviest is equal to lightest um then we have to check that one case um then we just do both one and then we return both and this is not actually this doesn't always have to be true right this actually is only true if there's only one person left at the end um because you can imagine um you know if you have two three limit is equal to five uh the heaviest actually points the heaviest goes you know starts at index one lightest starts at index zero and then after one iteration this actually goes to zero and this goes to one right so this is actually um strictly less than so yeah um okay let's actually run the case first before i celebrate okay looks okay so let's give it a submit um sometimes i get questions about running time but in this case um i'm confident about looking uh like sometimes you know i mentioned it constrains a lot um and in this case because i kind of um did it this way uh i know that well the sorting is n log n obviously um and the rest is linear time so i don't look at constraint because you can't you know it's very rare that you can do it um better than linear time and sorting is pretty fast in general unless you're doing something really funky uh because libraries are pretty fast about it um but yeah so what is the complexion of this like i said this is n log n uh this is all and in terms of space um depending how you want to define it uh we either have no you know constant extra space or because of the fact that we sort the people and we really should not mutate the input we should probably create another way of the same size and you know copy it over before sorting it you know you could say that this is of n space as well uh in a reasonable way because p because now the person who passed uh you know their input here you know it got mutated but yeah um i think that's all i have i think you could also do like sliding window in the same similar way or two pointers by taking advantage of that um this is less than 30 000 but i don't know how helpful that is so yeah uh for this one because it is greedy uh i'm going to look at the solution and just go over with y'all um just to kind of see if i you know maybe there's another way maybe you know if there's a funkiness or something like that but okay yeah so basically this is the idea that i did so yeah except for their logic is the other way where um the lightest is with the heaviest okay so i guess that's the only um thing about it uh yeah now i like that they actually did the space complexes of n because i think um because of what i said about the uh the mutating input so yeah uh cool let me bring this back up so that you know you could snapshot it or whatever um but yeah that's what i have with this problem i think so let me know what you think uh hit the like button to subscribe on drum and discord these i would also say that these greedy problems um they take a lot of practice because the actual proofs are hard for me i actually find greedy problems harder than dynamic program problems because for dynamic program problems you're proved by being exhaustive where for greedy problems sometimes you know you have a hypothesis and then it turns out to be wrong um and you know and the good thing about lead code um is that you know you get one like they tell you what the case that you get wrong is and you can analyze that so that's why it's a good practice for greedy problems as well but yeah that's all i have for this prom uh i will see y'all tomorrow bye
Boats to Save People
loud-and-rich
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
Array,Depth-First Search,Graph,Topological Sort
Medium
null
238
hey guys it's off by one here and today we're going to be solving product of array except self so in this problem we're given an integer array nums and they want us to return an array answer such that answer of I is equal to the product of all elements of nums except the current nums so what does that mean exactly if we take a look at this example here we can see that the output array is supposed to be 24 12 8 and 6 and the way this is calculated is by on the first spot you multiply 2 times 3 times 4 for the second spot you multiply one times three times four the third spot you multiply one times two times four and so on the tricky part about this problem is that we can't use a division operation so we couldn't just go through the whole array find whatever the product is and then at the end just divide the product by whatever number we're at and store that in our answer array so let's think about another way to solve this problem without dividing if we take a look at our answers array we can see that the first entry is 2 times 3 times 4. and then the next entry is one times three times four the third entry is one times two times four and then the last entry is one times two times three if we take a closer look at what these numbers are we can see that for the first entry we're calculating the product of all the numbers afterwards and then for the second entry we're calculating the product before and the product after for the third entry similar thing we calculate the product before and the product after and then for the last entry we're only calculating the product before so what we could do here is have an array for the product before and the product after so it could look something like this the array before for one it would just be one because there's nothing before that for two it would also be one because one times one is one and then for three it would be 1 times 2 which is two and for four it would be six and then for after it would be two times three times four for the first precision and that is 24. and then for the second position we would have three times four which would be 12. for the third position we would have just a four and then for the last one it would just be a one because there's nothing after the four and then to get this answers array all we have to do is multiply each one of these and store them in our answers array so 1 times 24 would be 24 1 times 12 would be twelve two times four would be eight and six times one would be six the runtime for this algorithm is actually o of n which is great it's exactly what we want but the problem now is that we take up a lot of extra space here with these two arrays and we don't actually need them we can actually solve this problem with all of one space the way we do that is by having two variables one to keep track of the product before and one to keep track of the product after and the way we're going to calculate these products is by looping through the array once going this way and one's going this way because to get this we would need to iterate backwards so we can have four times three times two so I'm going to show you what I mean in more detail so I've initialized the array to all ones so we can multiply our before and after to it and to start let's go with this first position so there's nothing before so people just multiply the answers array by one and that gives us one and then we go to the second one before is still one so we're going to do that after is three and then we have 1 times 2 and that would give us a before of two and that's what we're going to do here and same thing for this last one we would have 1 times 2 times 3 which would make them before 6. and that's what we store here and now we're going to go backwards so our after we're going to start at 4 here and there's nothing after four so we just multiply oh we just multiplied by one and then we go to three the only thing after three is four so we would multiply um by four so just after now it's four and then we're going to go over to two and we can see that here we're the after is 3 times 4 and that would be 12. and then for the first one the after would be 2 times 3 times 4 which is 24. so now our final array will look like this 24 12 8 and 6. and that's exactly what we want here and this algorithm now takes o of n time and only takes up constant space because we're only using these two variables so now we can go through the code so to start we want to initialize our answer array which is going to look like this we want to set it to all ones for a size of nums and then from here we just want to initialize our two variables that are we're going to use to keep track of our multiplication so we're going to have product before and set that equal to one and then product after and have that equal to one so now we're going to iterate through the array forwards so for I in range of length of nums what we want to do here is set our answer array at I equal to the product before because if we think about it the first entry we don't want it to change we want it to be one because there's nothing before it and then after that you want to modify product before so it's equal to product before times the current value of nums and then now we just want to iterate backwards and the way to do that in Python is like this for I in range of length of nums minus one and then minus one that can look a little confusing but that's just how you iterate backwards in Python and what we want to do here is now multiply our answers array times our product after and if we think about it in the example there was nothing after four so it would make sense that product after is just one and then from there we do the same thing we did above where product after is Multiplied with the current number we're at and then from here we can just return answers and that should work so now I'm going to manually go through the code so to start we want to initialize our answers array with all ones so it's going to look like this and we want to initialize our variables to one which I did here as you call them b and a just to make them short and then we're going to iterate forwards so for answers at I which would be this position we want to set it to a product before and it's already one so nothing changes there and then we update product before to product before times nums of I which is 2. so now this is two and then we go to the next one and so now answers at I is going to be set to product before which is 2. and then product four gets multiplied by the current number which is three so now it is six and now we go to the next iteration so answers at I is going to be set to product before which is six and then product four is going to be updated to 24. and then for the last iteration here we are going to set numbers I to 24. and then B is going to be updated to 120 I believe and so now we're going to iterate backwards since we're done going forwards so we're going to start at 5 here so we can see that answers at I times product after is still going to be the same because this is set to one still but now we're going to update product after to be multiplied by five so I'm just going to do that and so next we go to the four and answers that I times product after is the new answer that I so this 6 will be multiplied by 5 which would be 30. and then this is updated to be product after times the current number which is four so we would have 5 times 4 which is 20 and now we go to the next iteration and answers at I times product after the new answers at I so 20 times 2 that is 40 and then our product after is multiplied by our current number and that is going to be 60. and then for our last iteration here we are just going to update answers at I by multiplying it times the product after which is 60. and that's our final answer if this video helped you in any way please like And subscribe because it really supports the channel thanks for watching and I'll see you in the next video
Product of Array Except Self
product-of-array-except-self
Given an integer array `nums`, return _an array_ `answer` _such that_ `answer[i]` _is equal to the product of all the elements of_ `nums` _except_ `nums[i]`. The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. You must write an algorithm that runs in `O(n)` time and without using the division operation. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** \[24,12,8,6\] **Example 2:** **Input:** nums = \[-1,1,0,-3,3\] **Output:** \[0,0,9,0,0\] **Constraints:** * `2 <= nums.length <= 105` * `-30 <= nums[i] <= 30` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer. **Follow up:** Can you solve the problem in `O(1)` extra space complexity? (The output array **does not** count as extra space for space complexity analysis.)
null
Array,Prefix Sum
Medium
42,152,265,2267
227
hey what's up guys this is john here so today let's take a look at 227 basic calculator number two and this is one of the uh the calculator series problems so for this problem there's no parenthesis and there's only uh two operators which is the plus subtract multiply and undivided and they're like us i think the total four calculators problems in lead code i think it's pretty i think they're pretty interesting so today i think i'm gonna try to use a like more generic way of solving this problem so that in case there is some any follow-up questions you can still any follow-up questions you can still any follow-up questions you can still use the same similar idea here so a few examples right so you know there are like some solutions that you don't even need a stack you can just use like several variables to track the other previously operator and the values but today so for my generic solutions i'm going to use two stacks the first one is going to gonna store all the other numbers and the second one will store all the other operators so how will this thing work right basically you know a few examples here you know so when with this kind of like let's forget about parentheses for now let's only consider this uh for our operators so when can we calculate the previously result the previously two numbers right so let's say we have two three plus two can we calculate this one probably not it's depending on the current operator right so at this moment you know we have a two stacks here so the first stack is three and two right and the second stack is the operator at this moment we have a plus one here right so that's the stack one that's the operator stack and now we're at the uh we're at the this multiplies here it depends actually depending on the priority of the operators here right because you know as you guys can see if the current operator is has a higher priority than the then the top then the first one in the operator stack then we cannot calculate those two numbers right so when can we start calculation we it only when let's say we have 2 plus 3 times 2 and then let's see that there's another time here right so now what we have another 2 here right we have another multiply and then we have another two here right so that's going to be our current stack now we're at this uh multiply operators here you know now the multiplier operator is not greater right it's not greater than the top one right then we know that okay so now we can calculate the previously result right and we do that until we have seen the uh so basically now we have this two times two here right so we just pop this two times two we have like what we have three and after calculations we add we push this thing we append the result back to the stack right now we only have this plus here right so that's that let's say we have another three here right so now what we have uh we have a three and then we have another multiply here right okay so this part is gone right we have that now let's see the next one is plus two right so what do we have you know since this plus is smaller it's not either equal or smaller than the top one right then we pop this these two out right it's going to be what's going to be 12 right because the 3 times 4 will be 12. so now we have 12 here we have 12 and then this thing is gone and the plus is still not greater than the top one right then we do what we do a plus which will be the 12 plus 3 which is which will be the 15 and then this is gone as and in the end the 15 is our final answer which is this answer right three plus 4 12 plus 2. yeah so that's the 15 right in the end here so we have a 15 here and now we are we just need to do a plus two here with that's why we're gonna have like another plus sign here and then about 15 we have a two here right so this is the new stack so in the end we all we have is this 15 and two left in this stack and then we have another the last class operator here so that the total the final result will be 17. so as you guys can see so the key logic for this kind of problem is that you know we have to know basically the priority of the uh the priority between the current operator and the previously our operators and we can keep popping up we can keep calculating the previously previous tokens you know as long as the current calculator is not greater than the top operator stack then we can keep popping those number one number two out and then do the calculation until we have reached the point that the current one is greater than the top one then we know okay we cannot continue we have to look for the next one all right cool so that's going to be our basic logic here you know i'll just i'll implement that one first and then we'll talk about the follow-up questions we'll talk about the follow-up questions we'll talk about the follow-up questions like the uh what happens if you need to handle the parentheses and what happens if you will need to support more operators other than this four right how can we do it okay cool so we're gonna have the numbers right at the stack and then that's stack one and then we have our operators right operators that's gonna be a stack too so a few like variables here right so then we have n here and then we have uh we have i here so i is from zero and then we have a while loop while i smaller than n right and then we start doing so since we have this kind of like empty strings you know the first thing to handle is like this just uh if it's empty string we simply i plus one and then i we just simply continue right so that's the first one and second one is always to uh to capture the current integers right so the card to capture current integers you know i just use this one let's use the if i if s i is digits right if the current is digit i just continue looping through moving the cursor to the right until we have reached a nine digit character right and then we have the uh the current number so that's why i'm going to define my current number equals to zero and then while i smaller than n and as i it's digits right then i just keep updating the card numbers multiply by 10 let them do a plus int dot s i right so that's that and then don't forget to do a high plus one here now we have the uh now we have the numbers here right so now let's do a nums dot append dot current number right so and here we're gonna have like some else here in the end we're going to do a i plus one here right but you know since as you guys can see here so we already do a whenever this while loop is finished the eye is has already reached to the next position here if we do a i plus one in the end there's gonna be a double increase here so that's why i just uh i just reverted back so that we all of the branches can still use the i plus one here it's a little trickier right i mean you guys can do something else but this uh this is just how i do it okay so that's that you know what so what is the house case so the else case is that this is the operator right so else case means that it's operator right operator and so like what we have discussed now you know the uh so the kernel so si is the current operators and we just need to compare the uh with the visit with the top one on the operators if the uh if the current one i mean if the current one current operator's priority is equal either equal or smaller than the top one then we can keep popping the numbers out and do the calculations right and to do that i'm going to create a few i think two helper functions here right like i said you know the first one is to get the priority right so i'm going to pass in the operators here right you know gift operators in what in the in plus and minus right then i give it priority equals to one right ask if the operators in what the to multiply or divide it i give it 2 that's the priority right and then i'm also going to create like another half functions to help me to do to evaluate right if i literate the numbers by passing in the number one number two and the operator okay so if the operators equal to plus right and then yeah we return num1 plus num2 right so i'm just going to copy and paste i'll see if this isn't miners we do a miners right so same thing for the time the multiply and the divide divided thing so we have a that and then we have a divided right so that's how we evaluate the our numbers here so like i said you know the uh so now we're at the uh that operator so first thing to check is that while the operator is not empty right operator it's not empty and the uh the pry already so we checked our operator it's not empty because you know it could be empty right this digits yeah because if we have two plus three plus six you know when we are at when we're at uh plus the first operators here right the operators is empty that's why we need to check this one so if it's not empty and then we check if the priority dot and that s i if that the priority of the current operator is either equal or smaller than the priority of the uh operators minus one right so if that's the case then we know okay we can calculate the first two numbers so that's why we do a num2 equals to nums pop right and then num1 equals to nums pop here so keep in mind here so the first one got popped out his num is num2 and second one got popped out is num1 so the sequence matters because we're going to have like this multiplied subtract and divide it so we have to make we have to follow this sequence here and of course then we have a after popping two numbers we need we also need to pop the uh the operators out right operators dot pop and then we can just evaluate the numbers after the evaluation we can we need to append this back to this nums stack here so we do a evaluate right by passing the num1 num2 and operator cool so that's that you know that's how we calculate the previous ones and then in the end here in the end right so now after this while loop here what might end up in these nums and operators you know if we have like 3 plus 2 times 6 so what we have in the stack will be something like this will be three two and six so and in the operator stack we have plus and the uh and the multiplier right because we're only doing this kind of calculations when there's like multiple when there is a case right when the current one is smaller than that than the previously operators right but if it's always increasing the priorities you know we might end up something like this after the while loop that's why in the end we also need to do a while loop similar like this one to evaluate the numbers to evaluate the uh our stacks so we can simply copy and paste right here and then let's do this yeah so that's that oh i think one thing i forgot to do here is that you know we forgot to append the operator stacks operators dot append as i because the isis is the operator right all right cool so and then i simply return the nums dot minus one because after this final while loop here we have evaluate everything in the stack so we can simply re return the last the only number left that's going to be our answer so yeah i think that's it i think let's run the code out of index what is out of the index these digits um operators oh wait maybe here operators okay yeah i mean i'm missing an as here same thing here okay 51 operators oh i'm sorry here so um so in the fight in the final while loop here we don't need to care or worry about the priority here because for all the priorities we need to be taken care of we have already taken care of it here so what's left here we can just we can simply calculate evaluate numbers from top down here that's why we think we can simply use the pr the operator operators stack to uh to evaluate the uh the value all right run the code all right go accept it submit all right so success i mean yeah so that's that you know the as you guys can see here you know the time complexity time and space complexity so the time is just a while loop here right from 1 0 to n here and so here even though we have we might have a nested while loop here but each element will only be pushed and put popped out from to an in and out of the queue only once so that's why the total time complexes of n and space complexity is also of course o of n right cool so that's that and how about some follow-up questions follow-up questions follow-up questions right i think the uh i think the first follow-up i think the first follow-up i think the first follow-up questions is like the uh besides this these four operators what how about to support more operators let's say how about this one three times plus five times three and then we have a power of two how about this right because this power operator has a higher even higher priority than this than the multiple and divide right i think the fix is pretty straightforward because we have been taking care of these things here you know we have a while loop here so all we need to do is this is just this all we need to do we just need to add an another branch in the operator in the priority here if these operators is equal to the power right then we simply return three that's going to be our the priority three operators and here we also just need to add another if condition here if this thing is equal to that we just need to do a right power evaluation here okay so that's pretty easy and how about to uh how about to support the parentheses right so to support the parentheses you know the uh we have to basically add two more out condition here right so the first one simply the uh else if the s i is equal to the left parenthesis you know actually there are like the way we're doing is like we just need to add this left parenthesis to the operators stack so that later on we can keep popping up the operators until we have seen the left parenthesis right then that we know that's when we should stop the while loop so we just append these things to the left parentheses without operators that's all we need to do when we see a left parenthesis and more work needs to be done when we see an ending parenthesis right so when this thing ha when this thing happens so what should we do you know keep in mind that you know so it's going to be similar like our final while loop because all the uh the priority related calculations you know have been taken care of in this while loop here and so that no whenever we see an ending parenthesis or we are we have reached the end of this uh string here we know that we can just safely and doing we can safely do this kind of pop thing from the top to calculate that and then add it back and then we can just do a evaluation by with those two numbers plus operators so that's why actually we can simply copy and paste this part and but the only thing we need to add here you know is and what and the operators and operators minus one that this output minus one is not equal to this left right we keep doing this until we have seen a left parenthesis then we know that's when we should stop right and then after this while loop don't forget to pop this left parenthesis out it's going to be another operator's dot pop yep i think that's all the follow-up follow-up follow-up for this problem you know like this is like a generic way of supporting to evaluate any of the operators including the uh to print this cool so yep that's it okay i think i'll stop here and i hope you guys enjoy watching this video thank you so much and stay tuned i'll be seeing you guys soon bye
Basic Calculator II
basic-calculator-ii
Given a string `s` which represents an expression, _evaluate this expression and return its value_. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. **Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "3+2\*2" **Output:** 7 **Example 2:** **Input:** s = " 3/2 " **Output:** 1 **Example 3:** **Input:** s = " 3+5 / 2 " **Output:** 5 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of integers and operators `('+', '-', '*', '/')` separated by some number of spaces. * `s` represents **a valid expression**. * All the integers in the expression are non-negative integers in the range `[0, 231 - 1]`. * The answer is **guaranteed** to fit in a **32-bit integer**.
null
Math,String,Stack
Medium
224,282,785
290
hello everyone myself Rahul so today I am going to solve a problem related to Strings so the problem name is word pattern so let's go through this problem statement so here we are given a pattern and a string s we have to find if s follows the particular pattern the same pattern so here the follow means a full match such that there is a bijection between a letter in pattern and no empty word in s right so through this the things are not very clear but let's go through the example so the pattern is a b a and the string given is dog cat and dog right so what does bijection mean over here is that for a particular character in pattern there should be corresponding word in a string so if we observe carefully the character a can correspond to Dom and the character B can correspond to character similarly this third character B can also correspond to the same cat and the last character a can correspond to dog so for each individual character we have a corresponding word Associated so in that case we have to return true another example is a b a and uh the string like basically the pattern is same but the string has changed from this to this so if you look here so a corresponds to Tau B corresponds to suppose cat then again the third B will correspond to cat this is fine till now but the last a is corresponding to fish over here but the earlier a was referring to dog right so it means this is not a well-led pattern or is not a well-led pattern or is not a well-led pattern or um valid string so we have to return false in this case right so there is no one-to-one mapping as such one-to-one mapping as such one-to-one mapping as such right so let me uh try to exam uh explain this using an example so the first example we can take is a b so this is the pattern that has been given to us and suppose the string given is dog Space Cat and again spaced on right so what they mean is that each individual character in the pattern this is the pattern and this is string s right so a got supports to dog so if a is corresponding to down then B is corresponding to cat oh sorry cat and this B is also corresponding to cat this mean which means it is fine so we don't need to update this data structure right so suppose we are maintaining that in a data structure and this a is called again corresponding to dog which was already present inside this data structure so it is also fine so in that case we have to return true right so in the other example if instead of a b a uh like let's keep it same Abba but instead of dog cat get down the example is dog cat and fish right so here it is corresponding to dog then comes space then we check the second character B with cat so B corresponds to add then comes again third character there is a space so this V is also responding to cat so B is already present inside this data structure so we don't update that then this a is corresponding to fish but a was already present inside of this data structure let's we will decide on that like what data structure we can use so his order a is corresponding to fish which is not correct because it was uh already referring to term so this is not correct so we will return false in this case right so how are we going to solve this problem so the first approach the brute force method the most intuitive method over here is can be like somehow we need to maintain the mapping between the connector and the corresponding string associated with that right so how are we going to maintain that using a hash map right so if we create a hash map of care and strings where the character is the key and the value is string is in the word and the character is in particular character in the pattern right so in this hash map so basically this is a hash map only so like a is the character and what is the value it doesn't put string that is the word a dot b cat and then comes the third character which is again B so before inserting that inside the map we will check whether this character was already present inside our uh map or not so B was already present inside the map so we will we can ignore that right and before ignoring me you should also check whether the second beat this B is also corresponding to the cat or not right so instead of cat suppose here it was some other animal suppose lion or any word right so B was already present inside the map but the value would have been different cat and lion so it's a contradiction so we would directly return holes from that condition only that place right but uh yeah coming again to a this a then a is corresponding to down we check whether a is present inside of one map using uh just a find operation and the value is again down so we can ignore that so we will be returning true right so the edge case that we would be missing over here is that um suppose um yeah let me just figure out okay so suppose this from the case a b a and uh here it is dog and again dog right so suppose this is the string s which is given to us this is the pattern p so corresponding to a we have dog inside of a map then comes B so B was not present inside the map this is the map key and value so initially we inserted a and down then we come B and this term and we check whether B is present inside the map or not using the key B so B is not present which means we have to insert this B right so uh but we would be inserting this B inside the map which is not correct because there has to be one to one mapping right so dog cannot be referred by two characters so this is not a correct scenario so to overcome this what we can do is like this can be the hash map one and we can also create another hash map let's call it hashmap 2. inside which the key value will pair will be there and the key would be string and the value would be character basically the reverse part of this uh earlier map right so whenever I inserted a and off so I can also insert dog and a over here then comes B and dog so before think of B and down right so B and Dom so here I will check whether B is present inside the hashmap one or not it is not present then also I am going to check whether dog is present inside the hashmap 2 or not so it is already present which means this is not a valid scenario basically both of them has need uh has not to be present inside in any of the maps right so these two uh Maps would help us basically tell us that no two characters are corresponding to a similar word or two same words are not corresponding to different characters like in this case dog is being referred by A and B so if we would have been using just a single hash map then we would not have been able to solve so that's why the hashmap 2 comes into picture that through which we are able to look up whether there is a character associated with that particular word right so this is one of the approaches of the time complexity over here would be the length of a string end of the string okay so and the space complexity is like we are using two maps so twice of what can be the maximum length of this so it can be the number of unique characters present inside the pattern plus the length of the string so basically the unique characters in the pattern plus the length of a string which is s right twice basically two types of that because we are maintaining two maps right so this is one of the approaches but we have a optimized approach to this as well like instead of using two maps can I solve this using a single map or a single data structure so the answer to this is yes because if You observe carefully in the problem it is mentioned that the pattern only contains lowercase English letters right so we can take the advantage of this condition so lowercase English characters which means it will lie between a to z right the pattern characters and how many are these it is 26 right so what we can do is we can create one array so this approach is actually being used at a lot of places where there is already a condition that the string characters are going to lie between 0 to 26 as in like uh per cases of lowercase characters can be present so instead of A to Z if capital A to Z are also present then instead of 26 we can create an array size of 52. but if it is already given that it will be lowercase character so I can create an array of 26 size so indexes will be 0 to 25 so basically each index is going to represent a unique character so this is going to represent a and b e z c and the last index is going to denote Z right so what I am going to do is so suppose this is the string a b a then comes stock cat dog right so I go through this first character a and then check what is the values on top and I am going to initialize all of these values suppose with spaces or any random uh string right so corresponding to a I will find what is the index in this array how we can do that a minus this so this is going to give me the Sky value of a right so I um so it will give me zeroth index so I will go to the zeroth index and check what is the current value so it is currently empty so I will insert dog over here then I will go to B corresponding to that the index will be 1 and I will insert cat in this string array so it is a string array and again for responding to B I will see what is the value it is cat so I will look inside my array I will see that it's already capped so I can ignore that I will go to the next pattern character corresponding to a it is dog I will go inside my array I will see what is the already existing value if it is not there right so it is already log so I can ignore that so once I have reached the end of my pattern so it means that all the characters have been I traded over so I can ignore I can return true from the Loop right so let's try to see what is the how I have coded that so I've already implemented but I will try to explain what's the logic behind that so I've created a string area of 26 size and initialized all the elements of that string array with spaces right then what we need to do is so initially we are given this string right dog space cat space dog so what I have done is I am creating a list of words out of that so instead of list like I can say Vector in C plus so what I have done is I've created a list dog cat and dog so that would require string passes but if you are using Java then you can directly use a split function which will give you this list right so in C plus uh to get the corresponding words out of this string I have written by while loop which like if you are in an interview then enter your might want you to implement this functionality as well like interviewer may ask you to not use the existing STL and instead of that you might have to write this logic yourself right so this logic is nothing but creating a list of or the vector of words in the given string s this one right so we have a word list associated with us now right so in one more condition I am checking over here is just that like the size of the list should be equal to the number of connectors in the pattern right so here we can see we have four characters so correspondingly we even having four words over here so if it is not the case then we have to return false right so that's the basic check I'm doing over here and uh the this for loop I guess like I've already explained so I'm taking one um character in the pattern at once so that c is equal to pattern of I right and here I am checking whether I'm I am looking for that particular character for the first time or not so if I am looking for that particular character for the first time right so here I am checking that uh like if the value if that particular word was already present in some other index or not right so in this example A B A and uh sorry this one a b a dog right so this was let me just quickly explain this example so in this vector 0 1 2 3 we have talked to this 45 so in the zeroth index it will be dog then comes B and this dog right so B is nothing but the first index so I can't directly insert raw in this first index why because dog was already present inside the zeroth index so before inserting I am I treating over the complete array of length 26 whether that particular word was already present inside the array or not it if it was already present then I need to return false right and otherwise if it was not present and then I just directly insert that particular word inside in that particular index so C minus a would give me the index in that particular array ARR and uh if it is not the equal like array of C minus a would give me the index value and it is not equal to word list of I which means I have to return false right if any of these condition is not uh met then ultimately I am returning true which means I have reached the end of my pattern string right let me run this and it's already tested but still oh yeah runtime memory usage are fine so as you can see like runtime and memory usage are on a very uh higher side so that's because like we are just using an extra space of 26 length instead of creating two maps that was there in the first Brute Force approach right and um yeah complexity wise as well like if we look over here is the time complexity would be if we have the given string then we are iterating over the complete string and uh in the worst case for every scenario I will be doing that 26 number of times because here I am checking right in this for Loop I'm checking whether that particular word was already present inside in any of the or indices of the error vector or not so in the first case that will be 26 times but that would really happen right it's a Time complexity where it is that and space complexity wise it is just of 26 which is constant so we can ignore that oh one right so we have a reduced space complexity part where the time complexity Still Remains the Same right so that's why memory usage is on 83 level like this yeah so I hope the solution is clear so please let me know if there is a better approach to this problem or if I have made any mistakes over here or any improvements are needed so until next time take care and I will see you thank you
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
1,591
hey what's up guys this is john again so uh this time 1591 stringed printer number two so this time the stringer the stringed printer will print following the below the two special rules here on each turn right the printer will print a solid rectangle and this will cover the existing colors in the rectangle and second once the printer has used a color then the color same color cannot be used again so which means that one color can only be printed once okay and then you're given like a matrix and the value on the matrix are the targeted values and your task is to check if it's possible to print the start matrix by using this string printer otherwise false so for example this one right so the target matrix is like this so obviously the first time we need to print one and the second time we'll print two okay and the example two is like more complicated one so for this one the again right the first time we'll print once on all the uh the cells and then the set and then we print three and then we print uh either five or four it doesn't really matter so that's that and they're like there are a few examples that cannot print to the final result and there's some constraints here right so i'm like within 60. so how do we approach this problem right the uh i think one thing we might uh we need to observe is that you know for each of the colors and in order to be able to print this color it has since it has to be a rectangle it means that we need at least for each of the colors we have to print within a range right because it uh the printer can only print the uh a rectangle so which means that for each color the first thing we need to do is that which we need to get uh the border for this color basically the left the right the top and the bottom so which means that we can pre-process so which means that we can pre-process so which means that we can pre-process uh this matrix and we can use a dictionary or hash map to store the uh the four borders for each color and once we have that i think next thing we have a we have some options but the way i use to solve this problem is that by using a dfs search and to be able to write the dfs logic so we also need to explore some of the examples that can that will return false so for example this one right so for this one we have one two and one two one so why this one is false right this is because let's say uh we start we try to print uh from left from uh top left corners and then we try to print everything so here if we if you want to print one since the border for one is what is from left to right basically is everything it means that we have to print uh ones all together and then by while we're printing once since we have a two here and if we want to print two right then we also need to print uh the entire like the uh array here at the in the entire board here but while we're printing two here we see okay so there's already a one that we have been previously printed and then that's why the answer is it's false right so another example is like this one so we have one and then three one three again right so first we print one and one once we print one there uh the next one we wanna print is three but while we're printing three here we see that okay so while printing three we need to print this one we also need to print this one two to three but we see okay so what this number here is one which have which are the ones the colors we have been printed pro previously that's why we need to return false so then we have this conclusion right so the conclusion is like this so every time when we do a dfs print every time let's say we start from one here and we start from one and then we try to print out everything based on the borders of the current colors and once we have seen a different colors and then we'll start print that one we'll start print that color basically that's a dfs recursive call and every time when we try to print the colors if we have seen a cell that's that equals to the previously uh scene cell the colors are previously printed colors then it means that it's a count there's a conflict then we need to return false because for example if this one since it's returned true let's see let's say we are printing one here and then we are looking we have a three now the dfs will go inside to print three right so we bring this one and this one because uh but there's no ones on the range of three right because while we're printing three there all we can see is three or four right so because the last one is four but it doesn't really matter because four has not been uh seen or has been printed yet only one has been printed yet as long as there's no ones while traversing uh while trying to print three then we're okay right and then so while we're at here that the three has been printed with no issues right and then the last one is four actually so while we're seeing four there we'll start printing four so the four is also okay because there's no one or three while printing four and then five so on and so forth so which means that we're going to maintain while we're doing the dfs we're going to maintain the uh like a previously printed colors but basically it's going to be a set and then we decide we just try all the colors if odd colors have passed the dfs track then we're going to return true otherwise as long as there's no color one color that failed and then we know okay there's uh there's going to be a it's going to be a false cool so then let's try to do the coding here um so like i said i'm going to create like a border like as a dictionary to store the uh the butter for each of the colors right and then we have a m the length of the target grid i'm going to do this and then equals the length of the target zero right so for i in range of m and for j in range of n so the current color the color is the t i and j right so if the c is not in the border dictionary right so we simply do have other colors equals to what the uh basically i'm having four uh elements which is the top down left and the right else which is update right we update the border of c equals to the what so first one is the left right we could do a minimum of i dot uh bother dot color dot zero okay right that's the left and the for the right is max right i dot the other c dot now this one is one right then similar for the top one minimum of j dot other c dot two then i have like uh the bottom ones maximum j dot father c dot three yep so that's how we uh do that i think i have a okay yeah so now i can just simply loop through the other colors right so the colors is actually the uh it's the set in the bother the key of the bothers right so i can just do a this one colors right and then um we're going to have like two things so we have the first one is the scene the same one right the scene the set and then we have a in progress it's also a set so we're basically maintaining two sets here so for color in the colors and if not dfs right if not dfs colors then we simply return fast because it means that this color has a conflict which means we need to return the fast otherwise in the end we return true here so now the uh the dfs right so for the dfs you know like i said so if each color basically so that one of the exit point an exit entry uh point is the uh if the current one in the in progress right then we just return fast like i said right because if the current one has been uh printed previously and then we just returned fast and then otherwise we just do a we just try to print right visit uh for this color basically we have the border of the so it's going to be a color dot zero right that's going to be the row and the other dot color dot one plus one similar for the uh for columns we have j here it's going to be a two and a three okay and then basically if the target.inj if the target.inj if the target.inj it's not that it's not equal to the current colors then we need to do a uh another dfs right but first you know since we are but first we need to update the process actually yeah we need to up uh like add the process right in process one is the current one um yeah and then we do uh and then later on we'll remove it okay so that's the because you know whenever we need to do a recursive dfs car a dfs car here we need to up add the current one to this in progress so that later on you know the uh we can use this one to act to return files here and then basically if not dfs right so if the df has to return false here we need to uh going to be a uh target inj right if this one is false we also return fast here and in the end we return true so yeah so basically here i'm doing the uh every time when i see a different colors while printing the current colors i'll go like to print try to print that color okay and while printing that colors right if the color has like uh has a conflict with the previously printed colors then i simply returned false and as long as there's one uh element that can return false then the whole thing will need to return false otherwise if everything works fine then i will return true and that's how the how i check the colors okay so that's the basic logic but if you just leave the code as it is right now it will tle so the reason being is that you know let's say since we had we're doing like a for loop check here right and for each of the photo pier we do another and we do another like the uh another dfs which means that if we have like a many ones here right for example for the first the for the first one you know dia we uh while processing the current colors we might also like what uh we will also try we also print basically process the nested colors and since we were looping through all the colors because one let's say if there's like one here right so if they're like a 10 colors if well and the first one is the colors that we process first right and then we'll basically while processing the first colors since we have dfs here we will also process all the nested colors inside so that's why we need to introduce a second uh second set here to help us to not reprocess the same colors that's why the uh every time right once a color it has been printed successfully which means that uh the for loop is finished which means that we have print all the cells for these colors we're gonna add this color to the thin set and then on the top right we can just do this if this color has been processed we'll we think we can call it this one process or uh let's do this print it and this one is print printing one then print it so here if the color is has been printed before then we simply return true right because it means that you know it has been processed so we don't need to check that otherwise you know so this one is printing right and this one and same thing for this printing and this print i print it okay yep i think that's pretty much it is so run code current oh c yeah okay so accept it right so how about the time and space and time and space complexity so for the time complexity uh so here we have m times n right so here's the m times n but that's not the uh but that's not the dominant dominating time complexity is actually this part so here we have um the first one is the color let's see the first we have a c means the total number of colors and then inside here we have what we have in each of the dfs we have a for loop okay so the for loop is going to be a c times m times n and inside of inside the four loop here we'll also do a another dfs call which means that you know we're going to have like another times c here so this is because we only do the dfs when the color is different than the current one that's why at most we will do a uh the dfs uh c times dfs car using one uh within one loop right that's why the uh the total should be i think c times m times n time times c yeah and so that's the time complexity so for the space complexity it's just the uh the border and the uh the printed and the printing colors yeah i believe the butter will be the dominating space complexity because this one has like uh has a space so the colors it's going to be as four times c right because for each of the colors we have four elements but for the printed and printing here right it's all basically it's a it's all of c right but now it's this is a four times c so that's the gonna be the complexity analysis here um cool yeah i think that's it so this so for this problem you know the um two things right so first you have to uh you need to pre-process the border for you need to pre-process the border for you need to pre-process the border for each colors so that you can uh use them try to print them out later on and second one is that you know you have to be able to find the uh what's going to be the condition for returning false and with the condition is the uh while printing the current color right and then uh if we see a different colors we'll i will try to print that color instead and while printing that colors if any uh if any cell right that on the current path while printing the current colors is the colors we have been printed before then it's going to be a false otherwise it's going to be true so that's why we basically we're introducing two set here so the first one is the printed which help us to record what are the colors we have been printed successfully right then to avoid some duplicate duplicated calculation second one is the printing for the current colors right so if there's a uh how many uh colors we have been printed before which is our printing and here's like backtracking okay because you know the i think this place is this part is always kind of obvious because after printing the current colors right we are we're not printing that colors right for example the three and four and so once the color has been printed successfully and then the uh we need to remove it from the current printing set yep i think that will be everything i want to talk about for this problem okay thank you for watching this video guys stay tuned see you guys soon bye
Strange Printer II
strange-printer-ii
There is a strange printer with the following two special requirements: * On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle. * Once the printer has used a color for the above operation, **the same color cannot be used again**. You are given a `m x n` matrix `targetGrid`, where `targetGrid[row][col]` is the color in the position `(row, col)` of the grid. Return `true` _if it is possible to print the matrix_ `targetGrid`_,_ _otherwise, return_ `false`. **Example 1:** **Input:** targetGrid = \[\[1,1,1,1\],\[1,2,2,1\],\[1,2,2,1\],\[1,1,1,1\]\] **Output:** true **Example 2:** **Input:** targetGrid = \[\[1,1,1,1\],\[1,1,3,3\],\[1,1,3,4\],\[5,5,1,4\]\] **Output:** true **Example 3:** **Input:** targetGrid = \[\[1,2,1\],\[2,1,2\],\[1,2,1\]\] **Output:** false **Explanation:** It is impossible to form targetGrid because it is not allowed to print the same color in different turns. **Constraints:** * `m == targetGrid.length` * `n == targetGrid[i].length` * `1 <= m, n <= 60` * `1 <= targetGrid[row][col] <= 60`
null
null
Hard
null
332
all right let's look at this problem called reconstruct itinerary so you're given a list of tickets uh ticket represent uh starting airport and ending airport and in your list of tickets is for a single person and you're also given the starting station the starting airport so you started from JFK you have to reconstruct the itinerary in the order and return it so for example in this case from these tickets you can create a directed graph and you know gfp is a starting point so you just Traverse and you go to HSC and this is quite clear uh there's one more condition that is given which is if there are multiple itineraries you should return the itinerary that has the smallest lexical order when it is a single Stream So what let's understand that in the second example so in a second example you can create two itineraries one as you go from JFK to SFO but in this case because ATL is smaller so you would prefer this one you have to handle this as well so how do you handle this so the simple way to handle this when you represent this graph in adjacency list like for example here for each node or when you are adding the neighbors you add those numbers in sorted order and you can use your priority view for that so when you look at JFK um you see a ticket from JFK to SFO QT another ticket from JFK to API so let's say first you encounter this JFK to our support so you add this in the priority queue and then when you add eight years because it's bright if you the first element which will give you will be the smallest one so that is a bit 200 lexical order but just like second order is not sufficient so what I mean by that is look at this example now here let's say a starting airport is given as a so yes you can go from A to B but then you are stuck right so yes you want to give reference to be representatively mean that will give you the right uh itinerary here in this case the only valid identity is you go from a to c from C back to a and then from A to B so yes you want to give priority to lexical order but that doesn't necessarily mean um then that will give you the right technology so you have to consider both practices order and I want to uh itinerary so let's look at an example to sort of understand how to solve this so I want to see example of this example so first of all let's try to understand uh let's say these are the different tickets these are different graphs that are given to us and we have to find a valid itinerary here so we have to find a valid path that uses each ticket once and only once and the ticket here is Edge right so it sort of forms a directed graph which has a eulerian path that's what it really means so let's first understand what eulerian path is so let's write out the in degrees and out degrees for each of every node integral is essentially the number of edges coming into the node and out degrees the number of edges going out of the node so let's look at a and here for example let's assume is a starting table is given to us so from a how many uh how many edges are coming in just one how many edges are going out you can see there are two right for B how many X's are coming in we can see for B there are two edges coming in and one Edge going out for C even if there are four total edges two are coming in and two are coming out and same is the case for D there are one two three four two coming in and two coming out and then for E there is one coming in and one coming out now we don't have to really look at this it is already given to us that this a valid itinerary does exist but the sort of tools so in a directed graph uh a valid euclidean path exists in two cases one either all the nodes have their integral degree equals in this case that's not the case you know for c d and e then individual degree are same but for not for a and b so that's the other condition if all the nodes have equal integral outages then you even have a euclidean cycle A and B have exactly one difference in the end degree analytically and in a the out degree is more than b the in degrees mode this tells you there will be a cpedian path it starts from here because this is an extra out degree right so there is one path going out extra and for B there is one path going coming in extra so a will be the starting point we will do the ending point and C and D will the middle once so that is the strategy now we want to sort of also build what you said is the adjacency is less also build out the adjacentialist presentation right so you have your a b okay and you want to follow the lexical order so from a what all nodes you can go to you see there are a is an out degree of two so you can go to B and B you put it in sorted order so BND from B you can go to C from C you can go to A and D to give reference to a from B you can go to b and a you can reference to B from e you can go to C that is your adjectives representation of the graph now what do we start from a okay so we go a and we keep following this classical order so from a you go to First cry which is B so you remove this because your Traverse this and so you go to B from B you will go to C so you remove the C from C you go to a remove this a from a you go to D we remove this D from D you go to B so you have an even preference electrical order so far and you are not stuck here it's all good from D you go to B and at B are stuck all the edges have not been completed but you are stuck so what do you how do you handle it at this point so this premises order tells you if where your is your ending point so now let's call this as the final i t in Array and you find itinerary B is the one that will be the last to reach and now from D we went into B so what you do is okay B I know is the last five let's remove B and let's continue so from D you can further go to E okay so let's do this so from B now I go to e from E I go to C from e I go to C and from C you go to D and now at B there is nothing else so now that means this is the last most node so now in front of d asically what you can do is now because everything is empty you could you can just put uh the entire this video from D to B is already a path right that essentially means that your final path would be you add this B here then we'll go to C and you do the same thing again so now see you see if there is any further paths that you could look at they are known here so you will see then you would look at the key and you would see there's any further paths to go at e here there isn't for you and that is how you sort of build from E then you add C then you add a then you add C and you add p and then you add you have a and select your final path from ABC to go back to a then you go to D then you go to e c d and then B and that's your final path so that's the plate right so how do you have a code for it so essentially first you create this ad essential list with the priority queue then you start from a till you get stuck you keep privacy then you get stuck because where you guys stuck is the last guy and then you continue remove that guys and then you continue again when you get stuck that is your second last guy again then you get to that's the third line square and so on and so forth right let's build out a code for this okay so the first things first you want to build an adjacency list so let's uh hash map a key is the airport name and we are using a priority queue to prefer the lexical order so we use a priority queue um let's call it expensive list uh what else we have uh let's maintain a linked list of spring which is our final itinerary let's call it route and as you saw here we are sort of maintaining a stack right and we've got that we removed that we added it here and then we continued further so for that let's maintain a stack right and let's first build the addition how do you build that sense of this um so for each ticket foreign destination is one so if adjacency list does not contain the key for source then you first add this Dot okay so now you are guaranteed that adjacency list dot get Source will give you uh that is a priority queue in that priority queue you add this destination right so your list is complete now what you do in the stack you know the starting point is JFK that's given to us so the first there is always JFK so you add JFK and now while your stack is not empty keep on just traversing and at some point you might get stuck and we'll handle that when you get stuck is when you take the first uh the topmost element on the stack and then continue right so okay let's call it last right so if or other while no it's quite okay so how do we handle this weekend last equals to you know if last well if you're struck how do you know if you are stuck right so you're stuck if you are not presentation start contains key if you don't even present content key or the list is empty let's dot get lost Dot either the keys not present if it's present in sample in this case what do you do well in this case you do that so you take the filament out of the stack and out in this route Dot you add it in the route okay let off so you add um you can also do like so you take it out and then you add it right that is good and if that's not the case then what do you do kind of simple you do start dot push body push in the stack uh so you want to remove the edge right we were removing the action now we are looking at for example from JF for example from here you went so you push into the stack now from a you want to push B into the stack but you also want to remove this uh Edge right so what you do is you do when this is a string let's look at you remove it and then you add it here that is it and again obviously stack won't be empty so you'll either remove it no you push right and that's it and so at the end of this you do return group okay let's run uh fix the compilation error it's a runtime error okay if adjacency is not contains key okay it's not it's r alright accepted submit and it gets accepted so that's it we can talk about time opacity clearly you know it's just a number of edges so slang compressor is just oapy space complexity how much elements can be written as tax orp so both times Your Capacity is over weak all right
Reconstruct Itinerary
reconstruct-itinerary
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it. All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string. * For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`. You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once. **Example 1:** **Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\] **Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\] **Example 2:** **Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\] **Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\] **Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order. **Constraints:** * `1 <= tickets.length <= 300` * `tickets[i].length == 2` * `fromi.length == 3` * `toi.length == 3` * `fromi` and `toi` consist of uppercase English letters. * `fromi != toi`
null
Depth-First Search,Graph,Eulerian Circuit
Hard
2051,2201
850
alright guys welcome to our channel code with sunny and in this video i will be talking about the heart problem of the lead code its index is eight five zero and it is its name is like rectangle area second okay so before moving on to discuss this problem is like i just want to summarize the topics that is being related to this one is like geometry you need to have the good knowledge of geometry like the figures how the overlapping is being done how we are going to handle the overlapping like in this problem we have some overlapping of figures and we need to calculate the area right so and for the case of overlapping of figures you need to consider that area exactly one time okay how we are going to handle all that case and what would be the best way to code i will tell all of that for now let's understand this problem okay so we'll be given a list of axis aligned rectangles okay so each rectangle will be given the four datas like the bottom left corner you can see x1 y1 and top right corner x2 y2 right are the coordinates of bottom left corner and the coordinates of top right corner of the earth rectangle okay so we'd be given n rectangles find the total area covered by all rectangles in the plane that is if you draw out the rectangles then there would be some they'll be occupying some area and we to report the all the area that is being covered now it is obvious that two or more rectangles have the are going to occupy the same area in the 2d plane then we need to account for that area exactly one time you're not going to count two or more times if you're going to count two or more times this problem should not be a hard problem right okay since the answer may be too large return it modulo this prime number okay so i'm going to discuss all the examples okay so you need not to be worried about so for now let's look over the constraints how this is going to help us okay you can see the rectangles length that is the input rectangle that is the total number of rectangles is 200 okay so we can have a of n squared solution we can have a offensive log of n solution right because it is also going to satisfy within the given time constraints uh we can also have n cube solution like it should be around 8 into 10 wish to the power 6 and this is like within the limited number of iterations and this is good okay so for now in this uh like in this video i have i'm going to explain it out the off and cube solution in the best possible way like uh i know the complexity is like huge we can have both n square solution also but to understand this problem to have a deeper feeling about this problem what is actually been happening over here i will recommend to like to understand the open cube solution then we can optimize that okay and there is another solution that i am also going to discuss it should be like of n cube logarithmic open and logarithmic and that is not good but it has a good complexity i don't know why ah we will discuss it later on for now let's try to understand this problem with the help of examples and diagrams and then we together find out the best solution for this problem so let's move further okay so let's try to figure out the analyze of example one okay so we'd be given the first rectangle as zero two okay so let's say it is like zero that is at this position and it is like 2 and 2 that is 1 2 it is at this position so the very first rectangle is about this one okay i'm going to do like that okay so this is the area that is being covered and this like the answer is going to be like at least this one also okay but there may be some overlappings let's discuss it about one zero two three is another like one zero so it should be like one okay so let me use another color it should be like x one and it is y zero so it is over here and it's like two three two one two and three yeah it is this one so it means that the like the rectangle is going to hold this one area okay now you can see that this area is being overlapped okay so we are not going to account for this area because we have already find out that area okay so we are always going to consider some unique areas for the given rectangle it is like only this one okay and let's look over the another rectangle one zero three one like its of one and zero and it's of three and one two three and one okay so this one in this one it means that all the positions over there now you can see that there is also some overlapping so we need to consider only the unique area so we are going to consider only this one okay so these are like the shaded part is like our answer and we need to report that answer so what is the answer you can see one two three four five six i think six should be the answer for this one yes it is the answer okay so it means that you need to account for the like distinct blocks that is being not repeated like if you have been already calculated that area we are not going to do that okay now the thing is like how we are going to manage that and like in a limited time we have to write down the code right so we need to have an efficient way to find out that area and check that these are going to be like accounted for the very first time if it is a repetition you're not going to do that okay now the problem arises when you can see the rectangle so 5 is like 10 raised to the power 9. now if it is around 10 raised to the power 5 you are going to maintain a linear vector or 2d vector or something like that i don't know and you are going to do that easily but here it is like 10 raised to the power 9 and this creates the problem how we are going to find it out that there is an overlapping over here okay so no need to worry about let's try to understand this in a different okay so consider this example like there is some overlapping you can see over here then what i am going to do is like the best way to solve this problem is like map all those x coordinates which are distinct right i'm talking about the distinct x coordinates in some vector linear vector like in a sorted non-decreasing format so you can see 0 non-decreasing format so you can see 0 non-decreasing format so you can see 0 70 100 220 270 and 320 these are the distinct x coordinates you can see 0 70 100 220 270 and 320 are the distinct x coordinate similarly we are going to map all the distinct y coordinates over here these are the y and these are the x okay now these are the distinct ones now the thing is like when we have having some rectangle we need to uh include that area which are not which have not occurred right so mapping these x unique x coordinates like this one and unique y coordinates like this one is going to help us in the best possible way also note that we cannot maintain a linear size vector of the maximum possible height orbit because rectangle of ij can vary up to 10 raised to the power 9 and if you are going to make a linear vector of like for the x coordinate and y got size to a 10 raised to the power 9 this is not possible right come on okay so we have to do something interesting and the interesting part is like we are going to have a unique x coordinate in some linear vector unique y coordinates and some linear vector now how we are going to calculate the areas okay now consider that we're going to have a like we are talking about the very first rectangle this is being introduced right now okay so you can see that it is going to vary from 0 comma 0 to 100 comma 100 right okay so it is going to vary from like x is varying from 0 to like 0 up to 100 and y is also varying from 0 to 100 okay now we need to include all those areas which are for this rectangle okay how we are going to do that okay the very best way is to like consider every adjacent part 0 to 70 and consider like not talking about consider every adjacent ones like for 0 to 70 there are 0 to 10 adjacent 10 to 30 adjacent and 30 to 70 adjacent 7200 adjacent like for every 0 to 70 x segment we are having different y segments as 0 to 10 like uh this is for 10 1 like for every 0 to 70 we would have being uh sorry 0 to 70 only we're having uh y from 0 to 10 and like from 10 to 30 also like from this to this we would have be having like of this one and similarly we're having from 30 to 70 so where is 70 or 70 is up to this one we would be having this one and it's 7200 where is 70 and it is hundred we would be having this and you can see that we are accounting for only the distinct ones still this rectangle contains much more area which is not covered we are going to introduce it later on you can see i'm talking about only 0 to 70 part what about 70 200 we would be discussing later on okay so for 0 to 70 we'd be dividing each segment from 0 to 100 where the y coordinate lies into some different parts you can see from 0 to 10 from 10 to 30 to 70 and from 7200 okay now for every adjacent coordinates difference in the x part we are going to find out the every coordinate difference in the y part and we are having the length also grabbing the width so our answer would be incremented by length into width for the current rectangle okay now like if let me just do some brute force like if we are only dealing with 0 to 70 what is the difference in x okay difference is x is 70 minus 0 it is it would be 17 only difference in y would be like 0 to 10 in this case our answer would be incremented by 17 to 10 and again uh like again in the next case 17 to 10 difference of 10 and 30 is 20 and again the next 30 and 70 so 17 to 40 and then again 1700 so it would be incremented by 17 to 30. these all are the answers that should be included when x is going to hold this range okay now the x like the adjacent ones in the x can vary from more different cases like we have deal with 0 to 70 we are going to deal with 7200 like for this part okay so x like y coordinates is also going to vary from 0 to 10 to 30 and like 30 to 70 also and similarly from 70 to 100 also and so on okay now this is not the like this was the very much easiest part now when we try to introduce the new rectangle like of this one okay so now this creates some confusion like there's some overlapping also let's try to understand that how we are going to handle that overlapping now consider the case like this is being involved like this rectangle from this one to this one and from like this one to this one now you can see for this rectangle it starts at 70 x coordinate and ends at 270 like this part we need to account for every possible areas okay and let me check it out if there is an overlapping also and it's y corner starts from 30 and it goes up to 130 like of this one okay now uh when you try to explore every possible adjacent x coordinate like from 70 to 100 you can see and for 7200 we are exploring like 30 to 70 y and 7200 this one and 100 to 130 now when we are at 30 to 70 you can see that uh for every like for 7200 and this is for x and for this is for y like if we find out the 70 to 100 keys uh where is that 70 yes and where is that 100 like for this part and uh what about the okay so what about this 30 to 70 and where is the 30 y and this is the 30 y and uh where is that 70 yeah this is the 70 point okay now the thing is like when we are just having this as our answer for this current case you can see that this has already been calculated okay why this has already been calculated okay the quite noticeable like quite noticeable thing over here is like when we are calculating 0 to 100 and like for this very first rectangle 0 200 and y is also varying from 0 to 100 okay in that case for every adjacent x you can see that we are going to visit 7200 in this one also and we are also visiting 30 to 70 in this one also okay so in that case we have already find out that area okay but now in this case also we are trying to visit from 72 to 17 the difference of x and in the case for y we are visiting 30 to 130 also in this case also for adjacent difference of 7200 like for the 7200 segment in case of x we are again visiting 30 to 70 and this is like when we try to include this area this will give us a wrong answer because this has been calculated twice we need to take it out that this should be visited exactly one time okay so if this is already visited this state has already been occurred we are not going to find out that area otherwise find out that this area and included your answer like in the case of 7200 i'm talking about consider the case for 22 20 to 270 okay in this segment we need to include the answers for every y at every adjacent consecutive y from 30 to 70 200 like it is the case of 2220 but it is at 220 yeah this is and it's for 270 and why is going to vary from this one to this one okay yeah i'm right okay so in for that case we are going to include this area every time like you can see this is not calculated yet okay and if this is being called calculated we are going to mark these cells as visited how it is going to be done i will explain in the coding part and mark this cell as we did and when we are going to encounter these cells again we are going to discard that cell because you have already calculated that area okay now the coding part is like very really very much simple if you consider like if you have understood understand all these concepts how the overlapping is being occurred and how we are going to find out the area we are going to map out all the distinct x coordinate in the linear vector and similarly y coordinate coordinates and we are going to account for every adjacent difference of x coordinates and y coordinates for every rectangle that we are going to get okay so let's move further to the coding part to understand this okay so you can see that i have many i have submitted many times to improve the complexity okay so let me first talk about this latest one okay so what i have done is like this is ll fall as long and this is the modulus prime number and like first i have mapped all the unique x coordinates and y coordinates you can see that for every rectangle i have rated for that and take out their x take out their y and include into a set okay now this part is like assigning the indexes like uh we are going to map all those unique x into some vector like here you can see vector int x value vector id y value you can see that this is like x dot begin up to x like all those lm unique x which are present in this set and similarly the unique y we are going to store it in a vector like when we try to fit some element and we need to know its index also right efficiently that's why i'm using an unordered map to map every unique x as well as every unique y by giving some unique index to it okay you can see over there okay so what we are going to do is like we are also going to maintain a visited vector of the like unique x size and unique y size okay and this is for checking it out whether we have reached this state already or not okay i trade for every rectangle pick out the corresponding x coordinate if we have some like we are getting some unique value right and we are going to find out what is the coordinate of that unique x in our vector x val you can see start of x okay is going to give us the starting coordinate of this current unique value and it is going to go up to the next starting chord like for the current rectangle if you are not understanding it clearly like suppose we have from 0 to 100 comma 100 what is the starting coordinate of this one it is 0 and ending coordinate it is up to 100 okay so it will give us the value coordinate like the index starting index of this 0 and the starting index of this 100 okay for the current rectangle you can see v2 will be given as this position okay and it will give us the coordinate we are going to iterate for every adjacent ones you can see the start of x is starting with the current index of this unique value and it goes up to of v2 like a start of x less than the index of v2 and it goes on and similarly for the case of y you can see coordinate of y it will give us the index note that c o r d underscore x as well as c o r d underscore y will give us the index of that value which is so that unique value that which is present in our linear vector where it is present directly in the index okay that's why i've used another map to map every unique value and assign its index now consider the case like when we are talking about some adjacent keys like let's say 0 to 70 then what we are going to do we are checking out if the start of x and the start of y is already visited like if current state has been visited we have already found out the area then we are not going to do that otherwise find out the width would be y x value of this start of x plus one that is that like if you are at this one we are going to have the 70 as the start of x plus 1 index 70 minus 0 you can see and similarly this was the width and heat would be like y value of start of y plus 1 minus this one this is the width of the current one and this is the height of the current one we need to include the area answered been incremented by the product of this one note that we are going to take care of the modulus because of the overflows like the value may exceed from that prime number we need to take the modulus with that and mark this as visited okay and finally written on the answer this will give you all test cases first now the thing is like we have some more optimized solution like of this one or let me talk about this 28 msi solving that okay so what i have done is like the concept is like similar we are going to use the lower bound technique okay so you can see that we are going to map every x unique x into some coordinate of x in a linear vector similarly in this one and we are going to have a visited vector also now for every uh like in the previous case we are using the concept of index rate we are not going to use here we are going to use the concept of value like it will start from the current value and it will goes up to till it is not equal to the v2 that let that is like the next value okay in the vector you can see it is for the coordinate of x okay now similarly for the y case also and pick out the difference like the current uh where is the present value like its index start of x minus the begin iterator similarly start of y minus the e nitrate note that here start of an x and start of y are the i triggers okay in the like you are taking the lower bond only you're not fetching out the index and it goes until it like the next value is not equal to v2 and we need to find out the width as well as say we are going to fetch out the next element and with the current element is start of x similarly start of y and start of y also next element of start of y and start off y and find out the product and increment your answer if this state is not with the trick this will also give you all test cases first okay so if you have any doubts do let me know in the comment section of the video okay so like one thing i also forget the one like time and space complexity so this case like when we are mapping the indexes so it should be like time complexity like of n cube you can see for these three loops worst case would be like of n cube similarly space complexity would be like of n square and in this case also we are using have to have a lower bound also concept so in this case we are going to have a time complexity of o and cube log of n and similarly uh yeah and the space complexity would be like of n square okay i am leaving up to you to understand this in detail if you have any doubts do let me know in the comment section of the video okay and i will recommend or i will ask if you like this video share this video and subscribe to youtube channel for latest updates thank you for watching this video
Rectangle Area II
insert-into-a-sorted-circular-linked-list
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**. Calculate the **total area** covered by all `rectangles` in the plane. Any area covered by two or more rectangles should only be counted **once**. Return _the **total area**_. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** rectangles = \[\[0,0,2,2\],\[1,0,2,3\],\[1,0,3,1\]\] **Output:** 6 **Explanation:** A total area of 6 is covered by all three rectangles, as illustrated in the picture. From (1,1) to (2,2), the green and red rectangles overlap. From (1,0) to (2,3), all three rectangles overlap. **Example 2:** **Input:** rectangles = \[\[0,0,1000000000,1000000000\]\] **Output:** 49 **Explanation:** The answer is 1018 modulo (109 + 7), which is 49. **Constraints:** * `1 <= rectangles.length <= 200` * `rectanges[i].length == 4` * `0 <= xi1, yi1, xi2, yi2 <= 109` * `xi1 <= xi2` * `yi1 <= yi2`
null
Linked List
Medium
147
169
hey if you're welcome back to the channel I hope you guys are doing extremely well so this is another video from the Strivers A to Z DSA course just in case you're for the first time here this is world's most in-depth course in this is world's most in-depth course in this is world's most in-depth course in DS algo why do I see that this cost us 456 modules by the end of the post you would have sold more than 400 plus problems in DS algo and you can go across the entire internet you can buy any of the paid courses none of them will be covering DS algo in such step so one thing that I can assure you is once you complete the entire post you can actually clear any of the DS algorithms in any of the companies in any part of the world so till now we have covered uh dell certain arrays of certain array of zeros ones and twos and in this video I'll be covering majority element so what does the problem majority element States it states that you'll be given an array of integers now your task is to find me the element that appears more than n by two times very important lining more than n by 2 not equal to two it has to be more than n by 2. Imagine n is eight then it should appear more than four times imagine n is 9 in that case 9 by 2 will take the floor value it is four so it should appear more than four times got it so in this array if I ask you which is the majority element how many like what's the length of the array three four five six seven is the length of the array can I say two appears for four times which is greater than n by 2 so 4 over here is your answer and this is what you have to tell me given an array tell me the element that appears more than n by 2 times so what will be the Brute Force solution to this particular problem it's going to be very simple I'll pick up an element and then I'll scan through the entire array basically do a searching through the entire array and I'll count plus and if at the end of the day the count appears to be greater than n by 2 for any of the element that is my answer first I'll pick up two next I'll pick up 3 and scan through the entire array this is what the Brute Force solution will be and the code will look something like this so it's very simple you just iterate through the entire array for the first time pick up two and scan through the entire array and keep a check and count after you have scanned through the entire array by taking array of I you check it the count is greater than n by 2 if it is then you return array of I and forward like out of the for Loop you can return -1 just in case there is no return -1 just in case there is no return -1 just in case there is no majority element so this is how the Brute Force solution will look like what will be the time complexity obviously we are using couple of Loops so it is we go of n square and when you give the solution to the interviewer will not be happy and will ask you to optimize it this is when you'll be giving the better solution so what will be the better solution The Brute is taking n Square so we know one thing for sure the better solution will be somewhere of the order n log n or B go of n or 2N but it is definitely going to be better than n Square so if I have to think what are we actually doing we are counting and we're looking for which element appears more than n by two times so yes we can use hashing it's very simple if there is a count we have to keep a track of how many times a Dockers the only technique that comes up to my mind is hashing that is what I will be doing so what I'll do is I will declare a hashma with the element and the count where the element is my key and the count is my value so this will be the representation in the map for a clear n value now what I'll do is I'll be like let's scan through the array it is two so I'll put that 2 and I'll probably tell him you okay once then I'll move and then I'll say you okay twice then I'll move and there's a three I'll say a doctors once then I'll move and there's a three it occurs twice then I'll move one occurs once then I'll move two occurs twice then I'll move two occurs four times so once you have completed the entire iteration now it's time to iterate in the map yes it's time to iterate in the map so if I iterate in the map you will see that this particular Guy 2 occurs four times which is greater than n by 2 which is three so two is your answer so just I trade in the map and see which element is occurring more than n by two times so let's quickly quote the better solution of the problem link will be in the description so we need a map to keep the count cell declare a map okay what is the next thing we have to iterate so let's quickly iterate and now once am I trading I'll say ma what's the element vfi do a plus so with this iteration I will be marking it in the map now what is the next job I trading the map and see which is more than n by two times so this is how you iterate in the map in C plus the Java port and the python code is in the description and now you say ID dot second because that is the value is greater than are you greater than V Dot size Y2 if you are then near the majority element and you know the key is very simple it's at the first place so the key will be the first place if after this there was no one you can simply say return -1 return -1 return -1 and now we will quickly go and run this off and see if it is running fine okay looks like it is not why is it not tap was not declared let's quickly go and declare hashing clue everything is running absolutely fine now it's over the time complexity can I say the first Loop is running for bego of N and there's a ordered map used which is going to take logarithmic of n if you use something like unordered map then this logarithmic of n will go off only in case of average and best case in case of worst case another map ends up taking the ego of end time within itself so that is an N login and what is how many elements are there in the map imagine you're given an array something like this then each of these elements will be in the map so thereby the worst case the map might end up taking n so what is the total time complexity can I say it as we go of n log n again depending on which map you're using and a big go of N2 Traverse in the map ever the space complexity we go of n because you are storing all the elements in a map data structure so this will only happen if the array contains all unique elements remember this so the moment you give this hashing solution to the interview he'll be like hey wait you are using an additional space complexity can you please optimize this that's when you'll be talking about the most optimal algorithm and that will be using something as the Moose voting algorithm now sitting in an interview you cannot invent this algorithm so you have to know this algorithm beforehand so you might be thinking but does that mean we have to mark it up no the interviewer will be grilling you on thought process and intuition if you mug up the algorithm and you just present it line by line you'll understand that you have marked up the algorithm so please make sure you understand the thought process intuition and the algorithm in depth so please make sure you watch the video till the end because you're going to take away a lot of things when the video ends so how will I be explaining this particular algorithm what I'll do is I'll do a Dryden of the algorithm and during The Dryden I'll be sharing the thought process and the intuition behind every step that this algorithm does so that it sticks to your mind okay so what is the algorithm all about it's very simple it's about two variables element and Dot initially count is zero and you can say initially the element is not initialized and we start iterating so whenever we are iterating and we are the first element or whatever if the count is zero that means we haven't taken any array please hear this out properly we still haven't taken any array so you will be like okay I will take seven and I'll increase the count to 1. so what I did was I said I will consider this 7 to be my answer I'm just taking a hypothetical assumption that 7 is my answer and the Countess one and now let's start moving we again move to seven like seven now this occurs twice five no it is not seven so you reduce the count remember this count is not storing how many times seven appears it doesn't have some other significance which I'll say next again seven increase next again five degrees next one degrees so whenever you find 7 you increase because 7 was your element whenever you find anything apart from Seven you decrease now you are reaching zero until how much till this portion let's understand what so if you take seven five one this is an array rather this is an array and the count over here is zero what does the count signify so you took the element seven how many times does it appear three times how many times the author elements appears where other includes five and one the other element appears three times this is the reason when there was a seven you did a plus so there were three plus done and when there was five one there was a minus 10. so 3 plus 3 minus ended up giving you a count of zero can I say something for sure if I just consider this array 7 is definitely not my major retirement why if seven was my majority element how can you cancel because for if an element appears more than n by two times there is only one limit which appears more than n by two times and you cannot cancel it all if there are six elements and seven appears four times can you cancel four to cancel 4 you need four more so it's not possible since 7 appeared three times in a six length array which is not greater than n by 2 it is equal to n by 2 so it got canceled so something that I can assurely say is till here 7 is not my majority element till here it's not so this cannot be considered as an answer but what I will do is I'll move ahead and I'll move to 5 okay the moment I move to 5 I find count is zero so what I'll do is I will just quickly say okay listen count is 0 so can you please take this as my new majority element and probably I'll start checking from here and my count will be one perfect so I will take five I'll make the count one let's move seven it's not equivalent so I'll just make it zero I just make it back zero so this time the array finishes here and the count becomes zero again eminent if I just take this particular array can 5 be the majority no that's why next we'll move ahead the moment we move ahead what will happen since count is 0 it will again initialize count to 1 and element to be five and we will start the array again from here and this time again let's move it's five increment it is seven decrement so can I see in this particular array what happened five seven what I can say is hey 5 was occurring twice seven hours occurring twice so it brought cancer thereby count was Zero thereby 5 also cannot be my answer so till now whoever I have considered as a majority got canceled by similar elements so till now no one has dominated we are still looking for someone who is dominating got it everyone has still no cancer let's go ahead what is the count value Crown's value is zero now so let's move it we are at account zero so again we start the count will again become one and this element still stays as five this time we'll move ahead count becomes 2 7 will move out count becomes three this term will move ahead count becomes four and we can say we have ended the iteration so since we have ended the iteration there is an element five this count has no significance but we have an element five this element 5 will be your maturity element if there exists a majority element why because everyone else got canceled off within itself so if there is someone still remaining who did not got canceled then that is my answer but am I sure that element 5 is the majority element what I said if there exists a majority limit it will be five and no one else if there is a majority element it will be five and no one else if there doesn't then okay fine for example if the last portion was something like one in that case you'd have bought one and the count would have been four but is one the majority element if you see one just appears four times maybe five that's it one app is five times and when you look at the length of the array it is six two four and four which is eight plus four twelve it's a 16 length array someone has to appear more than eight times to be majority and since it is five let's see 5 is so let's see how many times five is once twice four five six seven eight nine five appears nine times out of which four times when not canceled but the other times it was canceled so the other five times zeros canceled got it so I can say five is my major element it's a very simple process the first process is to apply moose voting algo okay about the second process verify if the element that you got is the majority or not how do you do it whatever the element is in this case the element was 5 just iterate through the array again and see how many times 5 appears this time it will come out to be 9 which is greater than the length 16 by 2. so that's why the 5 is if it doesn't then it is not got it so I hope you've understood the intuition it's very simple if someone appears more than n by two times it will not get canceled quite simple right that's the intuition so coming back to the code editor again the problem link will be in the description so what do we need account zero and we can keep an element normally now let's quickly start off with zero and probably V Dot size yes and how can I say first thing that I will check is what if the count is 0 I know for sure this is where I'm starting a check for a new section so ground will be one and the element will be V of I right but what if the count is not zero in that case I will check if V of I is equal to the element that I was thinking it's the majority if it is please increase if it is not okay let's reduce simple three lines if the count is zero we just assign and we move I plus if it is equal equivalent we just increase count and we move if it is not then we decrease and then we move so what will happen is when you're decreasing if the curve becomes 0 when you increase and when you come back the count will be checked with 0 and it will be replaced with the newer limit and it will start a new section quite simple and once you've got the element just iterate over here and V Dot size all right plus and you say Hey listen if V of I is equivalent to element probably you can keep something like counter one equal to zero and you can say counter one plus if at the end of the day counter one is greater than V Dot size by 2 again you can store B dot size in some variable this particular element is the answer or else you can say the answer is minus one or whatever they are asking you to return so what I'll do is now I'll quickly go and run this off and see if it is running fine no it does or it'll be counter one plus counter one done and let's quickly submit this off I hope it does run now remember one thing whatever is the value of counter at the end it doesn't represents anything so we have to talk about the time complexity how much a single Loop and three Fields so it's a single Loop so whenever it's a single Loop you know the time complexity is very simple it's we go off n for the burst iteration of the most voting algo and if they are stating that the array might have or might not have a majority limit then you go and verify this step will not be done if the problem states that their own ways exist a majority element then this step will never be done okay you only do the step if the prop if the array might not have a majority element got it so this will be the time complexity and we are not using any extra space so this will be the space complexity of the most optimal solution coming back to the sheet I can say that this particular problem is done and if you understood everything please do with that like button is just one like it won't cost you anything please do consider hitting that like button and look at your tradition do comment understood so that I understand that you understanding everything and if you're new to our Channel please do consider subscribing to us because it's like 1 23 am in the morning and after my office hours I'm recording this video so if you consider subscribing to me that will motivate me to make such more videos is broken don't ever forget you're golden I will find
Majority Element
majority-element
Given an array `nums` of size `n`, return _the majority element_. The majority element is the element that appears more than `⌊n / 2⌋` times. You may assume that the majority element always exists in the array. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** 3 **Example 2:** **Input:** nums = \[2,2,1,1,1,2,2\] **Output:** 2 **Constraints:** * `n == nums.length` * `1 <= n <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow-up:** Could you solve the problem in linear time and in `O(1)` space?
null
Array,Hash Table,Divide and Conquer,Sorting,Counting
Easy
229,1102
1,728
hey everybody this is larry this is me going with q4 of the uh weekly contest 224 uh cat and mouse 2. so i actually thought this one was a little bit easier than q3 for me but uh but that is not the general uh consensus so i don't know about that uh only 49 people solved it this problem um but for me and i there might be other ways to do it uh because there are this is just to be honest um scanning over a few solutions which we can also do in a little bit um you know it is just straight up game theory and that's my solution uh hit the like button hit the subscribe button join me on discord let me know what you think about this problem this very hard problem so um so for this one there are two observations that i made um one is that it doesn't make sense for the mouse to stand still so that way it eliminates some of the psychos i don't know if it's that helpful to be honest but that was one of my initial dots and then the second one was that uh the mouse cannot get to within a thousand turns the cat wins but it turns out that it's actually um not even as bad as that it turns out that there is a case do i have it here i didn't i don't i lost the case but so it turns out that the worst case is actually not that not a thousand so you can cash it in a much more straightforward way so let's say you have a mouse next to the cat and you do it one by one the actual actually the worst case is something like this oops um nope basically sit uh sit sagging uh all the way oops uh that's pretty much the idea and basically what i did during the contest and you could watch me solve it live afterwards um did i tell you to hit the like button yet i don't remember uh if you didn't hit the like button hit the subscribe button and join me on discord and everything i don't know today's a long day basically i don't even know if this is length eight so maybe i'm off by one but that's still the same idea which is that um so what i did was that i got this test case and then i just counted them out um because if we uh you know we base the idea off that the mouse will always move then the longest way that it could get to the end is about like 70 moves which is about like the distance is about like 35 or something like that and then 35 times two for the cat and the mouse so actually in my code i have a magic consonant that's 80. and after that it actually is just straight up uh game theory um and my code is actually i want to say it's very queen version of the game theory um and we will go over it together but this is basically the idea behind it and i would also say that if you don't um if you don't know game theory this is actually a little bit tricky to go over i would definitely uh i would definitely recommend you know understanding game fear and how it works um i'm gonna go over it for sure a little bit but probably not as in-depth as you know something that as in-depth as you know something that as in-depth as you know something that you know like you need the background a little bit i don't want to make it sound like this is easy anyone can do it i mean anyone can do it but you just have to learn to write things first um and i you know and i don't want to make this like a huge lecture because game theory can get a little bit hairy so okay so then so but the intuitive sense is that okay i just i reduce this to dynamic programming kind of i have a cache um and i keep track of and my states are kind of weird but we'll go over together so my end result is okay can the mouse win if the mouse is you know in the mouse location given that the cat is in this location and the turn number is zero um and i have like some pre-processing stuff that have like some pre-processing stuff that have like some pre-processing stuff that puts you know the mouse and the cats and the robots in the right place and then now here's the mouse win function this should be very straightforward um in terms of understanding i hope um like i said the key thing is just cutting it off that turn is greater than 80. um and then here this is just already relatively straightforward thing of okay if i'm the mouse i'm going to try this move right if i move to a place you know i'm trying to figure out with my current location my current state of the world is a winning state it is a winning state if i'm at on top of the food which is the base case um it is a losing state if the turn is you know too far in the future which i said is 80. um you know if we are able to get to a another similar state in which the cat cannot win then this is a winning state that's basically the idea um because if i'm able to go to a move where the cat cannot win then i'm going to take that move because the cat cannot win and then you kind of do that recursively um we'll talk about the cat win function i actually separate them out um not everyone does it this way but i feel like this is a this makes it way more readable but uh but basically okay given the mouse wind function i literally look at every direction and this is just you know up down left right um hmm that's interesting actually this is unnecessary so maybe i made it even slower that's uh because i forgot that i actually go into the other direction anyway um but i was thinking that maybe i jump into the wrong direction so actually this is a little bit even slower so i could actually reduce this to be faster by doing this uh though so that's actually whoopsie daisies uh because directions should already take care of the directions so i don't have to do negative jumps in the other direction but i think while in the contest and it's still passed so it's still fast enough um but in any way so now looking at this new code um you know this is just basically okay i have a direction and i'm gonna move mouse jump distance away um if the new space is on the food space then i return true because that means that i'm one move away from true uh if it goes out of bounds uh i break out the loop because that means that you know i jumped out of bounds and i don't need to go you know loop anymore um if this is a war then we also break because we cannot jump over a wall and this is why we have to make sure that we jump in the right order um and then if those things are not true then we will try to jump here if we jump here and the cat cannot win then that means that we're going to jump there because the cat cannot win um that's basically the idea and then we'll go look at the cat one as well i did a little copy and paste so the s thing doesn't make sense here too for some reason i thought i had i could do a negative jump but actually let me change that so that is a little bit cleaner uh but yeah but now this is the cat jump code uh so we go over each state can the cab win is this a state in which the cat can win it the cat can win if we could get to the foot first which is true uh if it is in the same space as the mouse then the cat wins um otherwise and we you could do something about turn but i leave it to the mouse so it's fine i don't think it matters that much uh but yeah so the key thing the other thing is that note that um we have to move so i actually made this observation before i made the turn i think now that with the turn um you know it's not that necessary actually but i just wanted to make sure that uh you know um you know it could stay in the same space um because we want to do that where on the mouse um it always for me it just made sense that the mouse always had to move and the cat could stay in the same space if it doesn't have to move meaning that it could just block uh or something like that's why i checked for it here but otherwise it's the same thing which is that the cat this is a winning state for the cat if it makes a move and that move means that the mouse does not win um so this is kind of a recursive uh logic and f uh understanding there and that's pretty much it um again you know uh we do the cat jump distance thing uh we check that with this next you know if it's on the food then the cab wins if the new space is where the mouse is then you also win you know you cannot jump over um you cannot jump outside and you cannot jump over walls otherwise you check whether you know if the mouse cannot win once you move there then it is true also the mouse cannot win if you just do nothing then it's also true otherwise this is a four state because that means that just every move you make uh the mouse will win so that's basically the idea and that's pretty much it with the game theory um and that basically is the recursive function uh the dynamic programming function um but yeah um let's see yeah so the complexity um i'm gonna only do the complexity for the mouse it should be the same for the cat um so what are the number of possible inputs well this is eight right so rose times column is equal to eight times eight which is 64. um and then we have you know mouse bow times column is equal to 64. cat rose times column is 064. so yeah and then turn as we kind of have a bound here it could be only be 80 right and actually it's half of that but um but yeah so then now the complexity just uh the space complexity anyway it's just this which is 64 times 80 which is about 300 000 uh i mean you know um yeah right um so that's going to be fast enough so that's our complexity um in terms of space for sure and for each one of these we have you know directions so yeah so we have four directions times uh the number of mouse jumps which is i think also i mean at once it could be eight so it could be also 32 uh so then the worst case time complexity is just you know all this together which is this times 32 which is equal to roughly me plugging into a calculator uh about 10 ml right so yeah and if you want to think about complexity it's just o times r times c uh times you know square because of the both sides uh times uh max turn which is in this case 80ish and this is the space complexity and then the time complexity is this times uh four which are of course we can rule out and times um you know r plus c because um because that's how far the mouse jump can be in the worst case and again the four drops out so then this is the final complexity which is yeah so this is the time complexion and this is the space complexity which i think the test case is a little bit generous otherwise i don't think this should be passing uh especially given the number of test cases that they have um because uh so yeah doing this um i definitely had doubts about this uh problem as i was solving it because uh i wasn't sure that this was gonna be fast enough because um it depends on the number of test cases that they have because for each individual test case i'm actually confident that they will pass but in the worst case it might not because uh or in the worst one case it will pass but in lead code is the total amount of time you take for all the test cases so i was worried about the number of test cases as a result um but otherwise um yeah and i got a wrong answer because i thought the worst case was actually a spiral but it turns out that this was a little bit uh longer so i should have used 80 instead because i it was a smaller constant because i did a spiral i counted the spiral and it was like 25 steps or something like that but apparently it wasn't far enough um so yeah um that's all i have for this problem uh it's a very tricky game theory problem um to get the complexity right so um so yeah let me know what you think uh every second counts for this problem so yeah let watch me stop it during the contest next ah dumb mistakes let's see okay well only one person got this so that means that my ranking reply based on this uh q3 which i didn't do really fast oh late curse well done um well a lot of people did this very quickly i don't know smart people and i have two penalties on top that's not good okay let's focus uh but this is gonna be hard for him if it takes two good people 20 minutes and well alex well done okay focus that what am i doing okay so just great i mean cheesy answer is just mini max but i don't think that's right or like not enough the only 64 space 64. those states trying to do some kind of crazy mimics mouse can win so is this a winning stick that shouldn't be that hard maybe let's see okay let's try it okay so the 64 times two so 800 states so state is what is that what are the states oh my god this is so annoying to write in python actually okay so the winning state is we find f the mouse is in fx after they move okay just go to i'm surprised not more people gotten this so i think maybe this could be harder than i think i don't get it this is just mini max know so hmm that's not a good sign for me you i think the assumption maybe we need to request something i don't think this is going to be we'll see if it's fast enough i'm going to be upset with it uh the most always wants to move i think so i think that's the trick so and now we can go see you check okay you hmm okay so make sure we turn something so just cut doesn't have to move you nope ready so i have a typo oh where does this x even come from wow how come it's not complaining i even use x somewhere in here that's terrible so there's a cycle of sorts alright get rid of this cycle from it going back and forth we've got hmm i don't know why i did it with dpi financial i've done it with uh the other way should have done it with a graph search maybe perhaps a thousand though that's gonna make it big okay i don't think it's going to be fast enough to that's the problem is true force was true force true huh why is this i gotta return true for this uh what's the input cat jump is two mouse jump is five jump here one move here and then mouse just jumps i don't get way back did i misunderstand this oh they cannot jump over the wall i think i miss my tap okay that's not hard i think that's going to be too many states to 4 million it's going to time out for sure i can even try that if it somehow doesn't time limit i would sum it but i don't think there's no way this isn't time limit so then now i don't know how this is the game theory way of doing it because otherwise they just got stuck on loops can i cheat i reduce this by like 100 it's fast enough maybe okay because you can't jump over wars can you do some kind of funky proof maybe like just the crazy one is the one that loops all the way around so what's that would that look like well i have half an hour decided that i don't get it's fine maybe so then uh people like messaging me during this time i don't know how to turn it off on a mac i'm not gonna lie please stop messaging me okay oh my god even with it off it just keeps going i don't know how to turn this thing off can you turn off messenger i don't know if i could just mute okay so what's that two that's six seven eight nine ten dollars 636. this should be good enough right 20 is too weak but it's fast enough i don't know probably not but worth a shot hmm this is force no should be true oh wait no because of the cat chases after the first jump that's actually a good uh thing but let's just do two let's give it a try who knows that worse over time limit because i don't know how this helped otherwise oh wrong answer um i think this is similar to mine why is this force nice of them to give me that this test cases though the answer is one what does that what does one mean one means that uh oh so maybe this is the worst case so this is one two three four six seven 15 plus 9 24 plus another 9 is 33 oh it's 33 each so that's 70 maybe now i'm like trying to figure out what was the answer expected true okay well let's give it another go maybe too slow still but okay well i don't know if that's cheating but uh thanks for watching everybody uh hit the like button hit the subscribe button join me on discord and ask me questions about this problem or other problems uh have a good year and all that stuff and i will see you next problem bye-bye
Cat and Mouse II
fancy-sequence
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a `grid` of size `rows x cols`, where each element is a wall, floor, player (Cat, Mouse), or food. * Players are represented by the characters `'C'`(Cat)`,'M'`(Mouse). * Floors are represented by the character `'.'` and can be walked on. * Walls are represented by the character `'#'` and cannot be walked on. * Food is represented by the character `'F'` and can be walked on. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. Mouse and Cat play according to the following rules: * Mouse **moves first**, then they take turns to move. * During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the `grid`. * `catJump, mouseJump` are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. * Staying in the same position is allowed. * Mouse can jump over Cat. The game can end in 4 ways: * If Cat occupies the same position as Mouse, Cat wins. * If Cat reaches the food first, Cat wins. * If Mouse reaches the food first, Mouse wins. * If Mouse cannot get to the food within 1000 turns, Cat wins. Given a `rows x cols` matrix `grid` and two integers `catJump` and `mouseJump`, return `true` _if Mouse can win the game if both Cat and Mouse play optimally, otherwise return_ `false`. **Example 1:** **Input:** grid = \[ "####F ", "#C... ", "M.... "\], catJump = 1, mouseJump = 2 **Output:** true **Explanation:** Cat cannot catch Mouse on its turn nor can it get the food before Mouse. **Example 2:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 4 **Output:** true **Example 3:** **Input:** grid = \[ "M.C...F "\], catJump = 1, mouseJump = 3 **Output:** false **Constraints:** * `rows == grid.length` * `cols = grid[i].length` * `1 <= rows, cols <= 8` * `grid[i][j]` consist only of characters `'C'`, `'M'`, `'F'`, `'.'`, and `'#'`. * There is only one of each character `'C'`, `'M'`, and `'F'` in `grid`. * `1 <= catJump, mouseJump <= 8`
Use two arrays to save the cumulative multipliers at each time point and cumulative sums adjusted by the current multiplier. The function getIndex(idx) ask to the current value modulo 10^9+7. Use modular inverse and both arrays to calculate this value.
Math,Design,Segment Tree
Hard
null
1,920
Work in this area Ajay will have to That a [ That a [ That a Hello one and welcome to new video English video by going to discuss problem number 90 from the problem 000 agree here and Ichchadhari our in the middle of this From the name of the Laker to one point that and from the railway station duty reduce 2002 number of clans given till minus one ok ghee problem example2 m30 this which is ours this is our meaning and here 1000 here put our name whose name For top one, if we check then what will happen, then our today's question is if we check which row for answer one, what will happen in row one, so here we will put it in place of Then what we have to do is like we will keep then we will submit and 20 so see here what we will do here is our 1000 and soon here will be gone name shop names of three which instead of numbers of five don't threaten 12345 this If we do the fragrance, then when we see the answer ad here for Kapoor, then what is this ad of ours and set our normal number 420 1234, so here we subscribe one two three and lastly subscribe 504 and if we see 40 504 506 Like we give it a little bit that this is given to us as an example Hello, we are given to this 505 1234 Now we have to make our answer so first of all we have to answer here for answer off if we if ours is ours then ours these people 9990008057 These people should not set the name of 80 work as Saturday or will have to be removed from the name, what are the five elements for this option, so what will be our June 2012, so our which is here, which will be the essay on 323 324 323 C Media 2012 i.e. One Ho which will be the essay on 323 324 323 C Media 2012 i.e. One Ho which will be the essay on 323 324 323 C Media 2012 i.e. One Ho ka see this place for Toubro for 2014 Andha if we are 1234 then our 3232 appointed here for this ka this is ours so for this we will first of all appoint village approach loot first of all we will make this who false a which is this This is our size of salt pudding, its size and hello, it's fine, like this is ours, then where do we get our time from, we have been appointed president and now inside this, we will fold it at number eight and like if this follow is finished. Ours is ready, now we will check its time from time to time, which will be clear, okay if we talk about its space complexity, then Space Congress is taking such an express which has been a special one, it is taking the rising size of If he is taking our speed on the same side, then this is the problem. Subscribe, this is our code, first of all, I have taken it as per okay, I will enter it, first of all, I have taken the salt, subscribe this is another form of his name, Jhalar Slide Distribution, what should we do? We have to make a loop that come as soon as possible appoint appoint appoint someone inside it like we will finish the solution together and finish it like we will finish it appoint and subscribe your answer and what is the result and this is our success This fast Andhe Se and those who do Meghnad 3000 work subscribe time complexity of complexity notification for this problem and we do this paste, we do this, instead of making a new one, update the same rally, then what should we do? Here too, we have to make these changes, first of all we will take out our N which is the size of the people who subscribe our channel, after that we have to change the change here that when we go something like that here, then on this In such a change, the person should know which value is the first here, that is, we click here, share and with that, if we can come out with the final, then you can subscribe to our channel, so we are here that we will give value in every position. Take, if I say for the first position, then we can do something like this, name data is equal to 99, this is a small, we will multiply, number at i, we will multiply and what we will do in this, village amazon in this and we will take this as sentence. Okay, we will take this and as we get this, we will cut into it number 10 2012 three 500 600 800 to 1000 times unity is 0 which is our first element, hello what will it go and ours will go something like this if you for some After calculating, what will we do? Now let's see what we will do for them. * * * * * * We should have got Now let's see what we will do for them. * * * * * * We should have got Now let's see what we will do for them. * * * * * * We should have got that i means nine number set i, we should have got the answer in one of the times index, we should have got, so this is like we will divide it, so here we do, so we can type 06 here, so if For 2012, how much is this, how much do we want here, if from here we want what is the value that we don't want from here, we will divide the thirteenth, from the end, if we divide it like this, then we are getting two, so there two, this is today's If we want the value of what was already here we will have the valley. If we take the percentage but the cent end, then we will get the value, meaning if we take the turn of thirteen of those, this is its original divide divided by this. Do some work, if you subscribe, he can do it in any flat. Our Ghaghra Subscribe 1234 Naveen Said 5185 K0 12345 2014, if we divide the education and get it, then we will get six * 4 plus, which is original velvet seat six * 4 plus, which is original velvet seat six * 4 plus, which is original velvet seat 20123 andhe, adding us to this, he will make it 20%. Do that we get it 20%. Do that we get it 20%. Do that we get it and that is subscribe our channel that is our 0123 our complete * 90 hoga five yeh to jab aap 5.5 par cent end kya hoga five yeh to jab aap 5.5 par cent end kya hoga five yeh to jab aap 5.5 par cent end kya hoga 5th 6th thirty plus humko nikal naam set 20123 4000 traditional it nikalna original to We will do 14% it nikalna original to We will do 14% it nikalna original to We will do 14% so we will quickly if we want this here which one we will do then now what will we do for our Naan here we have into three plus tha na religion set here and we will get its original vegetable 22 % throw Hey, we will get the original vegetable 22 % throw Hey, we will get the original vegetable 22 % throw Hey, we will get the fourth because the map of 6042 is 1618 incomplete and if we want it, then we will finally divide it from terrorism, which will be our channel, this problem, we are here, we are an actress in the name, so here we are Here let's look for the solution for the time complexity of space and see that this is our Ghaghra Raj Kaam Hai Hua Tha Name of the set Name of the shop number Set I percent N A plus This should be the first institute Put thumbs in it Parents Please share this formula inside and after that we like our complete is finished then doctor and i20 and plus and we hate table and after that we will get this complete so let's see let's remove our old solution on our fearless this Only one thing is appointed, now we have to start a potato here, where from where to where, Chadana is equal to zero six transaction size and we will increment it by Ajay, time, what to do, we will make it equal to our name set inside it. For which thing we will remove it and into a which is our norms of name set, we will have to take it, okay and after that, like we have to add it here, okay, this is our Dhoop Beg like From where to where we will run this 0606 this is done till the end and that and inside that what we have to do is keep doing a sentiment and here what we have to do is equalize the house add salt and our potatoes now after that we will do our We will return this number. Ok, we will return it. Submit it and subscribe our result and this particular chapter note solution of youth and we used very less space than 3000 people, then you must have understood the solution and if you have found the solution. Samaj aaya toh like share this video with your friends and if you want to practice regular problems then you can join our channel thank you for watching my video
Build Array from Permutation
determine-color-of-a-chessboard-square
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** **Input:** nums = \[0,2,1,5,3,4\] **Output:** \[0,1,2,4,5,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[0\], nums\[2\], nums\[1\], nums\[5\], nums\[3\], nums\[4\]\] = \[0,1,2,4,5,3\] **Example 2:** **Input:** nums = \[5,0,1,2,3,4\] **Output:** \[4,5,0,1,2,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[5\], nums\[0\], nums\[1\], nums\[2\], nums\[3\], nums\[4\]\] = \[4,5,0,1,2,3\] **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < nums.length` * The elements in `nums` are **distinct**. **Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)?
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
Math,String
Easy
null
1,790
hi my name is david today we're going to do number one seven nine zero check if one string swap can make strings equal this is an easy level problem on the code and we're gonna solve it in javascript we're given a function that takes in two strings s1 and s2 and we want to return true or false if we can make a string swap and they've defined this swap as if you can swap at most one string swap on exactly one of the strings otherwise return false so for example we have this two strings here if we know that we can swap b and k just one swap they're equal so we return true and here we return false because it's impossible to make them equal and here is also another edge case where they're both already equal so no swaps so it says at most one string swap so it's zero swaps so it's still true so in order to solve this problem there's two things we need to check the first thing is that they have to have the same letters and the letters have to appear the same amount of times so they can be in a match because this is impossible because they don't have the same letters and the second thing we ought to do is create account for how many swaps there so we know that if there's only two positions different that's one swap and if it makes more than that we know we return false so the first thing we want to do is that we want to create a char array and this is a variable and this is a general strategy where we keep we create an array of 26 indexes and every time we see a letter it increments to that corresponding index value and then we also want to create a swap variable and that's going to keep track of how many swaps we're doing next we want to fill this chart array up so we create we loop through s1 and then we add the value to the corresponding char array and i'll show this in code this idea took me a while to grasp but i'll show you including make more sense and then so we got the char array filled up so now we have to loop through s2 and inside of this we want to see if it's inside of it if it's not inside of if this letter in s2 is not inside of it we return false knowing that it's possible condition if current the value inside char array and then is not we return false and then if it is else current value isn't it we decrement the value in charge array because the amount of times of it occurs matters as well and then also we can combine this to the other part is that we check the swap so if condition if current s current index value i'll just put in kind of code s1 i is equal to s2 does not equal to it this means we need a swap and then we have a last condition if swap is greater than 2. re-return false and now lastly if we make it through this we return true so the all these are conditions to make it return the second condition will check if it will make it return false and if it doesn't we return true and i also i had three different loops at first but i learned that we can just combine this one with this one so you'll be going a little bit twice so to create it to do it in code let char array equals new array that is 26 index long and we fill it starting with zero and we create this swap variable that swap and it starts off at zero and now we loop through s1 for that i equals zero i is less than s1 dot length i plus and inside of it we fill out this char array so that temp and this is what i'm going to add to the chart array we have to change it to chart code so the idea is that we get s1 so this gets the letter and we change it to the chart code and then we have to minus because it's hardcoded as a lot of more than just the letters and it's also only low case too so that shortens it a lot we got subtracted from the a and just kind of that general idea and we just copy this and then we want to fill this out up on the in the array so try array where we get that temp we just plus and i'll console log this so you have an idea so you can see it and make sure i get it right char alright you see so bank every the b we increment one here for the second this represents b this is a and k and so forth and now we want to loop through it again they're the same length so it doesn't matter but we can just do s2 for easier read i equals zero i is less than s2 dot length i plus and we do the same thing let 10 where we do s2 if this is equal to zero it means that it's not in it so we can't do this problem so return false else so it isn't it we want to decrement it as well to keep track of the count inside of to make sure that count matches and then we create the other condition the swap condition if s1 index i is equal to s2 index i doesn't equal to it we increment swap and then lastly if swap is greater than two we return false and it makes it through all this so we just return true and that's it great so do the time complexity for this time we're doing a loop through here two loops but they're the same ones they're not nested so it's oven and then the space complexity so this is sufficient because it's constant is a constant 26 variable this is constant so it's going to be over 1. so that is how you solve this problem thank you
Check if One String Swap Can Make Strings Equal
lowest-common-ancestor-of-a-binary-tree-iii
You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly one** of the strings._ Otherwise, return `false`. **Example 1:** **Input:** s1 = "bank ", s2 = "kanb " **Output:** true **Explanation:** For example, swap the first character with the last character of s2 to make "bank ". **Example 2:** **Input:** s1 = "attack ", s2 = "defend " **Output:** false **Explanation:** It is impossible to make them equal with one string swap. **Example 3:** **Input:** s1 = "kelb ", s2 = "kelb " **Output:** true **Explanation:** The two strings are already equal, so no string swap operation is required. **Constraints:** * `1 <= s1.length, s2.length <= 100` * `s1.length == s2.length` * `s1` and `s2` consist of only lowercase English letters.
Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA.
Hash Table,Tree,Binary Tree
Medium
235,236,1780,1816
344
Jhal Hello Everyone Welcome To My Channel Police Question Is Reverse Entry To Computer Channel Please subscribe this Channel Notification On This Channel Indian Tech Help You With Your Infidelity The Question Is Right The Function Demonstration In Its Ring Is Given By Adding Actors That Both Tape Express For Another You Must For This Modifying Input Tray Correction System Printable Characters Is A Flu Example Born Again With Fellow Indian Outfit Videos And Example Number To The Giver Is Not And Furious Dahan Of Women Is Not Let's Move To 9 Let's See How They Can solve this question up to date will see the code is high tech na are obtained that and Neetu systematic symptoms minute yaar ki vijendra yudhishthir always one is used in battles absolutely inbuilt reverse on yaar that a can simply is or prevails that in it Good To Arrangement Reverse Format Of Vihar Incident Solve This Problem S E Will Tell Ka MP3 Same Science That Target Person All And Will Start From The End Of The Governor D That In These Girls Admit Temp That Angry Will Start Feeling And Temperature For The Beginning First Lutiya mein tel put and tagged aa tere ko calendar blue and english with ki film ki and will get all reverse format and vaikuntha but in this case 10 complexity of express time table ki nav the question is can they perform this in english improved toss complexity Will be over that pant answer is yes Fort Williams 2.0 52.21 Starting from 52.21 Starting from 52.21 Starting from ki and ki in one form happened pure first point at this point in guest ki intact roti length of ki sexual article - work ki sexual article - work ki sexual article - work select edwin limit i left leg limit tract tomorrow Subha to point left android nor will you take value a the world this the left and right that when misal the mid point is solved and is high voltage dahej ka price point se zap both of you and wickets vs eng in the time left indices left end Right index and values ​​for not develop and values ​​for not develop and values ​​for not develop a co an interview with writing axis pe ki sabhi welcome ho anti veer kam hair hai shri navdurga in movies left point to right 51512 alex 500ml feint welcome to me nine idols paint ki selwyn kam hai two hello friends Welcome To Your Knowledge Navi Mumbai Life Mein Tubelight Android Phone Tablet Samaai Last Point Is Se Zor Again Will Spoil Were That Login Me Left With Comment Light Bill Comment Ko Again Will Destroy 06 Name Electronic Comment Oye Yaar I Don't Have Welcome A Taboo Innovative That 10th 219 Alex Kontouris Comment Pati Android Comment Live Se Jaayengi Jhaal Normal Life Interview Amazing Site Will Commit And That Agnivesh Now And Bye Me Tension Will Stop Hair y55l Mode Hain Ride Point To The Length Of This Point And This Condition Will Not Satisfied E Tomorrow Morning Stopping Edit NCI Will Have 200 Beds Blood Bottles During This Time Elections Will Be A How To Open Time End Of Birth Place That Previous Dominate In English Sentence Complexities Of Beneficial As Well As Malefic And Back To Characters And What Is Equal To The Time Complexities How to Open Sudhir Vipin Sood This Question Let's Move to What is the Work Number for Significant to be Replicated Interviewer The Giver - 1 Interviewer The Giver - 1 Interviewer The Giver - 1 Bluetooth Setting Mobile Popular Left and Right Painting of Velvet Ka But Text and Taken Away Their Rights and Wasted with Ours Right and left after clean sweep in love letter side me left to right and right the volume to plus to subscribe to ki sohrai summit me kaur jhaal edit ko text message solution for this problem love you can find the ko dinner description give this video Was helpful to you please give them when thank you so much for watching our video please do not forget to subscribe
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. **Example 1:** **Input:** s = \["h","e","l","l","o"\] **Output:** \["o","l","l","e","h"\] **Example 2:** **Input:** s = \["H","a","n","n","a","h"\] **Output:** \["h","a","n","n","a","H"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
Two Pointers,String,Recursion
Easy
345,541
64
Tiger, in this video, we will find the solution to this in minimum questions. We have the complete matrix in front of us. Sorry, inside the maths, that Bigg Boss has been given. Friends, you will have to pay to fix it and you have to carry the topless button. There are many of you. Dreams are quite difficult, so you can use any number of buses and I too am of course you can go like this but very probably, you have to tell me the best route which will cost the least money. What will we do inside this, will we make stories, so this is this time, this is how much time and a, we breathe kumkum and tell that we will keep the empty land twice, so close, one is coming original and one is whatever we have got. Okay yes, this is coming. That I have found a Jaunpur whose name is original, whose name is we will make BP video, so if I make it empty then it will remain mine, all my centers have also initially fallen on vegetables, all of you have been examined, so what do we do? We have to do this and our difficult stage was that till the time I find and delete it, I will stitch it in the thoughts about our interest in the tablet, we will get information and storage and its meaning, then we had to think, well, solving the direction problem, family problem. If it used to be, then while I am deleting these cells, you should consider meeting the DP person that if you have recharged the phone, then I will tell you what is available at any place, what would you have read about the cheapest routes to know the destination from there. The price of Rs. 1000 must be lying there, on the other side, I am telling you that what is cooked in the serial, this is the best way to go to Sheshan, how much money will it cost, there is a shorter way than this, which will cost less money, how much money will it cost, that 40 You must have read what you must have read on this channel. Don't know how many people live here. From here, who knows how many people live here. The best thing that is proposed inside them is how much money do I make on this. It will start here if I make a big sign. So now we cover it, no problem, find out about their love, where is the small problem, the big role is, my face is not hidden, that going from here to here will cost the least amount, that there would be happy duty here, even if it was ₹1, that there would be happy duty here, even if it was ₹1, that there would be happy duty here, even if it was ₹1, it would be far away. But even if it is there, it will come from here, if it seems to be on Sardar, then the smallest compliance is here, if you send the biggest party then it will come from here, it is cheaper and if it comes from here and most of the accidents happen, then the smallest one is justice. If you come to the poll related to this then the problem will be from bottom to top. We will travel round the world while Yuvraj will do Swiss roll. If we try again then I will give it. Okay, now the scheme will be applicable that it will come from here, it is cheaper and at the same time. It is costing two rupees, so if you are from here, then you will become tied to here, see, it cannot be increased or taken and beyond this, two more rupees are spent, so there is an option, see, I am yours, it is a simple thing, you think country. If we want to go, then we can go to as many shops as we can, let's say we can buy a piece from here, we can buy water for ₹ 1 from here and we from here, we can buy water for ₹ 1 from here and we from here, we can buy water for ₹ 1 from here and we can buy the market from here and we spend minimum amount of money. Okay, so whatever you want. Go to the place and there is another one too in this dry luck will shine so retired understands this so I am giving it to you also but pay attention that if we assume this then I can go to dayan to go to the source and destination and in going there you have to From the airport and you can go to I-2, and you can go to I-2, and you can go to I-2, our blood pressure is wide spread when we go there and our blood pressure can be 120 when we go there, or we can go to Delhi from I-20 right there, we 120 when we go there, or we can go to Delhi from I-20 right there, we 120 when we go there, or we can go to Delhi from I-20 right there, we can drink alcohol in DJ joint in Afridi If we do then where would you like to go, you would like it the most I hope you would like to go there Come make love darling, one of your festivals is at the root and there are quiet s from there You will improve at the place where both of these are minimum. It will happen that we will get 6 viruses and there will be a laddu fight and this will be our answer. So much money will be spent that I will listen to Haridwar. See, as brother talks about going from Chandigarh to Delhi, Chandigarh is there, we have to go to Delhi, from Chandigarh we assume that we can go to Yamunanagar. In this case, we can go to Ambala, let's assume and the song comes, ' comes, ' comes, ' Brother, it doesn't come, we can go to Saharanpur. However, while going to Yamunanagar, we take our Ghaghra as the owner, from Yamunanagar to Delhi, half of it is from now and from Saharanpur to Delhi. If it is with, then we will take it from here, and if it is made from here, then we will take it. Okay, so I hope that you have understood the basic romance, so brother, this is a preposition, only the dead and young can go to the call center quickly in the morning. If you are paying from above there then it will be 8 rupees for this channel and further from the telescope, it will be 8 rupees. If you picked it up from here, you will get Durga Sun Tan from here. Now do n't understand this trick, General Mutual, it will be paid within a couple of rupees, so I understand. If it doesn't come then that current from death will come here where if the question problem is solved in this program then it is better then it will be fine with the money always through this YouTube because when you start understanding later then you will be tied down from here. You can go here. Only one can go and from here it is costing you ₹10. one can go and from here it is costing you ₹10. one can go and from here it is costing you ₹10. From here it is costing globally and in this year if you have your own flight then it has to be in zoo or airport. Now we will focus on this. From here only go here. We will go down from there is one here, now from here we will do it here near you and we can also go down there, sweets 2025, this romance in bed, 25 friends, eyes on this, now let's talk about here. At the most, one option can go down, so we will remove it from there and then listen to standing here, being famous, this is the first place where there is an option to understand something different, from here we can also bring it here. If you go from here then we will take 11. If you go from here, then if they came here from here, they spend these days and come here, then we can also go from here to here and come down here. If he goes then the promise is Rs 1010 per ki, now if we talk about it here then look, he is going to be hit on the round, he can reach here in the round, he passes both the legs here, if he reached here for ₹ 2, then he will be hit 11 here for ₹ 2, then he will be hit 11 here for ₹ 2, then he will be hit 11 in the race, he is needed here because if he will be hit He will milk and 65 and will go to the place from where the money is taken. These settings are 216 that now I have studied in school. Three value in these are in Shift Industries Ltd. Indore. Miding is in miding 523. If you subscribe here one by one, here you are in these temples. Please subscribe the page because this means that subscribe this channel, subscribe to know and this indicates that if you want to do this, then we will discuss on three or 18 because it will be cheaper from here, then you can cut it from here, whose is it, why is this center? That it was damaged, we could reach here by spending three rupees and from here, TV-18 is available, we reach here by spending three rupees and from here, TV-18 is available, we reach here by spending three rupees and from here, TV-18 is available, we could tie it to China too, but from here, the family members would prefer to spend three rupees in the middle, and from here, three will move away, if we breathe. The combination of these two is the sleep of victory for the memory people here, the meeting of these two plus sure, the main plus one of these two, it is clear that it is just eight, with it or not, 1719 flask 680, I have seen these two 3130 1000 stories 90 Addison electronic plus point road 5 minutes 1268 fill you are so full so now just comment below here both my 2019 plus accessibility then I 000000 this I think oneplus 3 to 4 minutes cornflour plus on the back is the same on both sides that is not the difference Pada Twentyeight 409 Plus Vanshmani otherwise you will be a viewer that yes, from here there is no problem on either side, you can go down here 225 27 Recipe of both 464 days I have 0005 This is my story for class ninth from 1000 This is two so below Go 90 4000 I folded it for 20 a plus six 06 - one five plus minus plus a plus six 06 - one five plus minus plus a plus six 06 - one five plus minus one six plus forces will subscribe, almond or hard in to-do so we will make our own hard in to-do so we will make our own hard in to-do so we will make our own channel which is Ajay's and we have input go How many days are there, how many columns are there for Ajay that I had made him my ideal, what resolutions are coming that I have looted and taken input in it, Ajay has been called, I have found this in the report, then I called Deepika in the morning itself. Made it and here is my Deepika, it should be as big as it is, it should be as big as mine and I was making this, I can say in giant and semi, okay, I will make it from the banks to do it like this, we are you that Now it will be seen that we will roll it from here to there, from bottom to top, they enter equal to BP dot length - 120 - - - 10 - I equal to BP dot length - 120 - - - 10 - I equal to BP dot length - 120 - - - 10 - I like the good ones as I say, separate them from the last, do, we are the last. They were the last, what do we do in the last row, just prepare this bill for the next rally, here is 10 Ujjain, when 1981 is out, then there is an option to give inch plus minus point questions, just go down from the last ones. If it is like it was broken here, Khurram Plus 98100 can live above and below it, then center sites one to two, now what happens in the rest of the area, India is in a plight in the rest of the area, like if you think about here, then check from here to here. It will be small, it will have to be added here, okay, so I will look at the things carefully in four parts, now this one that has come is on one of our teams and its use is also simple, so it means we are in the last voice mail Celsius, that is, just for planting team. But if we are then we are in the last row, this is our column on this team, the last is the last problem of this restaurant style Meghwal, if you are in the last then you simply cannot go, if you are in the last only and only then from where you get so much money. From here you will find that our recipe is in the mosque, how much money will it cost from there, it is lying in the middle and how much money will it cost on our spot, it is lying there, what is it in the vertical case, I am a I can go to that place, which is that place? Doppler Shivam Jain, so held, how much money will it cost, I got it in the DP, I plus tells the reason, I plus one happily, which is the best, how much money will it cost, it is lying in the DP. And how much money will it cost me to go there, Arya is lying in the size. Okay, now if you have two options, you can go, then you will have to take Clash Of The Amazing, where can you go and in that, Ajay is confused that the last 1468 Ud input ma'am do it small 23114 subscribe to also there is no damage submit this that they bowl correct answer commissioners have to understand must have enjoyed na
Minimum Path Sum
minimum-path-sum
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. **Note:** You can only move either down or right at any point in time. **Example 1:** **Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\] **Output:** 7 **Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum. **Example 2:** **Input:** grid = \[\[1,2,3\],\[4,5,6\]\] **Output:** 12 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 200` * `0 <= grid[i][j] <= 100`
null
Array,Dynamic Programming,Matrix
Medium
62,174,741,2067,2192